BigQuery 教程(第 2 代)


本教程演示了如何编写将查询提交到 BigQueryHTTP Cloud Functions 函数

目标

费用

在本文档中,您将使用 Google Cloud 的以下收费组件:

  • Cloud Functions
  • Cloud Build
  • Artifact Registry

如需了解详情,请参阅 Cloud Functions 价格

您可使用价格计算器根据您的预计使用情况来估算费用。 Google Cloud 新用户可能有资格申请免费试用

准备工作

  1. 登录您的 Google Cloud 账号。如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. 确保您的 Google Cloud 项目已启用结算功能

  4. 启用 Cloud Functions, Cloud Build, and Artifact Registry API。

    启用 API

  5. 安装 Google Cloud CLI。
  6. 如需初始化 gcloud CLI,请运行以下命令:

    gcloud init
  7. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  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

您可以使用 --runtime 标志的以下值来指定偏好的 Node.js 版本:

  • 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. 在 Google Cloud 控制台中,进入管理资源页面。

    转到“管理资源”

  2. 在项目列表中,选择要删除的项目,然后点击删除
  3. 在对话框中输入项目 ID,然后点击关闭以删除项目。

删除 Cloud Functions 函数

删除 Cloud Functions 函数不会移除存储在 Cloud Storage 中的任何资源。

如需删除您在本教程中创建的 Cloud Functions 函数,请运行以下命令:

gcloud functions delete nodejs-bq-function --gen2 --region REGION

您也可以通过 Google Cloud 控制台 删除 Cloud Functions 函数。