arrays - Postgres JSONB : where clause for arrays of arrays

标签 arrays json postgresql jsonb

postgres 中有(v 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'

查询的意思应该是:给我所有的id

  1. 一些顶级属性有特定的值
  2. 数组中的特定对象具有必需的属性
  3. 某些对象(来自 array2)特别是 array1 具有必需的属性

诀窍在于如何实现最后一个条件。


另一个例子:

{
    "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'

最佳答案

检索嵌套 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';

关于arrays - Postgres JSONB : where clause for arrays of arrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38201823/

相关文章:

json - 在 Azure 数据工厂 v2 中的 REST Web 服务上使用 JSON 正文查询

javascript - 如何将变量的值传递给 firebase 调用?

c++ - 如何在虚幻引擎中动态设置文本

c# - 如何使用 LINQ 过滤字符串 []?

c# - 是否可以更改 Attribute.Add 格式化添加属性的方式?

postgresql - 为什么 Postgres position() 函数给出不同的结果?

javascript - 如何使用 node-postgres 将多行正确插入 PG?

sql - 在 postgresql 中,是否可以使用 CREATE TABLE 上的触发器为表创建触发器?

c - 为什么当 N 越界时 &a[N] 不调用 UB?

python - 在Python中创建具有特定条件的矩阵