如何有效地使用python从大型postgres表中提取所有行?

时间:2016-01-04 19:14:21

标签: python postgresql fetch psycopg2 data-extraction

我已经能够使用python从postgres表中提取接近3.5 mil的行并写入文件。然而,这个过程非常缓慢,我确定不是最有效的。 以下是我的代码:

import psycopg2, time,csv
conn_string = "host='compute-1.amazonaws.com' dbname='re' user='data' password='reck' port=5433"
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
quert = '''select data from table;'''
cursor.execute(quert)

def get_data():
    while True:
        recs = cursor.fetchmany(10000)

        if not recs:
            break

        for columns in recs:
            # do transformation of data here
            yield(columns) 

solr_input=get_data()

with open('prc_ind.csv','a') as fh:
    for i in solr_input:
        count += 1

        if count % 1000 == 0:
             print(count)

         a,b,c,d = i['Skills'],i['Id'],i['History'],i['Industry']
         fh.write("{0}|{1}|{2}|{3}\n".format(a,b,c,d))

该表有大约8密耳的行。我想问一下,有没有更好,更快,内存更少的方法来实现这一目标。

2 个答案:

答案 0 :(得分:3)

我可以看到四个字段,因此我假设您只选择这些字段。

但即便如此,您仍然在加载8 mil x 4 x n字节的数据,而这些数据似乎是另一台服务器。所以是的,它需要一些时间。

虽然您正在尝试重建方向盘,但为什么不使用PostgreSQL客户端?

psql -d dbname -t -A -F"," -c "select * from users" > output.csv

答案 1 :(得分:1)

Psycopg2的copy_to命令与psql转储完全相同,正如Loïc建议的那样,除了它在python方面。我发现这是获得表转储的最快方法。

某些数据类型(例如hstore / json和复合类型)的格式有点时髦,但命令非常简单。

f = open('foobar.dat', 'wb')
cursor.copy_to(f, 'table', sep='|', columns=['skills', 'id', 'history', 'industry'])

文档:http://initd.org/psycopg/docs/cursor.html#cursor.copy_to