简体   繁体   English

Postgres全文搜索:如何在多个字段中搜索多个单词?

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

i'm using for the first time Postgresql and i'm trying to create a search engine in my website. 我是第一次使用Postgresql,并且试图在我的网站中创建一个搜索引擎。 i have this table: 我有这张桌子:

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

Then i created an index for every field of the table (is this the right way? Or maybe i can create one index for all fields?): 然后我为表的每个字段创建了一个索引(这是正确的方法吗?或者我可以为所有字段创建一个索引?):

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));

Now, what is the SQL query if i want to search one word in every index? 现在,如果我想在每个索引中搜索一个单词,SQL查询是什么?

I tried this and it works: 我试过了,它有效:

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')

Does exist a better way to do the same? 是否存在更好的方法来做到这一点? Can i search to_tsquery into multiple to_tsvector ? 我可以将to_tsquery搜索成多个to_tsvector吗? A friend of mine suggests a solution, but it is for MySQL database: 我的一个朋友提出了一个解决方案,但这是针对MySQL数据库的:

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

What is the solution for Postgresql? Postgresql的解决方案是什么?

In addition, can i search multiple to_tsquery into multiple to_tsvector ? 另外,我可以将多个to_tsquery搜索成多个to_tsvector吗? what is the SQL query if i want to search two words or more than one word? 如果我要搜索两个或多个单词,SQL查询是什么? Can i just pass "two words" to $word from PHP? 我可以直接从PHP向$ word传递“两个单词”吗? If i can, how does it work? 如果可以,它如何工作? Does it search for first word AND second one or first word OR second one? 它会搜索第一个单词和第二个单词还是第一个单词或第二个单词?

It looks like what you want is, in fact to search the concatenation of all those fields. 看起来您想要的实际上是搜索所有这些字段的串联。

You could build a query doing exactly this 您可以完全这样做来建立查询

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

and build an index on the exact same computation: 并在完全相同的计算上建立索引:

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

Don't forget to use coalesce on columns accepting NULL values. 不要忘记在接受NULL值的列上使用coalesce

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM