查询与postgres jsonb相交的json键

时间:2018-08-31 06:59:05

标签: sql postgresql jsonb

我如何查询相交的jsonb密钥:

例如:

     kv                                 |        column1                   
-----------------------------------------------------------
[{"k1": "v1"}, {"k2": "v22"}]           | web
[{"k10": "v5"}, {"k9": "v21"}]          | mobile
[{"k1": "v1"}, {"k5": "v24"}]           | web1
[{"k5": "v1"}, {"k55": "v24"}]          | web1

此处,第1行和第3行具有键k1,第3行和第4行具有键k5

因此,答案应该是第1,3和4行。

2 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

--This part is to simulate your table
with yourTable as (
select (string_to_array(t,'|'))[1]::jsonb kv,(string_to_array(t,'|'))[2] column1 from (
select unnest(string_to_array($$[{"k1": "v1"}, {"k2": "v22"}]           | web
[{"k10": "v5"}, {"k9": "v21"}]          | mobile
[{"k1": "v1"}, {"k5": "v24"}]           | web1
[{"k5": "v1"}, {"k55": "v24"}]          | web1$$::character varying,E'\n')) t

) b
) 
-- This is your request :
   select distinct kv,column1 from (
        select *,count(*) over (partition by elt) nb_inter from (
          select kv,column1,jsonb_object_keys(jsonb_array_elements(kv)) elt from yourTable
          ) a 
        ) b
where nb_inter >1

答案 1 :(得分:1)

假定以下设置:

create table data (id serial, kv jsonb, col1 text);

insert into data (kv, col1)
values
('[{"k1": "v1"}, {"k2": "v22"}]', 'web'),
('[{"k10": "v5"}, {"k9": "v21"}]', 'mobile'),
('[{"k1": "v1"}, {"k5": "v24"}]', 'web1'),
('[{"k5": "v1"}, {"k55": "v24"}]', 'web1');

您可以通过首先规范化数据,然后对规范化的数据进行自联接来获得这些行。要规范化数据,您需要取消嵌套JSON值两次:一次用于展平数组,另一次从JSON值提取键:

with normalized as (
  select d.id, t2.*
  from data d
    join jsonb_array_elements(kv) as t1(kv) on true
    join jsonb_each_text(t1.kv) as t2(k,val) on true
)
select n1.*
from normalized n1
where exists (select *
              from normalized n2
              where n1.id <> n2.id 
                and n1.k = n2.k);

以上返回:

id | k  | val
---+----+----
 1 | k1 | v1 
 3 | k1 | v1 
 3 | k5 | v24
 4 | k5 | v1 

或将其与IN条件一起使用以获取原始行:

with normalized as (
  select d.id, t2.*
  from data d
    join jsonb_array_elements(kv) as t1(kv) on true
    join jsonb_each_text(t1.kv) as t2(k,val) on true
)
select *
from data
where id in (select n1.id
            from normalized n1
            where exists (select *
                          from normalized n2
                          where n1.id <> n2.id 
                            and n1.k = n2.k))

返回:

id | kv                             | col1
---+--------------------------------+-----
 1 | [{"k1": "v1"}, {"k2": "v22"}]  | web 
 3 | [{"k1": "v1"}, {"k5": "v24"}]  | web1
 4 | [{"k5": "v1"}, {"k55": "v24"}] | web1

如果您不将键/值对存储在数组中,则这种类型的查询会更容易,与'{"k1": "v1", "k2": "v22"}'相比,[{"k1": "v1"}, {"k2": "v22"}]对我来说更有意义