2015-07-10 78 views
0

我想從嵌套字典結構輸入數據到PostgreSQL數據庫使用psycopg2如here所示。我不確定的是如何訪問字典的嵌套部分,或者甚至可以在一個插入查詢中執行。數據結構是這樣的:巢詞典插入到psycopg2

dictionary = ({ 
      "article_id":94527, "article_title":"An article title", 
      "country_info": [{"country_id":281133, 
           "country_code":"GB", 
           "country_name":"United Kingdom", 
           "lon":32.0000, 
           "lat":49.0000}, 
          {"country_id":281133, 
           "country_code":"FR", 
           "country_name":"France", 
           "lon":22.0000, 
           "lat":39.0000}] 
     }) 

和查詢到目前爲止是這樣的:

cur.execute(""" 
WITH article_s AS (
    SELECT id FROM article 
    WHERE id = %(article_id)s 
), 
article_i AS (
    INSERT INTO article (article_id, article_title) 
     SELECT %(article_id)s, %(article_title)s 
     WHERE NOT EXISTS (SELECT id FROM article where id = %(article_id)s) 
     RETURNING id 
), 
country_s AS (
    SELECT id FROM country 
    WHERE id = %(country_id)s 
), 
country_i AS (
    INSERT INTO country (id, country_code, country, geom) 
     SELECT %(country_id)s, %(country_code)s, %(country_name)s, ST_SetSRID(ST_MakePoint(%(lon)s, %(lat)s), 4326) 
     WHERE NOT EXISTS (SELECT 1 FROM country_s) 
     RETURNING id 
) 
INSERT INTO article_countries (article_id, country_id) 
    SELECT COALESCE (article_i.id, country_i.id), 
    COALESCE (article_i.id, country_i.id) 
    FROM article_i, country_i, 
    article_s, country_s 
; 
""", dictionary) 

人對如何實現這一目標有什麼建議?提前致謝!

回答

0

如果您使用的是postgres 9.2或更高版本,您可能會將該字典轉換爲json並嘗試以這種方式插入它。 postgres 9.2和更高版本對JSON類型有本地支持,這將允許您使用一些額外的sql訪問嵌套的json元素。

see also

+0

謝謝肯定看起來很有希望,但仍然沒有得到解決嵌套數據到查詢的問題。你能舉個例子嗎? – sammy88888888