代码之家  ›  专栏  ›  技术社区  ›  kee

如何在BigQuery客户端pythonapi中以原子方式覆盖表

  •  2
  • kee  · 技术社区  · 7 年前

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

    这可以正常工作,但如果表已经存在,则会抛出一个错误。我知道如何首先删除表,但我想知道是否有一种方法可以使它以原子方式覆盖表,从而使表始终存在。

    1 回复  |  直到 5 年前
        1
  •  2
  •   shollyman    7 年前

    您可以通过组合设置create\u处置和write\u处置来控制结果的持久化方式。python库在中公开了这些选项 QueryJobConfig ,并链接到RESTAPI文档中的更多详细信息。

    WRITE_EMPTY ,如果表已存在,则会导致失败。把它换成 WRITE_TRUNCATE 应该给你的原子替换的数据,你正在寻找。

    TL;DR: 只需将此添加到作业配置中:

    job_config.write_disposition = bigquery.WriteDisposition.WRITE_TRUNCATE