Postgres 9.4:COPY与转换步骤



我有一些非常大的CSV文件,我正在使用Postgres 9.4。我正在使用Postgres的COPY命令将它们高效地导入我的数据库。这很好:

    cursor = conn.cursor()
    copy_str = "COPY mytable(presentation_code,quantity,"
    copy_str += "processing_date,price_per_unit) FROM STDIN "
    copy_str += "WITH DELIMITER AS ','"
    file_obj = open(filename)
    cursor.copy_expert(copy_str, file_obj)
    try:
        conn.commit()
    except Exception as err:
        print 'EXCEPTION:', err

问题是,在适合COPY之前,我必须对数据文件运行一些转换步骤。其中包括重新排序字段,将字符串转换为浮点值,转换日期以使其适合Postgres,以及计算一些值(尽管我可能会跳过最后一步):

for row in reader:
    presentation_code = row[0].strip()
    quantity = int(row[1])
    period = row[9]
    processing_date = period[:4] + '-' + period[4:] + '-01'
    if row[4]:
        price_per_unit = actual_cost / float(row[4])
    else:
        price_per_unit = 0
    output = [presentation_code, quantity, processing_date, price_per_unit]
    writer.writerow(output)

有没有Postgres工具可以让我在一个命令中完成这两个步骤(转换,然后是COPY)?还是这只是一个必要的步骤?

您必须将转换编写为一个程序,将每一行从其标准输入获取到标准输出,然后将其用作copy命令本身的筛选器。有关详细信息,请参阅副本的手册页(参见"程序"部分):http://www.postgresql.org/docs/9.4/static/sql-copy.html.请注意,该程序将以"postgres"用户的身份运行(如果您想从客户端应用程序运行它,可以使用psql的\copy命令,http://www.postgresql.org/docs/9.4/static/app-psql.html)。

最新更新