Postgres全文搜索:如何在多个字段中搜索多个单词?
Postgres full text search: how to search multiple words in multiple fields?
我是第一次使用 Postgresql,我正在尝试在我的网站上创建一个搜索引擎。我有这个 table:
CREATE TABLE shop (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
address TEXT NOT NULL,
city TEXT NOT NULL
);
然后我为 table 的每个字段创建了一个索引(这是正确的方法吗?或者我可以为所有字段创建一个索引?):
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 查询是什么?我可以将 "two words" 从 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
。
我是第一次使用 Postgresql,我正在尝试在我的网站上创建一个搜索引擎。我有这个 table:
CREATE TABLE shop (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
address TEXT NOT NULL,
city TEXT NOT NULL
);
然后我为 table 的每个字段创建了一个索引(这是正确的方法吗?或者我可以为所有字段创建一个索引?):
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 查询是什么?我可以将 "two words" 从 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
。