在没有索引的情况下也可以执行全文检索,通过函数 to_tsvector 与 to_tsquery 在查询时即时处理:
SELECT title
FROM pgweb
WHERE to_tsvector('english', body) @@ to_tsquery('english', 'friend');
为了加速全文检索,应当建立 GIN 倒排索引:
CREATE INDEX pgweb_idx ON pgweb USING GIN (to_tsvector('english', body));
在表达式索引中必须使用显式指定了配置名称的双参数版本 to_tsvector,以确保索引内容绝对不受全局默认配置变更的干扰。
更为推荐的工程做法是在表中添加一个独立的 tsvector 存储型生成列,并在此列上建立常规 GIN 索引:
ALTER TABLE pgweb
ADD COLUMN textsearchable_index_col tsvector
GENERATED ALWAYS AS (to_tsvector('english', coalesce(title, '') || ' ' || coalesce(body, ''))) STORED;
CREATE INDEX textsearch_idx ON pgweb USING GIN (textsearchable_index_col);
随后即可直接在生成的列上发起极速检索:
SELECT title
FROM pgweb
WHERE textsearchable_index_col @@ to_tsquery('create & table')
ORDER BY last_mod_date DESC
LIMIT 10;