全文检索
PostgreSQL 内置全文检索能力,可以将文本转换为可搜索的 tsvector,并通过 tsquery 执行关键词匹配和排序。
全文检索适合文章、商品、工单、知识库等文本搜索场景。如果需要语义相似度召回,可以结合 pgvector。
基础查询
可以直接在查询中使用 to_tsvector 和 plainto_tsquery。
select id, title
from public.articles
where to_tsvector('simple', title || ' ' || content)
@@ plainto_tsquery('simple', 'cloudbase database');
simple 配置不做复杂语言处理,适合英文、标识符或已分词文本。中文搜索通常需要结合业务侧分词或其他检索方案。
使用生成列
频繁搜索时,建议将全文检索向量保存为生成列,并创建 GIN 索引。
create table public.articles (
id bigint generated by default as identity primary key,
title text not null,
content text not null,
search_vector tsvector generated always as (
to_tsvector('simple', coalesce(title, '') || ' ' || coalesce(content, ''))
) stored
);
create index articles_search_vector_idx
on public.articles
using gin (search_vector);
查询时直接使用 search_vector。
select id, title
from public.articles
where search_vector @@ plainto_tsquery('simple', 'cloudbase');
搜索排序
可以使用 ts_rank 对搜索结果排序。
select
id,
title,
ts_rank(search_vector, query) as rank
from public.articles, plainto_tsquery('simple', 'cloudbase database') query
where search_vector @@ query
order by rank desc
limit 20;
搜索高亮
ts_headline 可以生成带高亮标记的片段。
select
id,
title,
ts_headline('simple', content, plainto_tsquery('simple', 'database')) as snippet
from public.articles
where search_vector @@ plainto_tsquery('simple', 'database');
与模糊搜索和向量检索的 取舍
| 能力 | 适合场景 |
|---|---|
| 全文检索 | 关键词搜索、排序、高亮 |
pg_trgm | 短文本模糊匹配、拼写相近搜索 |
pgvector | 语义相似度、RAG 召回 |
实际业务中可以组合使用。例如先按租户和状态过滤,再做全文检索,最后按相关度排序。