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

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

准备应用

  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 替换为函数所用的基础映像环境,例如 nodejs22。如需详细了解基础映像以及每个映像中包含的软件包,请参阅运行时基础映像

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

    可选:

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

测试函数

  1. 当函数完成部署时,请复制 uri 属性。

  2. 在浏览器中访问此 URI。

    您应该会看到符合查询条件的字词列表,以及每个字词在目标数据集中出现的次数。