4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

BigQueryからGCSを経由せずにデータをエクスポートする

Last updated at Posted at 2017-05-05

背景

▼BigQueryから大きめのデータを取得するにはGCSを経由して取得するように公式に書いてある
https://cloud.google.com/bigquery/exporting-data-from-bigquery?hl=ja

でもある理由によりあんまりGCSを経由してエクスポートしたくなかったので、色々調べてみた。
以下はpythonとBigQueryクライアントライブラリを利用してデータを取得してくる方法。

やりかた

以下はGoogleAnalyticsのデータをBigQueryで取り扱うことを想定。
クエリを発行して、結果をpandasのDataFrame型に変換するところまでを例にとってみた。あとはto_csv()でCSVファイルにするなりなんなり。


from google.cloud import bigquery
import numpy as np
import pandas as pd

client = bigquery.Client()

QUERY = (
    'SELECT fullVisitorId FROM [${projectId}:${datasetId}.${tableId}]'
    'WHERE totals.newVisits = 1'
)

query = client.run_sync_query(QUERY)
query.timeout_ms = 100000
query.run()

rows = query.rows
token = query.page_token
df = None

'''
結果が100,000行を超える場合そのまま結果を取得できないので、
page_tokenをつかって次のページを取得
'''
while True:
    if df is None:
        df = pd.DataFrame(rows)
    else:
        df = pd.concat([df, rows], axis=1)
        
    if token is None:
        break
    rows, total_count, token = query.fetch_data(page_token=token)

参考にしたページたち

https://pypi.python.org/pypi/google-cloud-bigquery
http://gcloud-python.readthedocs.io/en/latest/bigquery-client.html
https://cloud.google.com/bigquery/docs/reference/libraries?hl=ja
https://cloud.google.com/bigquery/exporting-data-from-bigquery?hl=ja
https://cloud.google.com/bigquery/docs/data?hl=ja

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?