Postgres jsonb数组:查询非空交集

Postgres jsonb array: query for non-empty intersection

假设我在 table t 中有一个名为 value 的 JSONB 列,并且 JSON 的这些 blob 内部是一个 tags 字段,它是一个字符串列表。

我想查询任何标记为 "foo""bar".

的 JSON blob

假设 table 数据如下所示:

value
---------------------
{"tags": ["other"]}
{"tags": ["foo", "quux"]}
{"tags": ["baz", "bar"]}
{"tags": ["bar", "foo"]}
{"tags": []}

我想写这样的查询:

select value from t where value->'tags' NONEMPTY_INTERSECTION '["foo", "bar"]'

结果将是:

value
-----------------------
{"tags": ["foo", "quux"]}
{"tags": ["baz", "bar"]}
{"tags": ["bar", "foo"]}

是否有一个实际的查询可以完成这个,有什么方法可以更快吗?

SELECT DISTINCT t.value
FROM t, jsonb_array_elements(t.value->'tags') tags
WHERE tags.value <@ '["foo", "bar"]'::jsonb;

我要找的运算符是?|,可以这样使用:

select t.value from t where value->'tags' ?| array['foo','bar'];

测试如下:

danburton=# select * from jsonb_test;
           value
---------------------------
 {"tags": ["foo"]}
 {"tags": ["other"]}
 {"tags": ["foo", "quux"]}
 {"tags": ["baz", "bar"]}
 {"tags": ["bar", "foo"]}
 {"tags": []}
(6 rows)

danburton=# select jsonb_test.value from jsonb_test where value->'tags' ?| array['foo','bar'];
           value
---------------------------
 {"tags": ["foo"]}
 {"tags": ["foo", "quux"]}
 {"tags": ["baz", "bar"]}
 {"tags": ["bar", "foo"]}
(4 rows)