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

本教學課程說明如何編寫 HTTP Cloud Run 函式,向 BigQuery 提交查詢。

事前準備

  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 Builder (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 替換為專案編號,並將 PROJECT_ID 替換為專案 ID。 Google CloudGoogle Cloud如需如何找出專案 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是您要部署函式的地區。例如:europe-west1

    選用:

    • 如要建立公開 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.