gpt4 book ai didi

python - psycopg2/python 将数据从 postgresql 复制到 Amazon RedShift(postgresql)

转载 作者:行者123 更新时间:2023-11-29 13:27:59 24 4
gpt4 key购买 nike

我想了解社区对“使用 Python 2.7.x 将数据从 PostgreSQL 复制到 RedShift 的最佳方式”的看法。我不能使用 Amazon S3,RedShift 是普通的 postgresql 数据库,但仅支持从 S3 复制(我不能使用)

最佳答案

您可以使用 Python/psycopg2/boto 对其进行端到端编码。 psycopg2 的替代品是 PosgtreSQL 客户端 (psql.exe)。

如果你使用 psycopg2,你可以:

  1. 从 PostgreSQL 假脱机到一个文件
  2. 上传到S3
  3. 附加到 Redshift 表。

如果您使用 psql.exe,您可以:

  1. 将数据从 PostgreSQL 传输到 S3 分段 uploader

    in_qry=open(opt.pgres_query_file, "r").read().strip().strip(';')
    db_client_dbshell=r'%s\bin\psql.exe' % PGRES_CLIENT_HOME.strip('"')
    loadConf=[ db_client_dbshell ,'-U', opt.pgres_user,'-d',opt.pgres_db_name, '-h', opt.pgres_db_server]

    q="""
    COPY ((%s) %s)
    TO STDOUT
    WITH DELIMITER ','
    CSV %s
    """ % (in_qry, limit, quote)
    #print q
    p1 = Popen(['echo', q], stdout=PIPE,stderr=PIPE,env=env)

    p2 = Popen(loadConf, stdin=p1.stdout, stdout=PIPE,stderr=PIPE)

    p1.wait()
    return p2
  2. 上传到 S3。

  3. 使用 psycopg2 追加到 Redshift 表。

    fn='s3://%s' % location
    conn_string = REDSHIFT_CONNECT_STRING.strip().strip('"')
    con = psycopg2.connect(conn_string);
    cur = con.cursor();
    quote=''
    if opt.red_quote:
    quote='quote \'%s\'' % opt.red_quote
    ignoreheader =''
    if opt.red_ignoreheader:
    ignoreheader='IGNOREHEADER %s' % opt.red_ignoreheader
    timeformat=''
    if opt.red_timeformat:
    #timeformat=" dateformat 'auto' "
    timeformat=" TIMEFORMAT '%s'" % opt.red_timeformat.strip().strip("'")
    sql="""
    COPY %s FROM '%s'
    CREDENTIALS 'aws_access_key_id=%s;aws_secret_access_key=%s'
    DELIMITER '%s'
    FORMAT CSV %s
    GZIP
    %s
    %s;
    COMMIT;
    """ % (opt.red_to_table, fn, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY,opt.red_col_delim,quote, timeformat, ignoreheader)
    cur.execute(sql)
    con.close()

我尽力将所有 3 个步骤编译成 one script .

关于python - psycopg2/python 将数据从 postgresql 复制到 Amazon RedShift(postgresql),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30071367/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com