PostgreSQL 全文检索

PostgreSQL支持全文检索,但是中文的全文检索需要安装zhparser插件。阿里云上购买的PostgreSQL,某些版本不支持,升级到14最新的小版本,或者15才支持。

核心函数

PostgreSQL的全文检索,主要是用to_tsvector函数进行分词,to_tsquery进行查询关键字的拼凑。

1
select to_tsvector('It''s never too old to learn.') @@ to_tsquery('old & learn')

SQL中含单引号时,可以如上述代码写两个单引号,也可以用$$来代替外围的单引号

1
select to_tsvector($$It's never too old to learn.$$) @@ to_tsquery('old & learn')

创建全文检索字段

可以专门创建一个字段来进行全文检索,字段的类型设置为tsvertor:

1
2
alter table your_table 
add column your_text_column tsvector;

在更新数据时,需要用to_tsvertor进行分词:

1
2
3
update your_table 
set your_text_column=to_tsvertor('some new text')
where id=...

全文检索的索引

全文检索的索引是gin,倒排索引:

1
create index idx_fulltext on your_table using gin(your_text_column)

也可以对不是tsvector类型的字段用to_tsvector函数转换后来索引:

1
create index idx_fulltext on your_table using gin(to_tsvector(field_1),to_tsvector(field_2))

所以不用单独建立字段来进行全文检索,直接建索引就可以了
不知道上述代码在多个字段上建了索引,能否在field1上检索时指定field2里的词?