【问题标题】:Add/Update objects and elements inside NESTED JSONB arrays with PostgreSQL使用 PostgreSQL 在 NESTED JSONB 数组中添加/更新对象和元素
【发布时间】:2020-02-22 08:36:56
【问题描述】:

Json 请求:

INSERT INTO test.demotbl (data)
VALUES ('{
    "x1": "Americas",
    "x2": "West",
    "x3": [{
        "x_id": "sam"
    }],
    "x4": {
        "a1": true,
        "a2": false,
        "a3": [
            "xx",
            "xx"
        ],
        "a4": [
            "Josh"
        ],
        "y1": [{
                "id": "RW",
                "z2": true,
                "z3": "USER"

            },
            {
                "id": "RO",
                "z2": false,
                "z3": "SELECT"

            }
        ]
    }
}'::jsonb)

我想根据 id "id": "RO" 更新归档的 z4。

当我需要更新查询下方使用的 z4 字段时,我在这里遇到了类似的用例:

with zd as (select ('{x4,y1,'||index-1||',z4}')::text[] as path
            from table1
            ,jsonb_array_elements((field1->>'x4')::jsonb->'y1') 
            with ordinality arr(x,index)
            where x->>'id'='RO'
        )
update table1
set field1=jsonb_set(field1,zd.path,to_jsonb('[ { "name": "john" } ]'::jsonb),false)
from zd

但是现在在当前的 json 文件中没有提交的 X4,我需要添加“z4”:[{ “姓名”:“约翰” } 而不是仅仅更新字段

预期输出:

{
    "x1": "Americas",
    "x2": "West",
    "x3": [{
        "x_id": "sam"
    }],
    "x4": {
        "a1": true,
        "a2": false,
        "a3": [
            "xx",
            "xx"
        ],
        "a4": [
            "Josh"
        ],
        "y1": [{
                "id": "RW",
                "z2": true,
                "z3": "USER"

            },
            {
                "id": "RO",
                "z2": false,
                "z3": "SELECT",
                "z4": [{
                    "name": "john"
                }]
            }
        ]
    }
}

是否可以修改上述查询或建议一个新查询同时适用于添加(如果归档 z4 不存在)和更新归档 z4 示例 "z4": [{ "name": "john" },{ "name ": "Steve" }] 如果归档 z4 存在。

【问题讨论】:

  • "z4": [{ "name": "john", "name":"steve" }] 在预期输出中看起来不同。你想让 z4 成为一个数组吗?
  • @Bjarni Ragnarsson 是的,抱歉打错了,应该是 "z4": [{ "name": "john" },{ "name": "Steve" }]

标签: postgresql jsonb


【解决方案1】:

如果要添加z4,只需要将jsonb_set函数中的最后一个参数改为“true”而不是“false”即可。这指示函数在字段不存在时创建该字段。 您需要将 to_jsonb(...) 更改为 '....'::jsonb 以解析数组。
这应该有效:

with zd as (select ('{x4,y1,'||index-1||',z4}')::text[] as path
            from table1
            ,jsonb_array_elements((field1->>'x4')::jsonb->'y1') 
            with ordinality arr(x,index)
            where x->>'id'='RO'
        )
update table1
set field1=jsonb_set(field1,zd.path,'[{ "name": "john" },{ "name": "Steve" }]'::jsonb,true)
from zd

我希望我在这里正确粘贴和修改了这个:-)
最好的问候,
比亚尼

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 2020-03-16
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多