LoginSignup
0
0

More than 1 year has passed since last update.

ColaboratoryでBigQueryにアクセスする一番楽な方法

Last updated at Posted at 2022-04-08

公式のBigQueryのクライアントAPIを使う

ColaboratoryはGoogleアカウントがあれば使える
さらにこのアカウントはGCPアカウントとしてユーザーの認証を事前に通しておく必要がある

実際にデータを取得してみる

ColaboratoryではGCP関連のライブラリはディフォルトでインストールされているので、pip install等は書く必要がない
Colaboratoryでは不要だが、Colaboratory以外で実行する場合には下記を実行する必要がある
pip install --upgrade google-cloud-bigquery

今回はウマ娘というソーシャルゲームのデータベースからデータを取得する体でpythonコードを書いてみた

qiita.rb
#ColaboratoryでGoogleアカウントを認証する
from google.colab import auth
auth.authenticate_user()

from google.cloud import bigquery
project_id = 'uma_musume-2021'
client = bigquery.Client(project=project_id)

# 実行するクエリ
query =  """
                SELECT  
                COUNT(*) as cnt
                FROM 
                `uma_musume-2021.honban01.accesslog_20220407` 
                ;
         """
df_official = client.query(query).to_dataframe()

df_official

結果のテーブル

cnt
292281265

1日で2億9000万程度のレコードが記録されていることがわかる(適当に予想した数値)

その他

公式のBigQueryのクライアントAPIを使う以外にもColaboratoryでBigQueryにアクセスする方法がある

①ColaboratoryのMagic Command
②pandas経由のAPI

皆さんは色々試してみてください。
自分は公式のBigQueryのクライアントAPIを使用するやつのコードが読み取りやすかっただけです。

0
0
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
0
0