Nest字典插入psycopg2

时间:2015-07-10 17:27:44

标签: python postgresql dictionary psycopg2

我正在尝试使用psycopg2将嵌套字典结构中的数据输入到PostgreSQL数据库中,如here所示。我不确定的是如何访问字典的嵌套部分,或者甚至可以在一个插入查询中执行此操作。数据结构如下所示:

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)

任何人对如何实现这一点都有任何建议?提前谢谢!

1 个答案:

答案 0 :(得分:0)

如果你正在使用postgres 9.2或更高版本,你可以将该字典转换为json并尝试以这种方式插入。 postgres 9.2及更高版本对JSON类型具有本机支持,允许您使用一些额外的sql访问嵌套的json元素。

see also