我正在使用 python 客户端通过 SQL 创建表,如文档 ( https://cloud.google.com/bigquery/docs/tables ) 中所述,如下所示:
# from google.cloud import bigquery
# client = bigquery.Client()
# dataset_id = 'your_dataset_id'
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))
这很有效,除了通过 SQL 查询创建表的客户端函数使用 job_config 对象,并且 job_config 接收 table_ref,而不是表对象。
我在这里找到了用于创建表并带有描述的文档:https://google-cloud-python.readthedocs.io/en/stable/bigquery/usage.html ,但这适用于不是从查询创建的表。
关于如何在指定该表的描述的同时从查询创建表有什么想法吗?
最佳答案
由于您想要做的不仅仅是将 SELECT
结果保存到新表中,因此最好的方法不是在 job_config
变量中使用目标表,而是使用一个CREATE
命令
所以你需要做两件事:
- 从代码中删除以下 2 行
table_ref = client.dataset(dataset_id).table('your_table_id')
job_config.destination = table_ref
- 用此替换您的 SQL
#standardSQL
CREATE TABLE dataset_id.your_table_id
PARTITION BY DATE(_PARTITIONTIME)
OPTIONS(
description = 'this table was created via agent #123'
) AS
SELECT corpus
FROM `bigquery-public-data.samples.shakespeare`
GROUP BY corpus;
关于python - BigQuery Python 客户端 : Creating a Table from Query with a Table Description,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55549490/