LoginSignup
4
1

More than 3 years have passed since last update.

BigQuery Storage APIを使ってみた

Posted at

はじめに

基本的な機械学習の手順:②データを準備しようでは、BigQueryで作ったテーブルをPytohn環境にPandas Dataframe形式で取り込む処理をしてきました。

ただ、テーブルのサイズが大きくなると、結構時間がかかってしまいます。
たぶん、そんな悩みを持つ方が多かったのでしょう。そこで出てきたのが、BigQuery Storage APIという新たなサービス。

一説には7~8倍も速いと聞きましたが、どうなのでしょう。試してみたいと思います。

分析環境

Google BigQuery
Google Colaboratory

参考にしたサイト

BigQuery Storage API を使用して BigQuery データを pandas にダウンロードする

対象とするデータ

用いるテーブルは、myproject.mydataset.mytableという約100MBのテーブルです。
それを、下記の様に全件取ってくるだけというシンプルな処理で、Pandas Dataframe形式で取り込みます。

query="SELECT * FROM `myproject.mydataset.mytable`

1.BigQuery 標準API

まずは、これまでも使っているBigQueryの標準APIでやってみます。

import time
from google.cloud import bigquery
start = time.time()

client = bigquery.Client(project="myproject")
df = client.query(query).to_dataframe()

elapsed_time = time.time() - start

約120秒で処理できました。まあ、これくらいなら許容範囲ですが。

2.Pandas read_gbq

BigQueryのAPIを使わなくても、Pandasの機能でできるよね。ということで、そちらも試してみます。

import time
import pandas as pd

start = time.time()

df = pd.io.gbq.read_gbq(query, project_id="myproject", dialect="standard")

elapsed_time = time.time() - start

約135秒で処理が完了。BigQueryのAPIより少し遅くなっていますね。
BigQueryの標準APIでも、Pandasの機能に比べると、何か工夫がされているようです。

3.BigQuery Storage API

そして、今回のテーマであるBigQuery Storage APIの出番です。
Colabでライブラリーをimportしようとしたら、ライブラリーが無いよと言われてしまったので、まずはinstallから。

pip install --upgrade google-cloud-bigquery-storage

と、インストールするとランタイムの再起動を求めるメッセージが。時々他のライブラリーでも出ますが、ちょっと面倒ですね。

WARNING: The following packages were previously imported in this runtime:
  [google]
You must restart the runtime in order to use newly installed versions.

さて、ランタイムを再起動して、改めてライブラリーをimportして実行します。

import time
from google.cloud import bigquery
from google.cloud import bigquery_storage
start = time.time()

client = bigquery.Client(project="myproject")
bqstorageclient = bigquery_storage.BigQueryStorageClient()
df3 = (
    client.query(query)
    .result()
    .to_dataframe(bqstorage_client=bqstorageclient)
)

elapsed_time = time.time() - start

実行時間は、なんと驚異の約12秒。標準APIの7~8倍どころか、10倍出てます。
偶然かと思って、何度かやってみましたが、1~2秒程度の誤差はあるものの、ほぼこのスピードで完了しました。

おわりに

予想よりもかなり速い結果が返ってきて、ビックリしました。
普段の10倍速ければ、数GBとかのデータも短時間で取り込むことが可能ですね。(その後のPythonでの処理が重そうですが)

普通にBigQueryを回すのに加えて、$1.10 per TBと費用が掛かるので、乱発はできませんが、テーブルが大きすぎてデータ取り込みに何十分も待たないといけない、というときには使っていきたいサービスですね。

4
1
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
1