建立 Cloud Run functions,使用 BigQuery 提交查詢並傳回結果。

本教學課程說明如何編寫 HTTP Cloud Run 函式,向 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 叫用者角色指派給特殊 ID allUser。您可以在建立服務之後使用 IAM 編輯這項設定

測試函式

  1. 函式部署完成後,請複製 uri 屬性。

  2. 在瀏覽器中前往這個 URI。

    您應該會看到符合查詢條件的字詞清單,以及每個字詞在目標資料集中出現的次數。