0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

bigquery-magics を使って VSCode の Jupyter から BigQuery のクエリを実行する

Posted at

概要

bigquery-magics を用いることで、以下のようにVSCode上のJupyterノートブックからBigQueryのクエリを実行することができます。

result_query

ここでは、この bigquery-magics の導入手順および使い方を紹介します。

実行環境

bigquery-magicspip を用いて以下のコマンドでインストールします。

PowerShell
pip install bigquery-magics

conda を用いる場合は以下の通りです。

PowerShell
conda install conda-forge::bigquery-magics

初期設定およびクエリの実行

JupyterノートブックをVSCodeで開き、セルに以下を入力し実行します。

Jupyter セル 1
# Jupyter用拡張機能の読み込み
%reload_ext bigquery_magics

import bigquery_magics

# BigQueryのプロジェクトIDを指定
bigquery_magics.context.project = "bq-project-012345"

また、マジックコマンド %%bigquery と実行したいクエリを以下のように入力します。

Jupyter セル 2
%%bigquery
SELECT "apple" AS fruit, "carrot" AS vegetable

上記のセルを初めて実行するとURLが表示されるので、クリックしてブラウザでアクセスします。

image.png

Googleアカウントへのログインが要求されるので、アカウントを選択します。

login

問題なければそのままアクセス権を付与します。

authorize

ログインおよびアクセス権の付与が完了すると以下のページが表示されるので、 Copy ボタンを押して認証コードをコピーします。

copy_verification_code

VSCodeに戻り、URLと同時に表示されていた入力欄にコピーした認証コードを入力します。

enter_verification_code

アクセスに成功すると、以下のようにクエリ結果が表示されます。

result_query

以上でJupyterノートブックからBigQueryのクエリが可能になりました。

クエリ結果をデータフレームとして取得する

以下のようにマジックコマンドのオプションに任意の変数名を指定することで、クエリ結果をデータフレームとして取得することもできます。

Jupyter セル 3
%%bigquery df
SELECT "apple" AS fruit, "carrot" AS vegetable

ここでは df という変数にクエリ結果がDataFrameとして代入されるので、以降のセルで一般的なDataFrameの変数として利用することができます。

Jupyter セル 4
display(type(df))
display(df)

use_variable

非推奨:google.cloud.bigquery からの呼び出し

マジックコマンドは以下のように google-cloud-bigquery パッケージからの呼び出しも可能です。

Jupyter セル 1
# Jupyter用拡張機能の読み込み
%reload_ext google.cloud.bigquery

from google.cloud.bigquery import magics

# BigQueryのプロジェクトIDを指定
magics.context.project = "bq-project-012345"

しかし、クエリ実行時に表示される以下の警告の通り、現在では google.cloud.bigquery の使用は非推奨となっており、bigquery_magics の使用が推奨されています。

FutureWarning: %load_ext google.cloud.bigquery is deprecated. Install bigquery-magics package and use %load_ext bigquery_magics, instead.

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?