全文检索(FTS)是 PG 内置的搜索引擎:分词、匹配、按相关度排序。本文讲英文 FTS 与中文分词方案,结尾附文章搜索小案例。
一、核心概念
tsvector:文档的"词位集合"(分词后的词列表)
tsquery :查询的"词条"(and/or/not 组合)
@@ :匹配运算符
ts_rank :相关度评分
二、基本用法
SELECT to_tsvector('english', 'The quick brown fox jumps');
-- 'brown':3 'fox':4 'jump':5 'quick':2 (去停用词、词形还原)
SELECT * FROM articles
WHERE to_tsvector('english', content) @@ to_tsquery('english', 'quick & fox');
-- 权重排序
SELECT title, ts_rank(to_tsvector(content), query) AS rank
FROM articles, to_tsquery('quick') query
WHERE to_tsvector(content) @@ query
ORDER BY rank DESC;
三、查询语法
to_tsquery('quick & fox') -- AND
to_tsquery('quick | slow') -- OR
to_tsquery('quick & !fox') -- NOT
to_tsquery('quick <-> fox') -- 相邻(短语)
websearch_to_tsquery('quick "brown fox" -lazy')
-- 用户友好的搜索语法(支持引号短语、-排除)—— PG11+
四、持久化列与 GIN 索引
ALTER TABLE articles ADD COLUMN tsv tsvector;
UPDATE articles SET tsv = to_tsvector('english', coalesce(title,'') || ' ' || content);
CREATE INDEX idx_articles_tsv ON articles USING gin (tsv);
-- 触发器自动更新 tsv(见触发器篇)
SELECT * FROM articles WHERE tsv @@ websearch_to_tsquery('postgresql index')
ORDER BY ts_rank(tsv, websearch_to_tsquery('postgresql index')) DESC;
五、中文分词(重点)
默认 to_tsvector 不懂中文(整句当一个词)
方案:
1. pg_jieba 扩展(结巴分词移植,推荐):to_tsvector('jieba', content)
2. zhparser 扩展(简单配置)
3. 应用层分词后存数组(simpl 词典)
-- zhparser 示例
CREATE EXTENSION zhparser;
CREATE TEXT SEARCH CONFIGURATION chinese (PARSER = zhparser);
ALTER TEXT SEARCH CONFIGURATION chinese ADD MAPPING FOR n,v,a WITH simple;
SELECT to_tsvector('chinese', '数据库性能优化实战');
-- '优化':5 '实战':6 '性能':4 '数据库':1,3
六、小案例:文章搜索接口
CREATE TABLE articles (
id SERIAL PRIMARY KEY, title TEXT, content TEXT,
tsv tsvector
);
CREATE INDEX idx_articles_tsv ON articles USING gin (tsv);
-- 触发器维护 tsv(标题权重 A > 正文 B)
UPDATE articles SET tsv =
setweight(to_tsvector('chinese', coalesce(title,'')), 'A') ||
setweight(to_tsvector('chinese', coalesce(content,'')), 'B');
-- 搜索:支持引号短语与排除词
SELECT title,
ts_rank(tsv, q, 32) AS score,
ts_headline('chinese', content, q,
'StartSel=<b>, StopSel=</b>, MaxWords=35') AS 摘要高亮
FROM articles, websearch_to_tsquery('chinese', '"性能优化" -缓存') q
WHERE tsv @@ q
ORDER BY score DESC
LIMIT 10;
setweight 加权标题、ts_headline 生成高亮摘要、websearch 兼容用户输入 —— 搜索接口三件套。
七、总结
tsvector 分词 + tsquery 查询 + @@ 匹配 + ts_rank 排序;tsv 列 + GIN 索引保性能;中文上 zhparser/pg_jieba;ts_headline 出摘要高亮。