2017-09-05 285 views
0

我需要在这种情况下使用python创建一个脚本,以获取一个表的列jsonb创建另一个表,其中列是所有可能的关键字JSON。Postgre将列jsonb转换为另一个表,其中列是键

例如:

id | optional 

1 | {"a":"4", "b":"5"} 
2 | {} 
3 | {"a":"8", "c":"9", "d":"9"} 

id | a | b | c | d 

1 | 4 | 5 |  | 
3 | 8 |  | 9 | 9 

我使用此查询键:

select jsonb_object_keys(optional) as key from table group by key 

我用下面的代码在Python用键创建一个表格S作为列

connection = psycopg2.connect(host=host, database=database, user=user, password=password) 
    try:  
     columns = "(" 
     for column in keys: 
      columns+=column+" TEXT "+',' 
     columns = columns[0:len(columns)-1] 
     columns += ");" 
     query = "CREATE TABLE " + table +" " 
     query += columns 
     print query 
     cur = connection.cursor() 
     cur.execute(query) 
     connection.commit() 
     cur.close() 

,我得到了我需要把在其他表使用此查询的数据:

select id, optional->'a',... from table where optional<>'{}' 

在我来说,我身边有31键,以便上面的查询是大和另一方面,如果我想重复使用这个脚本到另一个案例,我需要改变这个查询可能。

所以我想知道是否有另一种更优雅和更通用的方式来做到这一点。即使它不是必要的解决方案使用python,如果它只与postgres它对我也有好处

任何想法?

预先感谢

回答

2

你可能在Postgres的溶液中insterested描述in this answer (see Generalized solution).

实施例源表:

drop table if exists my_table; 
create table my_table(id int primary key, data jsonb); 
insert into my_table values 
(1, '{"a":"4", "b":"5"}'), 
(2, '{}'), 
(3, '{"a":"8", "c":"9", "d":"9"}'); 

使用功能:

select create_jsonb_flat_view('my_table', 'id', 'data'); 

select * from my_table_view; 

id | a | b | c | d 
----+---+---+---+--- 
    1 | 4 | 5 | | 
    2 | | | | 
    3 | 8 | | 9 | 9 
(3 rows) 

您可以创建基于平面视图的新表:

create table my_new_table as 
select * 
from my_table_view 
order by id; 
+0

Soory但是,当我尝试执行代码 SQL的错误,我有这样的错误: 'ERROR:功能create_jsonb_flat_view(未知,未知,未知)不存在 LINE 1:select create_jsonb_flat_view('my_table','id','data'); ^ 提示:没有函数匹配给定的名称和参数类型。您可能需要添加明确的类型转换.' – Cyberguille

+1

您在该文章中拥有该函数的代码。您应该在数据库中创建函数(一次)。 – klin

+0

只需要创建一个像列一样的键的表,但我不知道如何去通用'select id,可选 - >'a',...',像放'select id,optional- >键,...',并且不需要指定列的名称 – Cyberguille