【问题标题】:Postgres jsonb array: query for non-empty intersectionPostgres jsonb数组:查询非空交集
【发布时间】:2016-09-14 00:27:46
【问题描述】:

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

我想查询任何标记为 "foo""bar" 的 JSON blob。

所以假设表格数据如下所示:

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"]}

是否有一个实际的查询可以完成此操作,有什么方法可以快速完成吗?

【问题讨论】:

标签: postgresql jsonb


【解决方案1】:
SELECT DISTINCT t.value
FROM t, jsonb_array_elements(t.value->'tags') tags
WHERE tags.value <@ '["foo", "bar"]'::jsonb;

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-29
      • 2020-11-16
      • 2015-11-28
      • 2015-09-10
      • 2016-06-14
      • 1970-01-01
      • 2021-09-28
      • 2017-05-02
      相关资源
      最近更新 更多