要求:使用S3将数百万行加载到表中,并避免内存问题
我看到有两种方法,分别是copy_from 2和copy_expert。
其中哪一个最有效并避免了内存问题。
另外,我看到Redshift(即Postgres)支持复制命令从S3文件加载数据,但不确定Postgres是否支持这种特性
发布于 2022-05-05 15:32:59
我的实现将copy_from
更改为copy_expert
。对PostgreSQL负载的广泛分析可以在这里找到:https://hakibenita.com/fast-load-data-python-postgresql。
COPY_FROM
def insert_with_string_io(df: pd.DataFrame, table_name: str):
buffer = io.StringIO()
df.to_csv(buffer, index=False, header=False)
buffer.seek(0)
with conn.cursor() as cursor:
try:
cursor.copy_from(file=buffer, table=table_name, sep=",", null="")
except (Exception, psycopg2.DatabaseError) as error:
print("Error: %s" % error)
COPY_EXPERT
def insert_with_string_io(df: pd.DataFrame):
buffer = io.StringIO()
df.to_csv(buffer, index=False, header=False)
buffer.seek(0)
with conn.cursor() as cursor:
try:
cursor.copy_expert(f"COPY <database>.<schema>.<table> FROM STDIN (FORMAT 'csv', HEADER false)" , buffer)
except (Exception, psycopg2.DatabaseError) as error:
print("Error: %s" % error)
https://stackoverflow.com/questions/64810090
复制相似问题