我不知道深度和每个深度的字段,如何在 postgres 中递归地展平嵌套的 jsonb? (见下面的例子)
进行扁平化的 postgressql 查询将非常受欢迎
{
"xx": "",
"xx": "",
"form": "xxx",
"type": "",
"content_type": "xxx",
"reported_date": ,
"contact": {
"imported_date": "",
"name": "",
"phone": "",
"alternate_phone": "",
"specialization": "",
"type": "",
"reported_date": ,
"parent": {
"_id": "xxx",
"_rev": "xxx",
"parent": "",
"type": "xxx"
}
}
}
我在堆栈溢出中搜索过,但他们只考虑具有单一深度且键之前已知的 jsonb
示例设置:
create table my_table(id int, data jsonb);
insert into my_table values
(1,
$${
"type": "a type",
"form": "a form",
"contact": {
"name": "a name",
"phone": "123-456-78",
"type": "contact type",
"parent": {
"id": "444",
"type": "parent type"
}
}
}$$);
递归查询对在任何级别上找到的每个 json 对象执行
jsonb_each()
。新键名包含从根开始的完整路径:
with recursive flat (id, key, value) as (
select id, key, value
from my_table,
jsonb_each(data)
union
select f.id, concat(f.key, '.', j.key), j.value
from flat f,
jsonb_each(f.value) j
where jsonb_typeof(f.value) = 'object'
)
select id, jsonb_pretty(jsonb_object_agg(key, value)) as data
from flat
where jsonb_typeof(value) <> 'object'
group by id;
id | data
----+------------------------------------------
1 | { +
| "form": "a form", +
| "type": "a type", +
| "contact.name": "a name", +
| "contact.type": "contact type", +
| "contact.phone": "123-456-78", +
| "contact.parent.id": "444", +
| "contact.parent.type": "parent type"+
| }
(1 row)
如果您想获得此数据的平面视图,您可以使用此答案中描述的函数
create_jsonb_flat_view()
Flatten aggregated key/value pairs from a JSONB field?
您需要使用扁平化的 jsonb 创建表(或视图):
create table my_table_flat as
-- create view my_table_flat as
with recursive flat (id, key, value) as (
-- etc as above
-- but without jsonb_pretty()
现在你可以使用桌子上的功能了:
select create_jsonb_flat_view('my_table_flat', 'id', 'data');
select * from my_table_flat_view;
id | contact.name | contact.parent.id | contact.parent.type | contact.phone | contact.type | form | type
----+--------------+-------------------+---------------------+---------------+--------------+--------+--------
1 | a name | 444 | parent type | 123-456-78 | contact type | a form | a type
(1 row)
该解决方案适用于 Postgres 9.5+,因为它使用了此版本中引入的 jsonb 函数。如果您的服务器版本较旧,强烈建议升级 Postgres 以有效地使用 jsonb。
jsonb_unnest_recursive()
查询:
select cardinality(path) as level,
array_to_string(path, '.') as path,
value
from jsonb_unnest_recursive($${
"type": "a type",
"form": "a form",
"contact": {
"name": "a name",
"phone": "123-456-78",
"type": "contact type",
"numbers": [11,22,33],
"parent": {
"id": "444",
"type": "parent type"
}
}
}$$::jsonb) as t;
结果:
Stackoverflow 无法将此降价解析为表格 :(
| level | path | value |
| :--- | :--- | :--- |
| 1 | form | "a form" |
| 1 | type | "a type" |
| 2 | contact.name | "a name" |
| 2 | contact.type | "contact type" |
| 2 | contact.phone | "123-456-78" |
| 3 | contact.parent.id | "444" |
| 3 | contact.parent.type | "parent type" |
| 3 | contact.numbers.0 | 11 |
| 3 | contact.numbers.1 | 22 |
| 3 | contact.numbers.2 | 33 |