LoginSignup
24
29

More than 5 years have passed since last update.

Postgresqlでバルクインサートする方法

Posted at

PostgresqlでINSERTする方法

1000行ずつINSERTするのを10回実行するコード

import psycopg2
from psycopg2  import extras
import datetime

dsn="dbname=xxxx host=xxxx port=5432 user=xxxx password=xxxx"
con = psycopg2.connect(dsn)

for i in range(10):

    cur = con.cursor()
    insert_list = []    
    target_list = 何か処理した結果をリストに入れる

    for row in target_list:
        #ここではrowに3つのカラムのデータが入っているとする。
        #この場合、これらのデータを以下のようにタプルにする
        t = (row[0],row[1],row[2])
        insert_list.append(t)

    extras.execute_values(cur, "INSERT INTO table values %s", insert_list)
    con.commit()

con.close()

psycopg2にはexecutemanyという関数があるが、これはバルクインサートではなく遅い。
具体的には上のコードのextras.execute_valuesのところを以下のようにするとexecutemanyでINSERTできる。

cur.executemany("INSERT INTO table values(%s,%s,%s)",insert_list)

最初は遅いの知らなくてこれでやってたが、遅すぎて高速化を調べてたらここに書いてました。
https://datumstudio.jp/blog/postgresql%E3%81%A7insert%E9%80%9F%E5%BA%A6%E6%AF%94%E8%BC%83
http://initd.org/psycopg/docs/extras.html#fast-exec

自分の環境では、1000行INSERTするのに30秒かかってたのが、3秒くらいに短縮されました。
ただ、上にリンク書いたDatumさんの記事によるとCOPY文の方がもっと高速にできるらしいです。

24
29
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
29