csv_copy
을 사용하여 테이블을 만들거나 채우는 경우 가끔 매우 느립니다. 다음은 핵심 코드와 몇 가지 샘플 출력입니다. 시간이 만들고 테이블을 채우는에 따라 다릅니다 왜테이블 만들기 및 채우기가 느리고 불안정합니다
- 내가 알아낼 수 없습니다 :
나는 두 가지 질문이 있습니다.
- "none"이 인쇄되는 원인이 확실하지 않습니다.
번호 :
def create_populate_table(table_name,fields,types,cur):
sql = 'CREATE TABLE IF NOT EXISTS ' + table_name + ' (\n'
for i in xrange(len(fields)):
if i==0:
sql += fields[i]+' '+types[i]+' NOT NULL PRIMARY KEY,\n'
elif i==len(fields)-1:
sql += fields[i]+' '+types[i]+')'
else:
sql += fields[i]+' '+types[i]+',\n'
#print sql
cur.execute(sql)
conn.commit()
print "Table ",table_name," created ",timer()
cur.execute("SELECT count(*) from "+table_name)
if cur.fetchone()[0]>0:
return
# populate data into created table
fr= open(file, 'r')
fr.readline()
# parse and convert data into unicode
#data = unicode_csv_reader(fr, delimiter='|')
# anything can be used as a file if it has .read() and .readline() methods
data = StringIO.StringIO()
s=''.join(fr.readlines())
while(s.find('\r\n')<>-1):
s=s.replace('\r\n','\n')
#timer()
while(s.find('||')<>-1 or s.find('|\n')<>-1):
s=s.replace('||','|0|')
s=s.replace('|\n','|0\n')
#timer()
#print s.split('\t')[:2]
#exit(0)
data.write(s)
data.seek(0)
try:
cur.copy_from(data, table_name,sep='|')
conn.commit()
print "Table ",table_name," populated ",timer()
except psycopg2.DatabaseError, e:
if conn:
conn.rollback()
print 'Error %s' % e
fr.close()
출력은 I 볼 :
ME_Features_20121001.txt 표 ME_Features_20121001는 1.44s 없음 표 ME_Features_20121001는 1.48s 없음
FM_Features_20121001.txt 표 채워져 만들어 FM_Features_20121001 만든 67.92s 없음 표 FM_Features_20121001 인구 ED 0.22s 없음
NationalFile_20121001.txt (7백메가바이트)는 표 NationalFile_20121001 는 9.34s가 없음 표 NationalFile_20121001 없음
NJ_Features_20121001.txt 표 NJ_Features_20121001는 1.65s 없음 표 NJ_Features_20121001 채워 41.11s 없음
생성 4963.18s 채워 만든PW_Features_20121001.txt 표 PW_Features_20121001는 1.73s 없음 표 PW_Features_20121001 채워 생성 0.20s 없음
당신은 당신의 자신의 자란 python 수입업자를 사용해야합니까? Postgre copy 명령을 사용할 수 있습니까? – Kuberchaun
@JustBob 위 코드는 COPY 명령을 사용합니다. 그것이'cur.copy_from' 행의 기능입니다. 그것은 Psycopg2 커서를 사용하여'COPY ... FROM stdin'을 실행합니다. –
서버 측 기간을 측정하는 경우 (PostgreSQL 매뉴얼,'log_min_duration_statement' http://www.postgresql.org/docs/current/static/runtime-config-logging.html), 클라이언트가 보는 것과 일치합니까?일반적으로 CSV 파일의 레코드 수와 디스크 크기에 대략적으로 비례하는 시간이 필요합니다. 느린 CREATE TABLE은 느린 체크 포인트가있을 수있는 신호입니다. http://wiki.postgresql.org/wiki/Logging_Checkpoints 및 http://wiki.postgresql.org/wiki/Tuning_Your_PostgreSQL_Server –