Python 中的 Bigquery:如何将查询结果放入 table?

Bigquery in Python: How to put the results of a query in a table?

我最近开始在 Python2.7 中使用 BigQuery,但在将查询结果放入 table.

时遇到问题

我的查询:

query_data = {
    'configuration': {
        'query': {
            'query': QUERY
            'destinationTable': {
                'projectId': project_id,
                'datasetId': dataset_id,
                'tableId': 'table_id'
            },
            'createDisposition': 'CREATE_IF_NEEDED',
            'writeDisposition': 'WRITE_TRUNCATE',
            'allowLargeResults': True
        },
    }
}

query_request.query(projectId=PROJECT_NUMBER,body=query_data).execute()

根据我在 Google BigQuery documentationdestinationTablecreateDispositionwriteDisposition 中阅读的内容,应该确保我的查询结果最终出现在所选的 BigQuery table.

但它没有,我得到这个错误:

HttpError: https://www.googleapis.com/bigquery/v2/projects/project_id/queries?alt=json returned "Required parameter is missing">

有人知道如何修复这个错误吗?


PS: 'QUERY' 当我直接在 Google BigQuery 网站上使用它时有效,所以我非常怀疑问题出在那里。

PPS: 感谢@Pentium10 我能够解决这个问题。

您可以通过在查询中指定目的地 table 来完成此操作。您需要使用 Jobs.insert api 而不是 Jobs.query 调用,并且您应该指定 writeDisposition=WRITE_APPEND 并填写目标 table.

如果您使用的是原始 api,配置会是这样的。如果您使用 Python,python 客户端应该为这些相同的字段提供访问器:

"configuration": {
  "query": {
    "query": "select count(*) from foo.bar",
    "destinationTable": {
      "projectId": "my_project",
      "datasetId": "my_dataset",
      "tableId": "my_table"
    },
    "createDisposition": "CREATE_IF_NEEDED",
    "writeDisposition": "WRITE_APPEND",
  }
}