只匹配Postgres全文搜索中的一些单词

时间:2016-02-14 11:46:27

标签: postgresql full-text-search postgresql-9.1

我有兴趣使用postgres作为我正在开发的网站的搜索引擎,但是当匹配ts_query和ts_vector类型时,postgres似乎非常严格。如果ts_vector不包含查询中的所有项目,则匹配将被拒绝。

例如,我希望查询' Stack Overflow代码'匹配Stack Overflow站点摘要,但它并不是因为单词' code'并不存在,即使' Stack'和'溢出'是

SELECT 
to_tsvector('Stack Overflow is a question and answer site for professional and enthusiast programmers. It''s built and run by you as part of the Stack Exchange network of Q&A sites. With your help, we''re working together to build a library of detailed answers to every question about programming.')
@@ 
plainto_tsquery('english', 'Stack Overflow code')

返回:

false

在我的用例中,我对完全匹配不感兴趣,因为用户将使用它来搜索网站。

当只有部分查询在文档中时,是否可以将某些内容计为匹配?

1 个答案:

答案 0 :(得分:3)

那是因为plainto_tsquery将字符串切成单独的词位并放入& (AND)他们之间的运营商。这意味着它匹配所有单词。

如果你想要| (OR)运算符,您需要编写自己的“解析器”。例如,您可以使用' '

替换所有出现的'|'
SELECT 
to_tsvector('Stack Overflow is a question and answer site for professional and enthusiast programmers. It''s built and run by you as part of the Stack Exchange network of Q&A sites. With your help, we''re working together to build a library of detailed answers to every question about programming.')
@@ 
to_tsquery('english', replace('Stack Overflow Code', ' ' , '|'));