我正在编写一个将查询结果写入 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))
最佳答案
如果你检查类QueryJobConfig您会看到有一个名为 write_dispotition
的参数。正如您在 REST API 引用中所见 here ,这个参数可以设置为 3 个不同的选项:
WRITE_TRUNCATE
:如果表已存在,BigQuery 会覆盖表数据并使用查询结果中的架构。WRITE_APPEND
:如果表已存在,BigQuery 会将数据附加到表中。WRITE_EMPTY
:如果表已经存在并且包含数据,作业结果中会返回“重复”错误。
所以,在 job_config
定义之后添加这一行就可以了:
job_config.write_disposition = bigquery.WriteDisposition.WRITE_TRUNCATE
关于python - BigQuery Python 409 已存在 : Table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60836940/