簡體   English   中英

Postgres全文搜索:如何在多個字段中搜索多個單詞?

[英]Postgres full text search: how to search multiple words in multiple fields?

我是第一次使用Postgresql,並且試圖在我的網站中創建一個搜索引擎。 我有這張桌子:

CREATE TABLE shop (
  id SERIAL PRIMARY KEY,
  name TEXT NOT NULL,
  description TEXT,
  address TEXT NOT NULL,
  city TEXT NOT NULL
);

然后我為表的每個字段創建了一個索引(這是正確的方法嗎?或者我可以為所有字段創建一個索引?):

CREATE INDEX shop_name_fts ON shop USING gin(to_tsvector('italian', name));
CREATE INDEX shop_desc_fts ON shop USING gin(to_tsvector('italian', description));
CREATE INDEX shop_addr_fts ON shop USING gin(to_tsvector('italian', address));
CREATE INDEX shop_city_fts ON shop USING gin(to_tsvector('italian', city));

現在,如果我想在每個索引中搜索一個單詞,SQL查詢是什么?

我試過了,它有效:

SELECT id FROM shop WHERE to_tsvector(name) @@ to_tsquery('$word') OR
                          to_tsvector(description) @@ to_tsquery('$word') OR 
                          to_tsvector(address) @@ to_tsquery('$word') OR 
                          to_tsvector(city) @@ to_tsquery('$word')

是否存在更好的方法來做到這一點? 我可以將to_tsquery搜索成多個to_tsvector嗎? 我的一個朋友提出了一個解決方案,但這是針對MySQL數據庫的:

SELECT * FROM shop WHERE MATCH(name, description, address, city) AGAINST('$word')

Postgresql的解決方案是什么?

另外,我可以將多個to_tsquery搜索成多個to_tsvector嗎? 如果我要搜索兩個或多個單詞,SQL查詢是什么? 我可以直接從PHP向$ word傳遞“兩個單詞”嗎? 如果可以,它如何工作? 它會搜索第一個單詞和第二個單詞還是第一個單詞或第二個單詞?

看起來您想要的實際上是搜索所有這些字段的串聯。

您可以完全這樣做來建立查詢

... where to_tsvector('italian', name||' '||coalesce(decription,'')...) @@ to_tsquery('$word')

並在完全相同的計算上建立索引:

create index your_index on shop
using GIN(to_tsvector('italian',name||' '||coalesce(decription,'')...))

不要忘記在接受NULL值的列上使用coalesce

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM