在 jsonb_extract_path 中使用变量作为搜索关键字
Use variables as search keys within jsonb_extract_path
我正在处理一个事件,该事件比较最后一个条目和新条目之间的列中的 jsonb 值。我还有另一个 table,它通过传递 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 一样。
使用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
个示例
我正在处理一个事件,该事件比较最后一个条目和新条目之间的列中的 jsonb 值。我还有另一个 table,它通过传递 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 一样。
使用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
个示例