jsonb_to_tsvector() 是一个系统函数,用于将 jsonb 文档中的项转换为 tsvector 词元。单词将根据指定的或默认的文本搜索配置进行规范化。
jsonb_to_tsvector() 已在 PostgreSQL 11 中添加。
用法
jsonb_to_tsvector ( [configregconfig, ]documentjsonb,filterjsonb) →tsvector
filter 是一个 jsonb 值或数组,其中包含一个或多个(如果是数组)以下关键字:
"string"(包含所有字符串值)"numeric"(包含所有数值)"boolean"(包含所有布尔值)"key"(包含所有键)"all"(包含以上所有)
"all" 将覆盖任何其他值。
变更历史
- PostgreSQL 11
- 已添加(提交 1c1791e0)
示例
jsonb_to_tsvector() 的基本用法示例
postgres=# SELECT jsonb_to_tsvector('{"a": "The Quick Brown Fox",
"b": "Jumps Over The Lazy Dog"}'::jsonb,
'["string"]');
jsonb_to_tsvector
--------------------------------------------------------
'brown':3 'dog':10 'fox':4 'jump':6 'lazi':9 'quick':2
(1 row)
在 filter 中包含 JSONB 数组键
postgres=# SELECT jsonb_to_tsvector('{"vulpes": "The Quick Brown Fox",
"canine": "Jumps Over The Lazy Dog"}'::jsonb,
'["key", "string"]');
jsonb_to_tsvector
-----------------------------------------------------------------------------
'brown':5 'canin':8 'dog':14 'fox':6 'jump':10 'lazi':13 'quick':4 'vulp':1
(1 row)
覆盖默认的文本搜索配置
postgres=# SELECT jsonb_to_tsvector('simple',
'{"a": "The Quick Brown Fox",
"b": "Jumps Over The Lazy Dog"}'::jsonb,
'["numeric","all"]');
jsonb_to_tsvector
--------------------------------------------------------------------------------------------
'a':1 'b':8 'brown':5 'dog':14 'fox':6 'jumps':10 'lazy':13 'over':11 'quick':4 'the':3,12
(1 row)
如果没有任何值与 filter 匹配,或者 filter 为空,则返回一个零长度的 tsvector。
postgres=# SELECT length(jsonb_to_tsvector('{"a": "The Quick Brown Fox",
"b": "Jumps Over The Lazy Dog"}'::jsonb,
'"numeric"'));
length
--------
0
(1 row)
postgres=# SELECT length(jsonb_to_tsvector('{"a": "The Quick Brown Fox",
"b": "Jumps Over The Lazy Dog"}'::jsonb,
'[]'));
length
--------
0
(1 row)
如果提供了无效的 filter 值,则会引发错误。
postgres=# SELECT jsonb_to_tsvector('{"a": "The Quick Brown Fox",
"b": "Jumps Over The Lazy Dog"}'::jsonb,
'["varchar"]');
ERROR: wrong flag in flag array: "varchar"
HINT: Possible values are: "string", "numeric", "boolean", "key", and "all".
参考资料
- PostgreSQL 文档: 文本搜索函数
