python - BigQuery Python 客户端 : Creating a Table from Query with a Table Description

标签 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))

这很有效,除了通过 SQL 查询创建表的客户端函数使用 job_config 对象,并且 job_config 接收 table_ref,而不是表对象。

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

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

最佳答案

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

所以你需要做两件事:

  1. 从代码中删除以下 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/

    相关文章:

    python - 使用 python 最通用的列映射

    go - 将超过 7 天的数据插入分区的 BigQuery 表

    sql - 在 BigQuery 中使用 LEAD

    python - user32.SwitchDesktop 仅在 Debug模式下工作 - Python Windows 服务

    python - 将 FreeTDS ODBC 与 pyodbc 结合使用时,glibc 检测到损坏的双链表

    google-bigquery - BigQuery 在嵌套字段上插入更新

    google-bigquery - 使用 COUNT(DISTINCT ...) 时出现 BigQuery 错误 "Response too large to return"

    python - 如何从Python中的以下内容获取表名

    Python pandas CustomBusinessDay

    python - 在 bash 中调用一个 python 进程,然后将输出捕获到一个变量中