2011-11-15 40 views
24

我有数千万行要从多维数组文件传输到PostgreSQL数据库。我的工具是Python和psycopg2。批量添加数据的最有效方法是使用copy_from。但是,我的数据大多是32位浮点数(real或float4),所以我宁愿不从真实→文本→真实转换。下面是一个例子数据库DDL:使用二进制COPY表FROM与psycopg2

CREATE TABLE num_data 
(
    id serial PRIMARY KEY NOT NULL, 
    node integer NOT NULL, 
    ts smallint NOT NULL, 
    val1 real, 
    val2 double precision 
); 

这里就是我在使用Python字符串(文本):

# Just one row of data 
num_row = [23253, 342, -15.336734, 2494627.949375] 

import psycopg2 
# Python3: 
from io import StringIO 
# Python2, use: from cStringIO import StringIO 

conn = psycopg2.connect("dbname=mydb user=postgres") 
curs = conn.cursor() 

# Convert floating point numbers to text, write to COPY input 
cpy = StringIO() 
cpy.write('\t'.join([repr(x) for x in num_row]) + '\n') 

# Insert data; database converts text back to floating point numbers 
cpy.seek(0) 
curs.copy_from(cpy, 'num_data', columns=('node', 'ts', 'val1', 'val2')) 
conn.commit() 

是否有可以工作使用二进制模式等同?也就是说,保持二进制浮点数?这不仅会保持浮点精度,而且可能会更快。

(注:看到相同的精度的例子中,使用SET extra_float_digits='2'

+0

那么,你可以[导入二进制文件COPY](http://www.postgresql.org/docs/9.1/interactive/sql-copy.html),但为此,整个文件必须在一个特定的二进制格式,而不仅仅是一个值。 –

+0

@Erwin,是的,我读了关于COPY的二进制模式,但我不确定它是否被psycopg2支持,或者我是否应该使用不同的方法。 –

+0

我使用的二进制文件格式的唯一应用是导入从* PostgreSQL导出*的文件。我不知道任何其他可以编写特定格式的程序。尽管如此,这并不意味着它不可能出现在那里。如果是用于重复操作,则可以以文本形式复制到Postgres一次,下一次写入二进制文件和'COPY FROM .. FORMAT BINARY'。 –

回答

29

这里是COPY的二进制等效FROM用于Python 3:

from io import BytesIO 
from struct import pack 
import psycopg2 

# Two rows of data; "id" is not in the upstream data source 
# Columns: node, ts, val1, val2 
data = [(23253, 342, -15.336734, 2494627.949375), 
     (23256, 348, 43.23524, 2494827.949375)] 

conn = psycopg2.connect("dbname=mydb user=postgres") 
curs = conn.cursor() 

# Determine starting value for sequence 
curs.execute("SELECT nextval('num_data_id_seq')") 
id_seq = curs.fetchone()[0] 

# Make a binary file object for COPY FROM 
cpy = BytesIO() 
# 11-byte signature, no flags, no header extension 
cpy.write(pack('!11sii', b'PGCOPY\n\377\r\n\0', 0, 0)) 

# Columns: id, node, ts, val1, val2 
# Zip: (column position, format, size) 
row_format = list(zip(range(-1, 4), 
         ('i', 'i', 'h', 'f', 'd'), 
         (4, 4, 2, 4, 8))) 
for row in data: 
    # Number of columns/fields (always 5) 
    cpy.write(pack('!h', 5)) 
    for col, fmt, size in row_format: 
     value = (id_seq if col == -1 else row[col]) 
     cpy.write(pack('!i' + fmt, size, value)) 
    id_seq += 1 # manually increment sequence outside of database 

# File trailer 
cpy.write(pack('!h', -1)) 

# Copy data to database 
cpy.seek(0) 
curs.copy_expert("COPY num_data FROM STDIN WITH BINARY", cpy) 

# Update sequence on database 
curs.execute("SELECT setval('num_data_id_seq', %s, false)", (id_seq,)) 
conn.commit() 

更新

我重写了上面的方法来为COPY写入文件。我在Python中的数据是NumPy数组,所以使用它们是有意义的。下面是用1M的行,列7一些示例data

import psycopg2 
import numpy as np 
from struct import pack 
from io import BytesIO 
from datetime import datetime 

conn = psycopg2.connect("dbname=mydb user=postgres") 
curs = conn.cursor() 

# NumPy record array 
shape = (7, 2000, 500) 
print('Generating data with %i rows, %i columns' % (shape[1]*shape[2], shape[0])) 

dtype = ([('id', 'i4'), ('node', 'i4'), ('ts', 'i2')] + 
     [('s' + str(x), 'f4') for x in range(shape[0])]) 
data = np.empty(shape[1]*shape[2], dtype) 
data['id'] = np.arange(shape[1]*shape[2]) + 1 
data['node'] = np.tile(np.arange(shape[1]) + 1, shape[2]) 
data['ts'] = np.repeat(np.arange(shape[2]) + 1, shape[1]) 
data['s0'] = np.random.rand(shape[1]*shape[2]) * 100 
prv = 's0' 
for nxt in data.dtype.names[4:]: 
    data[nxt] = data[prv] + np.random.rand(shape[1]*shape[2]) * 10 
    prv = nxt 

在我的数据库,我有一个看起来像两个表:

CREATE TABLE num_data_binary 
(
    id integer PRIMARY KEY, 
    node integer NOT NULL, 
    ts smallint NOT NULL, 
    s0 real, 
    s1 real, 
    s2 real, 
    s3 real, 
    s4 real, 
    s5 real, 
    s6 real 
) WITH (OIDS=FALSE); 

,并命名为num_data_text另一个类似的表。

这里有一些简单的辅助功能由NumPy的记录阵列中使用这些信息来准备数据COPY(文本和二进制格式):

def prepare_text(dat): 
    cpy = BytesIO() 
    for row in dat: 
     cpy.write('\t'.join([repr(x) for x in row]) + '\n') 
    return(cpy) 

def prepare_binary(dat): 
    pgcopy_dtype = [('num_fields','>i2')] 
    for field, dtype in dat.dtype.descr: 
     pgcopy_dtype += [(field + '_length', '>i4'), 
         (field, dtype.replace('<', '>'))] 
    pgcopy = np.empty(dat.shape, pgcopy_dtype) 
    pgcopy['num_fields'] = len(dat.dtype) 
    for i in range(len(dat.dtype)): 
     field = dat.dtype.names[i] 
     pgcopy[field + '_length'] = dat.dtype[i].alignment 
     pgcopy[field] = dat[field] 
    cpy = BytesIO() 
    cpy.write(pack('!11sii', b'PGCOPY\n\377\r\n\0', 0, 0)) 
    cpy.write(pgcopy.tostring()) # all rows 
    cpy.write(pack('!h', -1)) # file trailer 
    return(cpy) 

这我如何使用辅助函数基准的两个拷贝格式的方法:

def time_pgcopy(dat, table, binary): 
    print('Processing copy object for ' + table) 
    tstart = datetime.now() 
    if binary: 
     cpy = prepare_binary(dat) 
    else: # text 
     cpy = prepare_text(dat) 
    tendw = datetime.now() 
    print('Copy object prepared in ' + str(tendw - tstart) + '; ' + 
      str(cpy.tell()) + ' bytes; transfering to database') 
    cpy.seek(0) 
    if binary: 
     curs.copy_expert('COPY ' + table + ' FROM STDIN WITH BINARY', cpy) 
    else: # text 
     curs.copy_from(cpy, table) 
    conn.commit() 
    tend = datetime.now() 
    print('Database copy time: ' + str(tend - tendw)) 
    print('  Total time: ' + str(tend - tstart)) 
    return 

time_pgcopy(data, 'num_data_text', binary=False) 
time_pgcopy(data, 'num_data_binary', binary=True) 

下面是最后两个time_pgcopy命令的输出:

Processing copy object for num_data_text 
Copy object prepared in 0:01:15.288695; 84355016 bytes; transfering to database 
Database copy time: 0:00:37.929166 
     Total time: 0:01:53.217861 
Processing copy object for num_data_binary 
Copy object prepared in 0:00:01.296143; 80000021 bytes; transfering to database 
Database copy time: 0:00:23.325952 
     Total time: 0:00:24.622095 

因此,使用二进制方法NumPy→文件和文件→数据库步骤都快得多。明显的区别是Python如何准备COPY文件,这对文本来说确实很慢。一般来说,二进制格式以2/3的时间作为该模式的文本格式加载到数据库中。

最后,我比较了数据库中两个表中的值,看看数字是否不同。对于列s0,大约1.46%的行具有不同的值,并且s6(可能与我使用的随机方法有关)的这一部分增加到6.17%。所有70M 32位浮点值之间的非零绝对差值介于9.3132257e-010和7.6293945e-006之间。文本和二进制加载方法之间的这些细微差异是由于文本格式方法所需的float→text→float转换的精度损失所致。

+0

很酷。你是否写过这样的文章?它是否真的提高了性能? –

+0

如果它工作,酷!除了格式之外,解决方案是使用psycopg的'copy_expert()'。 – piro

+0

@Erwin,是的,我使用[复制](http://www.postgresql.org/docs/current/interactive/sql-copy.html),[结构](http:// docs。 python.org/library/struct.html)和[dtype](http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html)。基准在,并且看起来不错。 –

1

Here是我的版本。基于迈克的版本。

它非常的ad-hoc但有两个优点:

  • 超载readline
  • 示例如何hstore二进制格式写期待发电机并作为流。