在postgres中递归地展平嵌套的jsonb,没有未知的深度和未知的关键字段

时间:2017-08-09 08:30:04

标签: postgresql jsonb

如何在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,并且之前已知密钥

1 个答案:

答案 0 :(得分:4)

示例设置:

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)

如果您希望获得此数据的平面视图,可以使用此回答documentation中描述的函数create_jsonb_flat_view()

您需要使用展平的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。