基本文本匹配

openGauss的全文检索基于匹配算子@@,当一个tsvector(document)匹配到一个tsquery(query)时,则返回true。其中,tsvector(document)和tsquery(query)两种数据类型可以任意排序。

openGauss=# SELECT 'a fat cat sat on a mat and ate a fat rat'::tsvector @@ 'cat & rat'::tsquery AS RESULT;
 result
----------
 t
(1 row)
openGauss=# SELECT 'fat & cow'::tsquery @@ 'a fat cat sat on a mat and ate a fat rat'::tsvector AS RESULT;
 result
----------
 f
(1 row) 

正如上面例子表明,tsquery不仅是文本,且比tsvector包含的要多。tsquery包含已经标注化为词条的搜索词,同时可能是使用AND、OR、或NOT操作符连接的多个术语。详细请参见文本搜索类型。函数to_tsquery和plainto_tsquery对于将用户书写文本转换成适合的tsquery是非常有用的,比如将文本中的词标准化。类似地,to_tsvector用于解析和标准化文档字符串。因此,实际中文本搜索匹配看起来更像这样:

openGauss=# SELECT to_tsvector('fat cats ate fat rats') @@ to_tsquery('fat & rat') AS RESULT;
result
----------
 t
(1 row)

需要注意的是,下面这种方式是不可行的:

openGauss=# SELECT 'fat cats ate fat rats'::tsvector @@ to_tsquery('fat & rat')AS RESULT;
result
----------
 f
(1 row)

由于tsvector没有对rats进行标准化,所以rats不匹配rat。

@@操作符也支持text输入,允许一个文本字符串的显示转换为tsvector或者在简单情况下忽略tsquery。可用形式是:

tsvector @@ tsquery
tsquery  @@ tsvector
text @@ tsquery
text @@ text

我们已经看到了前面两种,形式text @@ tsquery等价于to_tsvector(text) @@ tsquery,而text @@ text等价于to_tsvector(text) @@ plainto_tsquery(text)。

意见反馈
编组 3备份
openGauss 2024-03-19 00:49:40
取消