19

Python API 経由でGoogle BigQueryを使用しています。クエリ結果からテーブル (新しいテーブルまたは古いテーブルを上書き) を作成するにはどうすればよいですか? クエリのドキュメントを確認しましたが、役に立ちませんでした。

シミュレートしたいこと:

ANSI SQL の「SELECT ... INTO ...」。

4

3 に答える 3

16

これを行うには、クエリで宛先テーブルを指定します。呼び出しでJobs.insertはなく APIを使用する必要があり、宛先テーブルを指定して入力する必要があります。Jobs.querywriteDisposition=WRITE_APPEND

未加工の 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",
  }
}
于 2013-01-31T20:38:00.753 に答える
15

受け入れられた答えは正しいですが、タスクを実行するための Python コードを提供していません。これは、先ほど書いた小さなカスタム クライアント クラスからリファクタリングされた例です。例外を処理しないため、ハードコーディングされたクエリをカスタマイズして、単にSELECT *...

import time

from google.cloud import bigquery
from google.cloud.bigquery.table import Table
from google.cloud.bigquery.dataset import Dataset


class Client(object):

    def __init__(self, origin_project, origin_dataset, origin_table,
                 destination_dataset, destination_table):
        """
        A Client that performs a hardcoded SELECT and INSERTS the results in a
        user-specified location.

        All init args are strings. Note that the destination project is the
        default project from your Google Cloud configuration.
        """
        self.project = origin_project
        self.dataset = origin_dataset
        self.table = origin_table
        self.dest_dataset = destination_dataset
        self.dest_table_name = destination_table
        self.client = bigquery.Client()

    def run(self):
        query = ("SELECT * FROM `{project}.{dataset}.{table}`;".format(
            project=self.project, dataset=self.dataset, table=self.table))

        job_config = bigquery.QueryJobConfig()

        # Set configuration.query.destinationTable
        destination_dataset = self.client.dataset(self.dest_dataset)
        destination_table = destination_dataset.table(self.dest_table_name)
        job_config.destination = destination_table

        # Set configuration.query.createDisposition
        job_config.create_disposition = 'CREATE_IF_NEEDED'

        # Set configuration.query.writeDisposition
        job_config.write_disposition = 'WRITE_APPEND'

        # Start the query
        job = self.client.query(query, job_config=job_config)

        # Wait for the query to finish
        job.result()
于 2017-05-22T16:12:25.363 に答える