Postgres JSONB:数组数组的where子句

时间:2016-07-05 11:04:19

标签: arrays json postgresql jsonb

有postgres(第9.5节,如果有关系):

create table json_test(
 id varchar NOT NULL,
 data jsonb NOT NULL,
 PRIMARY KEY(id)
);

其中数据是json并包含数组数组

{
    "attribute": "0",
    "array1": [{
        "id": "a12",
        "attribute": "1",
        "array2": [{
            "id": "a21",
            "attribute": "21"
        }]
    },
    {
        "id": "a12",
        "attribute": "2",
        "array2": [{
            "id": "22",
            "attribute": "22"
        }]
    }]
}

必填:

select id from json_test where 
    json_test->>'attribute'='0' and
    array1.[id='a12'].array2.attribute='22'

查询应该意味着:给我所有的ids

  1. 某些顶级属性具有特定值
  2. 数组中的特定对象具有必需属性
  3. 某个对象(来自array2),特别是array1具有必需的属性
  4. 诀窍是如何实现最后一个条件。

    另一个例子:

    {
        "attribute": "0",
        "array1": [{
            "id": "a12",
            "attribute": "1",
            "array2": [{
                "id": "a21_1",
                "attribute_1": "21_1"
            },{
                "id": "a21_2",
                "attribute_2": "21_2"
            }]
        }]
    }
    
    select * from json_test where 
        array1.[id='a12'].array2.attribute_1='21_1' and  
        array1.[id='a12'].array2.attribute_2='21_2'
    

2 个答案:

答案 0 :(得分:5)

检索嵌套json数组的最常用方法是在横向连接中使用多个jsonb_array_elements()。例如:

with json_test(id, data) as (
    values
        (1, 
        '{
            "attribute": "0",
            "array1": [{
                "id": "a12",
                "attribute": "1",
                "array2": [{
                    "id": "a21",
                    "attribute": "21"
                }]
            },
            {
                "id": "a12",
                "attribute": "2",
                "array2": [{
                    "id": "22",
                    "attribute": "22"
                }]
            }]
        }'::jsonb)
    )

select id, elem2
from 
    json_test, 
    jsonb_array_elements(data->'array1') array1(elem1),
    jsonb_array_elements(elem1->'array2') array2(elem2)
where elem2->>'id' = '22';

 id |              elem2              
----+---------------------------------
  1 | {"id": "22", "attribute": "22"}
(1 row)

该方法是通用的,因为您可以轻松访问任何级别上任何json对象的任何值,例如:

...
where 
    data->>'attribute' = '0'
    and elem1->>'id' = 'a12'
    and elem2->>'id' = 'a21_1';

答案 1 :(得分:1)

扩展klin的答案,包括所有测试:

SELECT j.id
FROM json_test j
     JOIN LATERAL jsonb_array_elements(j.data->'array1') x(y) ON true
     JOIN LATERAL jsonb_array_elements(x.y->'array2') a(b) ON true
WHERE j.data->>'attribute'='0'
  AND x.y->>'id' = 'a12'
  AND a.b->>'attribute' = '22';