创建一个使用 BigQuery 提交查询并返回结果的 Cloud Run 函数。

本教程介绍如何编写一个 HTTP Cloud Run functions 函数,用于向 BigQuery 提交查询。

目标

在此教程中,您将学习以下操作:

  1. 准备要向 BigQuery 提交查询的应用
  2. 使用 HTTP 触发器部署函数
  3. 测试函数

费用

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

如需根据您的预计使用量来估算费用,请使用价格计算器

新 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. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  5. Verify that billing is enabled for your Google Cloud project.

  6. Enable the Artifact Registry, Cloud Run Admin API, and Cloud Build APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  7. 在 Google Cloud 项目中设置 Cloud Run 开发环境
  8. 如果您通过网域限制组织政策来限制项目的未经身份验证的调用,则您需要按照测试专用服务中的说明访问已部署的服务。

  9. 所需的角色

    如需获得从源代码部署 Cloud Run 服务所需的权限,请让您的管理员为您授予以下 IAM 角色:

    如需查看与 Cloud Run 关联的 IAM 角色和权限的列表,请参阅 Cloud Run IAM 角色Cloud Run IAM 权限。如果您的 Cloud Run 服务与Google Cloud API(例如 Cloud 客户端库)进行交互,请参阅服务身份配置指南。如需详细了解如何授予角色,请参阅部署权限管理访问权限

    Cloud Build 服务账号的角色

    您或您的管理员必须为 Cloud Build 服务账号授予以下 IAM 角色。

    点击可查看 Cloud Build 服务账号需要的角色

    除非您替换此行为,否则 Cloud Build 会自动使用 Compute Engine 默认服务账号作为默认 Cloud Build 服务账号来构建源代码和 Cloud Run 资源。为了让 Cloud Build 能够构建来源,请让管理员向项目的 Compute Engine 默认服务账号授予 Cloud Run Builder (roles/run.builder):

      gcloud projects add-iam-policy-binding PROJECT_ID \
          --member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com \
          --role=roles/run.builder
      

    PROJECT_NUMBER 替换为您的 Google Cloud项目编号,将 PROJECT_ID 替换为您的 Google Cloud项目 ID。如需详细了解如何查找项目 ID 和项目编号,请参阅创建和管理项目

    向 Compute Engine 默认服务账号授予 Cloud Run Builder 角色需要几分钟时间才能传播

准备应用

  1. 将示例应用代码库克隆到本地计算机:

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

    或者,下载该示例的 zip 文件并将其解压缩。

  2. 转到包含示例代码的目录:

    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 触发器部署函数,请执行以下操作:

  1. 在包含示例代码的目录中运行以下命令:

    gcloud run deploy FUNCTION \
       --source . \
       --function FUNCTION_ENTRYPOINT \
       --base-image BASE_IMAGE \
       --region REGION \
       --allow-unauthenticated

    您需要进行如下替换:

    • FUNCTION 替换为您要部署的函数的名称,例如 my-bigquery-function。您可以完全省略此参数,但如果省略它,系统会提示您输入名称。

    • FUNCTION_ENTRYPOINT 替换为源代码中函数的入口点。这是 Cloud Run 在您的函数运行时执行的代码。此标志的值必须是源代码中存在的函数名称或完全限定类名称。 您必须为示例函数指定的入口点是 helloBigQuery

    • BASE_IMAGE 替换为函数的基础映像环境,例如 nodejs24。如需详细了解基础映像以及每个映像中包含的软件包,请参阅运行时基础映像

    • REGION 替换为您要在其中部署函数的 Google Cloud区域。例如 europe-west1

    可选:

    • 如果您要创建公共 HTTP 函数(例如 webhook),请指定 --allow-unauthenticated 标志。此标志会将 Cloud Run IAM Invoker 角色分配给特殊标识符 allUser。您可以在创建服务后使用 IAM 修改此设置

测试函数

  1. 当函数完成部署时,请复制 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.

删除教程资源

  1. 删除您在本教程中部署的 Cloud Run 服务。Cloud Run 服务在收到请求之前不会产生费用。

    如需删除 Cloud Run 服务,请运行以下命令:

    gcloud run services delete SERVICE-NAME

    SERVICE-NAME 替换为服务的名称。

    您还可以通过Google Cloud 控制台删除 Cloud Run 服务。

  2. 移除您在教程设置过程中添加的 gcloud 默认区域配置:

     gcloud config unset run/region
    
  3. 移除项目配置:

     gcloud config unset project