BigQuery Python 客户端:使用表描述通过查询创建表

orc*_*man 5 python google-bigquery

我正在使用 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))
Run Code Online (Sandbox Code Playgroud)

除了通过 SQL 查询创建表的客户端函数使用 job_config 对象,并且 job_config 接收 table_ref 而不是表对象之外,这种方法运行良好。

我在这里找到了用于创建带有描述的表的文档:https://google-cloud-python.readthedocs.io/en/stable/bigquery/usage.html,但这适用于不是从查询创建的表。

关于如何在指定该表的描述的同时从查询创建表的任何想法?

Tam*_*ein 2

由于您想要做的不仅仅是将SELECT结果保存到新表中,因此最好的方法不是在job_config变量中使用目标表,而是使用CREATE命令

所以你需要做两件事:

  1. 从代码中删除以下两行
table_ref = client.dataset(dataset_id).table('your_table_id')   
job_config.destination = table_ref
Run Code Online (Sandbox Code Playgroud)
  1. 用这个替换你的 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;
Run Code Online (Sandbox Code Playgroud)