BigQuery のチュートリアル(第 2 世代)


このチュートリアルでは、BigQuery にクエリを送信する Cloud Functions の HTTP 関数の作成について説明します。

目標

費用

このドキュメントでは、Google Cloud の次の課金対象のコンポーネントを使用します。

  • Cloud Functions
  • Cloud Build
  • Artifact Registry

詳細については、Cloud Functions の料金をご覧ください。

料金計算ツールを使うと、予想使用量に基づいて費用の見積もりを生成できます。 新しい Google Cloud ユーザーは無料トライアルをご利用いただける場合があります。

始める前に

  1. 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.
  2. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  3. Google Cloud プロジェクトで課金が有効になっていることを確認します

  4. Cloud Functions, Cloud Build, and Artifact Registry API を有効にします。

    API を有効にする

  5. Google Cloud CLI をインストールします。
  6. gcloud CLI を初期化するには:

    gcloud init
  7. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  8. Google Cloud プロジェクトで課金が有効になっていることを確認します

  9. Cloud Functions, Cloud Build, and Artifact Registry API を有効にします。

    API を有効にする

  10. Google Cloud CLI をインストールします。
  11. gcloud CLI を初期化するには:

    gcloud init
  12. gcloud CLI がすでにインストールされている場合は、次のコマンドを実行して更新します。

    gcloud components update
  13. 開発環境を準備します。

    Node.js 設定ガイドに移動

アプリケーションの準備

  1. ローカルマシンにサンプルアプリのリポジトリのクローンを作成します。

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    または、zip 形式のサンプルをダウンロードし、ファイルを抽出してもかまいません。

  2. Cloud Functions のサンプルコードが含まれているディレクトリに移動します。

    cd nodejs-docs-samples/functions/v2/helloBigQuery
  3. サンプルコードを見てみましょう。このサンプルは、指定したデータセットで 400 回以上発生した単語をクエリし、結果を返します。

    // Import the Google Cloud client library
    const {BigQuery} = require('@google-cloud/bigquery');
    const bigquery = new BigQuery();
    
    const functions = require('@google-cloud/functions-framework');
    
    /**
     * HTTP Cloud Function that returns BigQuery query results
     *
     * @param {Object} req Cloud Function request context.
     * @param {Object} res Cloud Function response context.
     */
    functions.http('helloBigQuery', async (req, res) => {
      // Define the SQL query
      // Queries the public Shakespeare dataset using named query parameter
      const sqlQuery = `
          SELECT word, word_count
                FROM \`bigquery-public-data.samples.shakespeare\`
                WHERE corpus = @corpus
                AND word_count >= @min_word_count
                ORDER BY word_count DESC`;
    
      const options = {
        query: sqlQuery,
        // Location must match that of the dataset(s) referenced in the query.
        location: 'US',
        params: {corpus: 'romeoandjuliet', min_word_count: 400},
      };
    
      // Execute the query
      try {
        const [rows] = await bigquery.query(options);
        // Send the results
        res.status(200).send(rows);
      } catch (err) {
        console.error(err);
        res.status(500).send(`Error querying BigQuery: ${err}`);
      }
    });

関数のデプロイ

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 フラグを使用すると、認証なしで関数にアクセスできます。認証を要求するには、フラグを省略します。

関数のトリガー

  1. 関数がデプロイされたら、uri プロパティをメモするか、次のコマンドを使用して検索します。

    gcloud functions describe nodejs-bq-function --gen2 --region=REGION --format="value(serviceConfig.uri)"
  2. ブラウザでこの URI にアクセスします。クエリ条件に一致する単語のリストと、各単語がターゲット データセットに出現する回数が表示されます。

クリーンアップ

このチュートリアルで使用したリソースについて、Google Cloud アカウントに課金されないようにするには、リソースを含むプロジェクトを削除するか、プロジェクトを維持して個々のリソースを削除します。

プロジェクトの削除

課金をなくす最も簡単な方法は、チュートリアル用に作成したプロジェクトを削除することです。

プロジェクトを削除するには:

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. 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 の関数を削除することもできます。