【问题标题】:Bigquery (and pandas) - ensure data-insert consistencyBigquery(和 pandas) - 确保数据插入的一致性
【发布时间】:2018-05-25 02:10:30
【问题描述】:

在我的 python 项目中,我需要用一个关系数据框填充一个 bigquery 表。我在从头开始创建一个新表并确保我上传到它的第一个数据实际上被放入表中时遇到了很多麻烦。

我已阅读页面https://cloud.google.com/bigquery/streaming-data-into-bigquery#dataconsistency 并看到将 insertId 应用于插入查询可以解决问题,但由于我使用 pandas 的数据帧,pandas-gbq 包的函数 to_gbq 似乎非常适合这个任务。然而,当使用 to_gbq 函数并创建/替换新表时,有时(显然是随机的)第一个数据块不会写入表中。

有人知道如何确保将 DataFrame 完全插入到 bigquery 新创建的表中吗?谢谢

【问题讨论】:

    标签: python pandas dataframe google-bigquery google-cloud-platform


    【解决方案1】:

    相信你遇到的是https://github.com/pydata/pandas-gbq/issues/75。基本上,Pandas 使用 BigQuery 流式 API 将数据写入表中,但流式 API 在创建表后到开始工作时会有延迟。

    编辑:pandas-gbq 的 0.3.0 版通过使用加载作业将数据帧上传到 BigQuery 而不是流式传输来解决此问题。

    同时,我建议使用“加载作业”来创建表。例如,使用google-cloud-bigquery 包中的client.load_table_from_file 方法。

    from google.cloud.bigquery import LoadJobConfig
    from six import StringIO
    
    destination_table = client.dataset(dataset_id).table(table_id)
    job_config = LoadJobConfig()
    job_config.write_disposition = 'WRITE_APPEND'
    job_config.source_format = 'NEWLINE_DELIMITED_JSON'
    rows = []
    
    for row in maybe_a_dataframe:
        row_json = row.to_json(force_ascii=False, date_unit='s', date_format='iso')
        rows.append(row_json)
    
    body = StringIO('{}\n'.format('\n'.join(rows)))
    
    client.load_table_from_file(
        body,
        destination_table,
        job_config=job_config).result()
    

    编辑: 对于包含非 ASCII 字符的列,此代码示例失败。见https://github.com/pydata/pandas-gbq/pull/108

    【讨论】:

    • 感谢您的回答。我希望这个问题能很快得到解决,因为使用 pandas 的 to_gbq 函数非常方便!
    • 那么,在当前时间,如何保证数据插入的一致性呢? (也具有非熊猫功能)
    • 同时,我建议使用“加载作业”来创建表。例如,使用google-cloud-bigquery 包中的client.load_table_from_file 方法。 googlecloudplatform.github.io/google-cloud-python/latest/…
    • 我添加了一个示例作为此答案的解决方法
    • 刚刚应用了您的解决方案,稍微重写了 to_gbq 函数,看起来工作正常
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    • 2015-12-26
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多