管理 materialized view

本文說明如何在 BigQuery 中管理 materialized view。

BigQuery 對 materialized view 的管理作業包括:

如要進一步瞭解 materialized view,請參閱下列資源:

事前準備

授予 Identity and Access Management (IAM) 角色,讓使用者具備必要權限,可執行本文件中的各項工作。執行工作所需的權限 (如有) 會列在工作的「必要權限」部分。

修改 materialized view

您可以使用 Google Cloud 控制台或 bq 指令列工具,透過資料定義語言 (DDL) 搭配 ALTER MATERIALIZED VIEW 和 SET OPTIONS 來修改 materialized view。如需 materialized view 選項清單,請參閱 materialized_view_set_options_list。

以下範例將 enable_refresh 設為 true。請視用途需要調整。

所需權限

如要修改 materialized view,您需要 bigquery.tables.get 和 bigquery.tables.update IAM 權限。

下列各項預先定義的 IAM 角色,都包含修改 materialized view 所需的權限:

  • bigquery.dataEditor
  • bigquery.dataOwner
  • bigquery.admin

如要進一步瞭解 BigQuery Identity and Access Management (IAM),請參閱「預先定義的角色和權限」。

SQL

如要修改 materialized view,請使用 ALTER MATERIALIZED VIEW SET OPTIONS DDL 陳述式:

  1. 前往 Google Cloud 控制台的「BigQuery」頁面。

    前往「BigQuery」

  2. 在查詢編輯器中輸入下列陳述式:

    ALTER MATERIALIZED VIEW PROJECT.DATASET.MATERIALIZED_VIEW
    SET OPTIONS (enable_refresh = true);

    替換下列內容:

    • PROJECT::materialized view 所在 專案的名稱
    • DATASET:包含 materialized view 的資料集名稱
    • MATERIALIZED_VIEW:要變更的 materialized view 名稱

  3. 按一下「 執行」。

如要進一步瞭解如何執行查詢,請參閱「執行互動式查詢」。

bq

執行 bq update 指令:

bq update \
--enable_refresh=true \
--refresh_interval_ms= \
PROJECT.DATASET.MATERIALIZED_VIEW

Java

在試用這個範例之前,請先按照「使用用戶端程式庫的 BigQuery 快速入門導覽課程」中的 Java 設定操作說明進行操作。詳情請參閱 BigQuery Java API 參考文件。

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.MaterializedViewDefinition;
import com.google.cloud.bigquery.Table;
import com.google.cloud.bigquery.TableId;

// Sample to update materialized view
public class UpdateMaterializedView {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String datasetName = "MY_DATASET_NAME";
    String materializedViewName = "MY_MATERIALIZED_VIEW_NAME";
    updateMaterializedView(datasetName, materializedViewName);
  }

  public static void updateMaterializedView(String datasetName, String materializedViewName) {
    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      TableId tableId = TableId.of(datasetName, materializedViewName);

      // Get existing materialized view
      Table table = bigquery.getTable(tableId);
      MaterializedViewDefinition materializedViewDefinition = table.getDefinition();
      // Update materialized view
      materializedViewDefinition
          .toBuilder()
          .setEnableRefresh(true)
          .setRefreshIntervalMs(1000L)
          .build();
      table.toBuilder().setDefinition(materializedViewDefinition).build().update();
      System.out.println("Materialized view updated successfully");
    } catch (BigQueryException e) {
      System.out.println("Materialized view was not updated. \n" + e.toString());
    }
  }
}

列出 materialized view

您可以透過 Google Cloud 控制台、bq 指令列工具或 BigQuery API 列出 materialized view。

所需權限

如要列出資料集中的 materialized view,您必須具備 bigquery.tables.list IAM 權限。

下列各項預先定義的 IAM 角色,都包含列出資料集中 materialized view 所需的權限:

  • roles/bigquery.user
  • roles/bigquery.metadataViewer
  • roles/bigquery.dataViewer
  • roles/bigquery.dataOwner
  • roles/bigquery.dataEditor
  • roles/bigquery.admin

如要進一步瞭解 IAM 中的 IAM 角色和權限,請參閱「預先定義的角色和權限」。

列出 materialized view 的程序與列出資料表的程序相同。如要列出資料集中的 materialized view,請按照下列步驟操作:

控制台

  1. 點選左側窗格中的 「Explorer」。

    醒目顯示的「Explorer」窗格按鈕。

    如果沒有看到左側窗格,請按一下 「Expand left pane」(展開左側窗格),開啟窗格。

  2. 在「Explorer」窗格中展開專案,依序點選「Datasets」(資料集) 和資料集。

  3. 依序點選「總覽」>「表格」。捲動清單,查看資料集中的資料表。資料表、檢視表和 materialized view 是由「Type」(類型) 欄中的不同值識別。materialized view 副本的值與 materialized view 相同。

bq

請發出 bq ls 指令。--format 旗標可用來控制輸出內容。如要列出預設專案以外的 materialized view,請按照下列格式將專案 ID 新增至資料集:project_id:dataset。

bq ls --format=pretty project_id:dataset

其中:

  • project_id 是您的專案 ID。
  • dataset 是資料集名稱。

執行指令時,Type 欄位會顯示資料表類型。例如:

+-------------------------+--------------------+----------------------+-------------------+
|         tableId         | Type               |        Labels        | Time Partitioning |
+-------------------------+--------------------+----------------------+-------------------+
| mytable                 | TABLE              | department:shipping  |                   |
| mymatview               | MATERIALIZED_VIEW  |                      |                   |
+-------------------------+--------------------+----------------------+-------------------+

範例:

輸入下列指令,列出預設專案中資料集 mydataset 的 materialized view。

bq ls --format=pretty mydataset

輸入下列指令,列出 myotherproject 中資料集 mydataset 的 materialized view。

bq ls --format=pretty myotherproject:mydataset

API

如要使用 API 列出 materialized view,請呼叫 tables.list 方法。

Go

在試用這個範例之前,請先按照「使用用戶端程式庫的 BigQuery 快速入門導覽課程」中的 Go 設定操作說明進行操作。詳情請參閱 BigQuery Go API 參考文件。

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/bigquery"
	"google.golang.org/api/iterator"
)

// listTables demonstrates iterating through the collection of tables in a given dataset.
func listTables(w io.Writer, projectID, datasetID string) error {
	// projectID := "my-project-id"
	// datasetID := "mydataset"
	// tableID := "mytable"
	ctx := context.Background()
	client, err := bigquery.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("bigquery.NewClient: %v", err)
	}
	defer client.Close()

	ts := client.Dataset(datasetID).Tables(ctx)
	for {
		t, err := ts.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		fmt.Fprintf(w, "Table: %q\n", t.TableID)
	}
	return nil
}

Python

在試用這個範例之前,請先按照「使用用戶端程式庫的 BigQuery 快速入門導覽課程」中的 Python 設定操作說明進行操作。詳情請參閱 BigQuery Python API 參考文件。

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。


from google.cloud import bigquery

# Construct a BigQuery client object.
client = bigquery.Client()

# TODO(developer): Set dataset_id to the ID of the dataset that contains
#                  the tables you are listing.
# dataset_id = 'your-project.your_dataset'

tables = client.list_tables(dataset_id)  # Make an API request.

print("Tables contained in '{}':".format(dataset_id))
for table in tables:
    print("{}.{}.{}".format(table.project, table.dataset_id, table.table_id))

取得 materialized view 的相關資訊

您可以使用 SQL、bq 指令列工具或 BigQuery API,取得 materialized view 的相關資訊。

所需權限

如要查詢 materialized view 的相關資訊,您必須具備下列 Identity and Access Management (IAM) 權限:

  • bigquery.tables.get
  • bigquery.tables.list
  • bigquery.routines.get
  • bigquery.routines.list

下列每個預先定義的 IAM 角色都包含上述權限:

  • roles/bigquery.metadataViewer
  • roles/bigquery.dataViewer
  • roles/bigquery.admin

如要進一步瞭解 BigQuery 權限,請參閱「使用 IAM 控管存取權」。

如要取得 materialized view 的相關資訊,包括任何依附的 materialized view 副本,請按照下列步驟操作:

SQL

如要取得 materialized view 的相關資訊,請查詢 INFORMATION_SCHEMA.TABLES 檢視表:

  1. 前往 Google Cloud 控制台的「BigQuery」頁面。

    前往「BigQuery」

  2. 在查詢編輯器中輸入下列陳述式:

    SELECT * FROM PROJECT_ID.DATASET_ID.INFORMATION_SCHEMA.TABLES
    WHERE table_type = 'MATERIALIZED VIEW';

    替換下列內容:

    • PROJECT_ID:: 含有 materialized view 的專案名稱
    • DATASET_ID:包含 materialized view 的資料集名稱

  3. 按一下「 執行」。

如要進一步瞭解如何執行查詢,請參閱「執行互動式查詢」。

bq

使用 bq show 指令:

bq show --project=project_id --format=prettyjson dataset.materialized_view

更改下列內容:

  • project_id:專案 ID。只有在需要取得預設專案以外的 materialized view 資訊時,才需要加入這個旗標。
  • dataset:包含 materialized view 的資料集名稱。
  • materialized_view:要查詢資訊的 materialized view 名稱。

範例:

輸入下列指令,顯示 myproject 專案中 report_views 資料集內 materialized view my_mv 的相關資訊。

bq show --project=myproject --format=prettyjson report_views.my_mv

API

如要使用 API 取得 materialized view 資訊,請呼叫 tables.get 方法。

刪除 materialized view

您可以透過 Google Cloud 控制台、bq 指令列工具或 API 刪除 materialized view。

刪除 materialized view 時,也會一併刪除與該檢視表相關聯的所有權限。重新建立已刪除的 materialized view 時,您也必須手動重新設定先前與其相關聯的所有存取權限。

所需權限

如要刪除 materialized view,您必須具備 bigquery.tables.delete IAM 權限。

下列各項預先定義的 IAM 角色,都包含刪除 materialized view 所需的權限:

  • bigquery.dataEditor
  • bigquery.dataOwner
  • bigquery.admin

如要進一步瞭解 BigQuery Identity and Access Management (IAM),請參閱「預先定義的角色和權限」。

SQL

如要刪除 materialized view,請使用 DROP MATERIALIZED VIEW DDL 陳述式:

  1. 前往 Google Cloud 控制台的「BigQuery」頁面。

    前往「BigQuery」

  2. 在查詢編輯器中輸入下列陳述式:

    DROP MATERIALIZED VIEW PROJECT.DATASET.MATERIALIZED_VIEW;

    替換下列內容:

    • PROJECT::materialized view 所在 專案的名稱
    • DATASET:包含 materialized view 的資料集名稱
    • MATERIALIZED_VIEW:要刪除的 materialized view 名稱

  3. 按一下「 執行」。

如要進一步瞭解如何執行查詢,請參閱「執行互動式查詢」。

bq

使用 bq rm 指令刪除 materialized view。

API

呼叫 tables.delete 方法,並指定 projectId、datasetId 和 tableId 參數的值:

  • 將 projectId 參數指派給專案 ID。
  • 將 datasetId 參數指派給資料集 ID。
  • 將 tableId 參數指派給要刪除的 materialized view 資料表 ID。

Java

在試用這個範例之前,請先按照「使用用戶端程式庫的 BigQuery 快速入門導覽課程」中的 Java 設定操作說明進行操作。詳情請參閱 BigQuery Java API 參考文件。

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.TableId;

// Sample to delete materialized view
public class DeleteMaterializedView {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String datasetName = "MY_DATASET_NAME";
    String materializedViewName = "MY_MATERIALIZED_VIEW_NAME";
    deleteMaterializedView(datasetName, materializedViewName);
  }

  public static void deleteMaterializedView(String datasetName, String materializedViewName) {
    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      TableId tableId = TableId.of(datasetName, materializedViewName);

      boolean success = bigquery.delete(tableId);
      if (success) {
        System.out.println("Materialized view deleted successfully");
      } else {
        System.out.println("Materialized view was not found");
      }
    } catch (BigQueryException e) {
      System.out.println("Materialized view was not found. \n" + e.toString());
    }
  }
}

重新整理 materialized view

重新整理 materialized view 會更新檢視表的快取資料,反映基礎資料表的目前狀態。

查詢 materialized view 時,BigQuery 會傳回快取的 materialized view 資料,以及從基礎資料表擷取的資料。BigQuery 會盡可能只讀取上次重新整理檢視表後發生的變更。雖然重新整理 materialized view 時,可能不會納入最近串流的資料,但無論是否使用 materialized view,查詢一律會讀取串流資料。

直接從基礎資料表傳回查詢結果,會比從快取的 materialized view 資料傳回結果產生更高的運算費用。定期重新整理 materialized view 快取資料,可減少直接從基礎資料表傳回的資料量,進而降低運算成本。

本節說明如何執行下列操作:

自動重新整理

您隨時可以啟用或停用自動重新整理功能。自動重新整理工作是由 bigquery-adminbot@system.gserviceaccount.com 服務帳戶執行,並會顯示在 materialized view 專案的工作記錄中。

根據預設,基礎資料表發生變更 (例如插入或刪除資料列) 後,系統會在 5 到 30 分鐘內,自動從基礎資料表重新整理 materialized view 中的快取資料。

您可以設定重新整理頻率上限,管理快取資料自動重新整理的頻率,進而管理 materialized view 的費用和查詢效能。

啟用及停用自動重新整理功能

如要在建立 materialized view 時關閉自動重新整理功能,請將 enable_refresh 設為 false。

CREATE MATERIALIZED VIEW PROJECT.DATASET.MATERIALIZED_VIEW
PARTITION BY RANGE_BUCKET(column_name, buckets)
OPTIONS (enable_refresh = false)
AS SELECT ...

如果是現有的 materialized view,您可以使用 ALTER MATERIALIZED VIEW 修改 enable_refresh 值。

ALTER MATERIALIZED VIEW PROJECT.DATASET.MATERIALIZED_VIEW
SET OPTIONS (enable_refresh = true);

設定展示頻率上限

您可以設定自動重新整理的展示頻率上限。根據預設,materialized view 的重新整理頻率不超過每 30 分鐘一次。

您隨時可以變更重新整理展示頻率上限。

如要在建立 materialized view 時設定展示頻率上限,請在 DDL 中將 refresh_interval_minutes (或在 API 和 bq 指令列工具中將 refresh_interval_ms) 設為所需的值。

CREATE MATERIALIZED VIEW PROJECT.DATASET.MATERIALIZED_VIEW
OPTIONS (enable_refresh = true, refresh_interval_minutes = 60)
AS SELECT ...

同樣地,您也可以在修改 materialized view 時設定展示頻率上限。這個範例假設您已啟用自動重新整理,只想變更展示頻率上限:

ALTER MATERIALIZED VIEW PROJECT.DATASET.MATERIALIZED_VIEW
SET OPTIONS (refresh_interval_minutes = 60);

展示頻率上限至少為 1 分鐘。重新整理頻率上限為 7 天。

您隨時可以手動重新整理 materialized view,且不受展示頻率上限限制。

盡可能提供最佳服務

系統會盡可能自動重新整理。BigQuery 會在基礎資料表變更後的 5 分鐘內嘗試啟動重新整理作業 (如果上次重新整理作業是在 30 分鐘前完成),但不保證重新整理作業會在該時間啟動,也不保證何時完成。

自動重新整理的處理方式與優先順序為「batch」的查詢類似。如果 materialized view 的專案目前沒有運算資源,重新整理作業就會延遲。如果專案包含許多檢視表,且重新整理作業的成本很高,則每個檢視表可能會比基礎資料表明顯落後。

手動重新整理

您隨時可以手動重新整理 materialized view。

所需權限

如要手動重新整理 materialized view,您必須具備 bigquery.tables.getData、bigquery.tables.update 和 bigquery.tables.updateData IAM 權限。

下列各項預先定義的 IAM 角色都包含手動重新整理 materialized view 所需的權限:

  • bigquery.dataEditor
  • bigquery.dataOwner
  • bigquery.admin

如要進一步瞭解 BigQuery Identity and Access Management (IAM),請參閱「預先定義的角色和權限」。

如要更新 materialized view 中的資料,請呼叫 BQ.REFRESH_MATERIALIZED_VIEW 系統程序。呼叫這個程序時,BigQuery 會找出基礎資料表中的變更,並將這些變更套用至 materialized view。要執行的查詢 BQ.REFRESH_MATERIALIZED_VIEW 會在重新整理完成時結束。

CALL BQ.REFRESH_MATERIALIZED_VIEW('PROJECT.DATASET.MATERIALIZED_VIEW');

監控 materialized view

您可以使用 BigQuery API,取得 materialized view 和 materialized view 重新整理工作的相關資訊。詳情請參閱「監控 materialized view」。