python - 如何在 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))
这工作正常,但如果表已经存在,这会吐出一个错误。我知道如何首先删除表,但我想知道是否有办法让它以原子方式覆盖表,以便表始终存在。
解决方案
您可以通过设置 create_disposition 和 write_disposition 的组合来控制结果的持久化方式。python 库在QueryJobConfig中公开了这些选项,并链接到来自 REST API 文档的更多详细信息。
对于查询,写入处置的默认行为是WRITE_EMPTY
,如果表已经存在,则会导致失败。将其切换为WRITE_TRUNCATE
应该可以原子替换您正在寻找的数据。
TL;DR:只需将其添加到您的工作配置中:
job_config.write_disposition = bigquery.WriteDisposition.WRITE_TRUNCATE
推荐阅读
- php - htaccess 多次重写问题
- javascript - 当我重新加载页面并且没有检查 Laravel 6.0 中的单选按钮之一时,如何一次只显示一个表单
- android - 如果数据是通过意图从另一个活动获取的,如何使用文本观察器添加多个文本视图
- python - 在特定时间向视频添加文字
- css - 如何打破表 td 内的长帖子标题?
- electron - node-keytar,机器范围的凭证
- python-3.x - 如何使用 Sublime Text 编译 Python 3 程序
- c++ - 非静态成员引用必须相对于特定对象
- java - Android / JAVA:根据时区获取当前时间
- vue.js - Vuejs - 如何将新值添加到 itemList 数组中