このチュートリアルでは、BigQuery にクエリを送信する Cloud Functions の HTTP 関数の作成について説明します。
目標
- BigQuery にクエリを送信する HTTP Cloud Functions の関数を作成する。
費用
このドキュメントでは、Google Cloud の次の課金対象のコンポーネントを使用します。
- Cloud Functions
- Cloud Build
- Artifact Registry
詳細については、Cloud Functions の料金をご覧ください。
料金計算ツールを使うと、予想使用量に基づいて費用の見積もりを生成できます。
始める前に
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。
-
Cloud Functions, Cloud Build, and Artifact Registry API を有効にします。
- Google Cloud CLI をインストールします。
-
gcloud CLI を初期化するには:
gcloud init
-
Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。
-
Cloud Functions, Cloud Build, and Artifact Registry API を有効にします。
- Google Cloud CLI をインストールします。
-
gcloud CLI を初期化するには:
gcloud init
-
開発環境を準備します。
gcloud CLI がすでにインストールされている場合は、次のコマンドを実行して更新します。
gcloud components update
アプリケーションの準備
ローカルマシンにサンプルアプリのリポジトリのクローンを作成します。
git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git
または、zip 形式のサンプルをダウンロードし、ファイルを抽出してもかまいません。
Cloud Functions のサンプルコードが含まれているディレクトリに移動します。
cd nodejs-docs-samples/functions/v2/helloBigQuery
サンプルコードを見てみましょう。このサンプルは、指定したデータセットで 400 回以上発生した単語をクエリし、結果を返します。
関数のデプロイ
HTTP トリガーを使用して関数をデプロイするには、サンプルコードを含むディレクトリで次のコマンドを実行します。
gcloud functions deploy nodejs-bq-function \ --gen2 \ --runtime=nodejs20 \ --region=REGION \ --source=. \ --entry-point=helloBigQuery \ --trigger-http \ --allow-unauthenticated
優先する Node.js のバージョンを指定するには、--runtime
フラグに次の値を使用します。
nodejs18
(推奨)nodejs16
nodejs14
nodejs12
nodejs10
--allow-unauthenticated
フラグを使用すると、認証なしで関数にアクセスできます。認証を要求するには、フラグを省略します。
関数のトリガー
関数がデプロイされたら、
uri
プロパティをメモするか、次のコマンドを使用して検索します。gcloud functions describe nodejs-bq-function --gen2 --region=REGION --format="value(serviceConfig.uri)"
ブラウザでこの URI にアクセスします。クエリ条件に一致する単語のリストと、各単語がターゲット データセットに出現する回数が表示されます。
クリーンアップ
このチュートリアルで使用したリソースについて、Google Cloud アカウントに課金されないようにするには、リソースを含むプロジェクトを削除するか、プロジェクトを維持して個々のリソースを削除します。
プロジェクトの削除
課金をなくす最も簡単な方法は、チュートリアル用に作成したプロジェクトを削除することです。
プロジェクトを削除するには:
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.
Cloud Functions の関数の削除
Cloud Functions を削除しても、Cloud Storage に保存されたリソースは削除されません。
このチュートリアルで作成した Cloud Functions の関数を削除するには、次のコマンドを実行します。
gcloud functions delete nodejs-bq-function --gen2 --region REGION
Google Cloud コンソールから Cloud Functions の関数を削除することもできます。