2017-09-05 288 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