首页 > 解决方案 > 如何在 BigQuery 客户端 Python API 中以原子方式覆盖表

问题描述

这是我用作 GCP 文档参考的代码片段:

job_config = bigquery.QueryJobConfig()
# Set the destination table
table_ref = client.dataset(dataset_id).table('your_table_id')
job_config.destination = table_ref
sql = """
    SELECT corpus
    FROM `bigquery-public-data.samples.shakespeare`
    GROUP BY corpus;
"""

# Start the query, passing in the extra configuration.
query_job = client.query(
    sql,
    # Location must match that of the dataset(s) referenced in the query
    # and of the destination table.
    location='US',
    job_config=job_config)  # API request - starts the query

query_job.result()  # Waits for the query to finish
print('Query results loaded to table {}'.format(table_ref.path))

这工作正常,但如果表已经存在,这会吐出一个错误。我知道如何首先删除表,但我想知道是否有办法让它以原子方式覆盖表,以便表始终存在。

标签: pythongoogle-bigquery

解决方案


您可以通过设置 create_disposition 和 write_disposition 的组合来控制结果的持久化方式。python 库在QueryJobConfig中公开了这些选项,并链接到来自 REST API 文档的更多详细信息。

对于查询,写入处置的默认行为是WRITE_EMPTY,如果表已经存在,则会导致失败。将其切换为WRITE_TRUNCATE应该可以原子替换您正在寻找的数据。

TL;DR:只需将其添加到您的工作配置中:

job_config.write_disposition = bigquery.WriteDisposition.WRITE_TRUNCATE

推荐阅读