【问题标题】:Use variables as search keys within jsonb_extract_path在 jsonb_extract_path 中使用变量作为搜索键
【发布时间】:2019-10-06 00:23:35
【问题描述】:

我正在处理一个比较最后一个条目和新条目之间的列中的 jsonb 值的事件。我有另一个表,它通过传递 jsonb 对象本身来定义要比较的值。我正在使用的东西是这样的:

select jsonb_extract_path(_tmp_jsonb, 'key_1', 'key2') into target;

我正在查看的 jsonb 对象是这样的:

{
 "key1": {"key2": 15},
 "key3": {"key2": {"key4": 25}}
}

现在我可以使用上面的命令得到 15 没有问题,但我想做的是能够将任何组合键作为 jsonb 数组传递,例如 {"search_keys":["key3", "key2", "key4"]}。所以是这样的:

select jsonb_extract_path(_tmp_jsonb, ["key3", "key2", "key4"]) into target;

更清楚地说,我要问的是如何在 postgres 中使用可变长度参数数组,就像在 python 中使用 *args 所做的那样。

【问题讨论】:

    标签: postgresql plpgsql jsonb


    【解决方案1】:

    使用the #> operator 代替函数。右边的操作数是一个文本数组。

    declare
        _tmp_jsonb jsonb;
        _path text[];
        target jsonb;
    begin
        _tmp_jsonb := '{"key1": {"key2": 15}, "key3": {"key2": {"key4": 25}}}';
        _path := array['key3', 'key2', 'key4'];
        target := _tmp_jsonb #> _path;
        ...
    

    对了,简单的作业不要用select,太费钱了。

    Postgres 12 中,您可以使用 SQL/JSON 路径函数,例如:

    declare
        _tmp_jsonb jsonb;
        _path jsonpath; -- !!
        target jsonb;
    begin
        _tmp_jsonb := '{"key1": {"key2": 15}, "key3": {"key2": {"key4": 25}}}';
        _path := '$.key3.key2.key4';
        target := jsonb_path_query(_tmp_jsonb, _path);
        ...
    

    新功能灵活且强大,因为 json 路径可能包含通配符并支持递归。

    阅读文档:

    另请参阅this answer. 中的 jsonpath 示例

    【讨论】:

    • 很好,现在有什么方法可以让我也有一个通配符吗?
    • 感谢您,这对您有很大帮助。虽然我不确定我们是否可以升级到 Postgres12。
    猜你喜欢
    • 1970-01-01
    • 2011-12-26
    • 2021-06-25
    • 1970-01-01
    • 2017-04-14
    • 2018-05-27
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多