建立可傳回 BigQuery 結果的 Cloud Run 函式

本教學課程將說明如何編寫可將查詢提交至 BigQuery 的 HTTP Cloud Run 函式。

事前準備

  1. 請確認您已按照設定頁面所述,為 Cloud Run 設定新專案。

  2. 啟用 Artifact Registry、Cloud Build 和 Cloud Run Admin API:

     gcloud services enable artifactregistry.googleapis.com \
         cloudbuild.googleapis.com \
         run.googleapis.com
    
  3. 如果您適用網域限制組織政策,且該政策限制專案的未經驗證叫用,您就必須按照「測試私人服務」一節的說明存取已部署的服務。

必要的角色

如要取得從原始碼部署 Cloud Run 服務所需的權限,請要求管理員授予您下列 IAM 角色:

如需與 Cloud Run 相關聯的 IAM 角色和權限清單,請參閱「Cloud Run IAM 角色」和「Cloud Run IAM 權限」。如果您的 Cloud Run 服務會與Google Cloud API 互動 (例如 Cloud 用戶端程式庫),請參閱服務身分設定指南。如要進一步瞭解如何授予角色,請參閱部署權限管理存取權

Cloud Build 服務帳戶的角色

您或管理員必須將下列 IAM 角色授予 Cloud Build 服務帳戶。

按一下即可查看 Cloud Build 服務帳戶的必要角色

除非您覆寫這項行為,否則 Cloud Build 會自動使用 Compute Engine 預設服務帳戶做為預設 Cloud Build 服務帳戶,以便建構您的原始碼和 Cloud Run 資源。如要讓 Cloud Build 建構來源,請要求管理員將 Cloud Run 建構工具 (roles/run.builder) 授予專案的 Compute Engine 預設服務帳戶:

  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 和專案編號的詳細操作說明,請參閱「建立及管理專案」。

將 Cloud Run 建構工具角色授予 Compute Engine 預設服務帳戶後,需要幾分鐘的時間才能套用

準備應用程式

  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 區域。例如:us-central1

    選用:

    • 如果您要建立公開的 HTTP 函式 (例如 webhook),請指定 --allow-unauthenticated 標記。這個標記會將 Cloud Run IAM 叫用者角色指派給特殊 ID allUser。您可以在建立服務之後使用 IAM 編輯這項設定

測試函式

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

  2. 在瀏覽器中造訪這個 URI。

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

清除所用資源

雖然 Cloud Run 在服務未用時不會產生費用,但將容器映像檔儲存於 Artifact Registry 仍可能會產生費用。您可以刪除容器映像檔或刪除 Google Cloud 專案,以免產生費用。刪除 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.