【问题标题】:Python write DateFrame to AWS redshift using psycopg2Python 使用 psycopg2 将 DataFrame 写入 AWS redshift
【发布时间】:2019-05-22 07:52:12
【问题描述】:

我想每天更新 AWS 中的一个表,我打算先使用 Python psycopg2 删除 AWS 中公共表中的数据/行,然后将 python 数据帧数据插入该表中。

import psycopg2
import pandas as pd

con=psycopg2.connect(dbname= My_Credential.....)
cur = con.cursor()

sql = """
DELETE FROM tableA
"""

cur.execute(sql)
con.commit()

上面的代码可以做delete,但是我不知道怎么写python代码来插入My_Dataframe到tableA。 TableA 大小大约是 100 万行到 500 万行,请指教。

【问题讨论】:

  • 您的数据集有多大?如果你用 psycopg2 插入会很慢,你可以写入 S3 并使用copy 命令加载到 Redshift
  • 同样根据您的要求,如果您需要定期删除和重新加载表格,您可以使用truncate,它会更快更明智
  • @mdem7 100万到500万行,你知道怎么用truncate吗?
  • 对于这么多行,如果你从 python 插入会非常慢,你需要使用copy。对于截断,语法是 truncate table tableA

标签: python python-3.x amazon-web-services amazon-redshift


【解决方案1】:

我同意 @mdem7 在评论中的建议,使用 dataframe 插入 1-5 百万数据根本不是一个好主意,您将面临性能问题。

最好使用S3Redshift 加载方法。这是您执行TruncateCopy 命令的代码。

import psycopg2


def redshift():

    conn = psycopg2.connect(dbname='database_name', host='888888888888****.u.****.redshift.amazonaws.com', port='5439', user='username', password='********')
    cur = conn.cursor();

    cur.execute("truncate table example;")

    //Begin your transaction
    cur.execute("begin;")
    cur.execute("copy example from 's3://examble-bucket/example.csv' credentials 'aws_access_key_id=ID;aws_secret_access_key=KEY/KEY/pL/KEY' csv;")
    ////Commit your transaction
    cur.execute("commit;")
    print("Copy executed fine!")

redshift();

CopyMenifest option 中还有更多方法可以让Copy 更快,以便Redshift 可以并行加载数据。 希望这能给你一些搬家的想法。

【讨论】:

【解决方案2】:

关于如何在下面的 conde 中传递连接字符串代替连接详细信息的任何建议:-

conn = psycopg2.connect(dbname ='' ,host='' ...) 
i am looking to pass like this ..

conn = psycopg2.connect('Connection_String') 

【讨论】:

  • 最好为此创建一个新问题。
猜你喜欢
  • 1970-01-01
  • 2013-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-05
相关资源
最近更新 更多