【问题标题】:How to append query results using BigQuery Python API如何使用 BigQuery Python API 附加查询结果
【发布时间】:2020-09-12 04:20:17
【问题描述】:

我找不到将查询结果附加到 BigQuery 中已存在且按小时分区的表的方法。 我只找到了这个解决方案:https://cloud.google.com/bigquery/docs/writing-results#writing_query_results

job_config = bigquery.QueryJobConfig(destination=table_id)

sql = """SELECT * FROM table1 JOIN table2 ON table1.art_n=table2.artn"""

# 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.

但是向bigquery.QueryJobConfig 提供目标表会覆盖它,我没有发现bigquery.QueryJobConfig 可以选择指定if_exists 或其他东西。据我了解,我需要申请job.insert来查询结果,但我不明白如何。

我也没有找到任何好的建议,也许有人可以指点我吗?

以防万一,我的实际查询很大,我从单独的 JSON 文件中加载它。

【问题讨论】:

    标签: python api google-bigquery sql-insert


    【解决方案1】:

    创建job_config时,需要将write_disposition设置为WRITE_APPEND

    [..]
    job_config = bigquery.QueryJobConfig(
        allow_large_results=True, 
        destination=table_id, 
        write_disposition='WRITE_APPEND'
    )
    [..]
    

    here

    【讨论】:

      【解决方案2】:

      您可以添加以下行以将数据附加到现有表中:

      job_config.write_disposition = 'WRITE_APPEND'
      

      完整代码:

      from google.cloud import bigquery
      client = bigquery.Client()
      job_config = bigquery.QueryJobConfig(destination="myproject.mydataset.target_table")
      job_config.write_disposition = 'WRITE_APPEND'   
      sql = """SELECT * FROM table1 JOIN table2 ON table1.art_n=table2.artn"""
      query_job = client.query(sql, job_config=job_config)
      query_job.result()
      

      【讨论】:

        【解决方案3】:

        您要查找的参数称为write_disposition。您想使用 WRITE_APPEND 追加到表中。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-30
          • 2015-07-26
          • 2022-07-22
          • 2023-03-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多