繁体   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