Mal*_*ode 1 python google-api google-bigquery
我正在编写一个将查询结果写入 BQ 表的 python 脚本。第一次运行脚本后,它总是在此之后出错,并显示以下错误:google.api_core.exceptions.Conflict: 409 Already Exists: Table project-id.dataset-id
. 我不明白为什么每次运行脚本时它都试图创建一个表。我是否指定了任何特定参数?
这是来自谷歌的文档。我以此为例,并认为已经创建了当前表。我在哪里可以阻止 api 创建同一个表?
from google.cloud import bigquery
# TODO(developer): Construct a BigQuery client object.
client = bigquery.Client()
# TODO(developer): Set table_id to the ID of the destination table.
table_id = "your-project.your_dataset.your_table_name"
job_config = bigquery.QueryJobConfig(destination=table_id)
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, job_config=job_config) # Make an API request.
query_job.result() # Wait for the job to complete.
print("Query results loaded to the table {}".format(table_id))
Run Code Online (Sandbox Code Playgroud)
如果您检查QueryJobConfig类,您将看到有一个名为write_dispotition
. 正如您在此处的 REST API 参考中所见,此参数可以设置为 3 个不同的选项:
WRITE_TRUNCATE
:如果表已存在,BigQuery 会覆盖表数据并使用查询结果中的架构。WRITE_APPEND
:如果表已存在,BigQuery 会将数据追加到表中。WRITE_EMPTY
: 如果表已经存在并且包含数据,则作业结果中会返回“重复”错误。因此,在job_config
定义之后添加这一行就可以解决问题:
job_config.write_disposition = bigquery.WriteDisposition.WRITE_TRUNCATE
Run Code Online (Sandbox Code Playgroud)