Bulk/batch update/upsert in PostgreSQL

前端 未结 5 1414
慢半拍i
慢半拍i 2020-11-29 00:27

I\'m writing a Django-ORM enchancement that attempts to cache models and postpone model saving until the end of the transaction. It\'s all almost done, however I came across

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 01:31

    it is pretty fast to populate json into recordset (postgresql 9.3+)

    big_list_of_tuples = [
        (1, "123.45"),
        ...
        (100000, "678.90"),
    ]
    
    connection.execute("""
        UPDATE mytable
        SET myvalue = Q.myvalue
        FROM (
            SELECT (value->>0)::integer AS id, (value->>1)::decimal AS myvalue 
            FROM json_array_elements(%s)
        ) Q
        WHERE mytable.id = Q.id
        """, 
        [json.dumps(big_list_of_tuples)]
    )
    

提交回复
热议问题