继这个答案后,我想知道使用PostgreSQL的内置全文搜索的最佳方法是,如果我想按等级排序,并限制只匹配查询.
让我们假设一个非常简单的表.
CREATE TABLE pictures (
id SERIAL PRIMARY KEY,
title varchar(300),
...
)
Run Code Online (Sandbox Code Playgroud)
管他呢.现在我想搜索该title字段.首先我创建一个索引:
CREATE INDEX pictures_title ON pictures
USING gin(to_tsvector('english', title));
Run Code Online (Sandbox Code Playgroud)
现在我想搜索'small dog'.这有效:
SELECT pictures.id,
ts_rank_cd(
to_tsvector('english', pictures.title), 'small dog'
) AS score
FROM pictures
ORDER BY score DESC
Run Code Online (Sandbox Code Playgroud)
但我真正想要的是:
SELECT pictures.id,
ts_rank_cd(
to_tsvector('english', pictures.title), to_tsquery('small dog')
) AS score
FROM pictures
WHERE to_tsvector('english', pictures.title) @@ to_tsquery('small dog')
ORDER BY score DESC
Run Code Online (Sandbox Code Playgroud)
或者这个(不起作用 - 不能score在WHERE条款中使用):
SELECT …Run Code Online (Sandbox Code Playgroud)