我刚刚开始使用 postgreSQL 进行模糊文本匹配。我有两列:job_title
和 company_name
。
典型的全文搜索会将job_title
和company_name
连接起来,然后根据单个排名返回搜索文本结果。
但是,在我的情况下,同等对待两列中的文本匹配可能会出现问题。例如,Google Co.
的 Search Engineer
不应与 Engineer Co.
的 Google Search
排名相同
我知道我可以为每一列分配不同的权重。然而,我没有理由认为其中一个比其他更重要。
如何分别将我的关键字与每个列进行匹配,并返回每个关键字的一些“匹配分数”?
类似于:
Jobs.where("(to_tsvector('english', position) @@ plainto_tsquery(:q)) AND
(to_tsvector('english',company) @@ plainto_tsquery(:q))", q: "Search Engineer", q: "Google")
最佳答案
正如您所指出的,您可以连接 tsvector:
# select to_tsvector('job description') ||
to_tsvector('company as keyword') ||
to_tsvector('job description as body') as vector;
vector
-----------------------------------------------------------
'bodi':9 'compani':3 'descript':2,7 'job':1,6 'keyword':5
(1 row)
您还可以为它们分配权重:
# select (setweight(to_tsvector('job description'), 'A') ||
setweight(to_tsvector('company as keyword'), 'B') ||
setweight(to_tsvector('job description as body'), 'D')) as vector;
vector
---------------------------------------------------------------
'bodi':9 'compani':3B 'descript':2A,7 'job':1A,6 'keyword':5B
(1 row)
您还可以使用ts_rank_cd()
。特别是,您可以更改分数标准化的方式。
http://www.postgresql.org/docs/current/static/textsearch-controls.html
就您而言,您似乎想组合两个单独的查询。一个丑陋但可能足够的解决方案可能如下所示:
select sum(rank) as rank, ...
from (
select ...
union all
select ...
) as sub
group by ...
order by sum(rank) desc
limit 10
如您所见,它不太漂亮。它也是聚合潜在的大量匹配行的大道。恕我直言,如果需要的话,您最好坚持使用内置的 tsvector 算法并调整权重。
关于ruby-on-rails - 使用 PostgreSQL 在多列中进行全文搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17355907/