管理邏輯檢視畫面

本文件說明如何在 BigQuery 中管理檢視表。您可以透過下列方式管理 BigQuery 檢視表:

事前準備

授予身分與存取權管理 (IAM) 角色,讓使用者取得執行本文件中各項工作的必要權限。執行工作所需的權限 (如有) 會列在工作內容的「必要權限」部分。

更新檢視畫面

建立檢視表後,您可以更新下列檢視表屬性:

所需權限

如要更新檢視畫面,您必須具備下列 IAM 權限:

  • bigquery.tables.update
  • bigquery.tables.get

以下每個預先定義的 IAM 角色都包含更新檢視畫面所需的權限:

  • roles/bigquery.dataEditor
  • roles/bigquery.dataOwner
  • roles/bigquery.admin

此外,如果您具備 bigquery.datasets.create 權限,就可以更新所建立資料集中的資料表和檢視表。

如要更新檢視表的 SQL 查詢,還需擁有檢視表 SQL 查詢所參照的資料表查詢權限。

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

更新檢視表的 SQL 查詢

您可以透過以下方式更新用來定義檢視表的 SQL 查詢:

  • 使用 Google Cloud 主控台
  • 使用 bq 指令列工具的 bq update 指令
  • 呼叫 tables.patch API 方法
  • 使用用戶端程式庫

您可以使用 API 或 bq 指令列工具,將 SQL 方言從舊版 SQL 變更為 GoogleSQL。您無法在Google Cloud 主控台中將舊版 SQL 檢視表更新為 GoogleSQL。

如何更新檢視表的 SQL 查詢:

主控台

  1. 在「Explorer」面板中展開專案和資料集,然後選取檢視畫面。

  2. 按一下 [Details] (詳細資料) 分頁標籤。

  3. 在「Query」(查詢) 方塊上方,按一下 [Edit Query] (編輯查詢) 按鈕。接著在顯示的對話方塊中按一下 [Open] (開啟)

    編輯查詢

  4. 在「Query editor」(查詢編輯器) 方塊中編輯 SQL 查詢,然後按一下 [Save view] (儲存檢視表)

    儲存檢視表

  5. 確定「Save view」(儲存檢視表) 對話方塊中的所有欄位都正確無誤,再點選 [Save] (儲存)

bq

發出含有 --view 旗標的 bq update 指令。如要使用 GoogleSQL,或將查詢方言從舊版 SQL 更新為 GoogleSQL,請加上 --use_legacy_sql 旗標,並將其設定為 false

如果您的查詢參照儲存在 Cloud Storage 或本機檔案中的外部使用者定義函式資源,請使用 --view_udf_resource 標記來指定這些資源。本文不示範 --view_udf_resource 旗標。如要進一步瞭解如何使用 UDF,請參閱「GoogleSQL 使用者定義函式」。

如果您要更新在預設專案以外的專案中的檢視表,請使用下列格式將專案 ID 新增至資料集名稱:project_id:dataset

bq update \
    --use_legacy_sql=false \
    --view_udf_resource=path_to_file \
    --view='query' \
    project_id:dataset.view

更改下列內容:

  • path_to_file:程式碼檔案的 URI 或本機檔案系統路徑,該檔案會在載入後立即接受評估,以做為檢視表使用的使用者定義函式資源。請重複該標記以指定多個檔案。
  • query:有效的 GoogleSQL 查詢
  • project_id:您的專案 ID
  • dataset:包含您要更新的檢視表的資料集名稱
  • view:您要更新的檢視畫面名稱

範例

輸入下列指令,更新 mydataset 中名為 myview 之檢視表的 SQL 查詢。mydataset 位於預設專案中。用於更新檢視表的查詢範例會查詢來自美國名稱資料公開資料集的資料。

bq update \
    --use_legacy_sql=false \
    --view \
    'SELECT
      name,
      number
    FROM
      `bigquery-public-data.usa_names.usa_1910_current`
    WHERE
      gender = "M"
    ORDER BY
      number DESC;' \
    mydataset.myview

輸入下列指令,更新 mydataset 中名為 myview 之檢視表的 SQL 查詢。mydatasetmyotherproject 中,而不是您的預設專案中。用於更新檢視表的查詢範例會查詢來自美國名稱資料公開資料集的資料。

bq update \
    --use_legacy_sql=false \
    --view \
    'SELECT
      name,
      number
    FROM
      `bigquery-public-data.usa_names.usa_1910_current`
    WHERE
      gender = "M"
    ORDER BY
      number DESC;' \
    myotherproject:mydataset.myview

API

您可以透過下列方式更新檢視表:使用包含已更新 view 屬性的資料表資源呼叫 tables.patch 方法。由於 tables.update 方法會取代整個資料表資源,因此建議使用 tables.patch 方法。

Go

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

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

import (
	"context"
	"fmt"

	"cloud.google.com/go/bigquery"
)

// updateView demonstrates updating the query metadata that defines a logical view.
func updateView(projectID, datasetID, viewID string) error {
	// projectID := "my-project-id"
	// datasetID := "mydataset"
	// viewID := "myview"
	ctx := context.Background()
	client, err := bigquery.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("bigquery.NewClient: %v", err)
	}
	defer client.Close()

	view := client.Dataset(datasetID).Table(viewID)
	meta, err := view.Metadata(ctx)
	if err != nil {
		return err
	}

	newMeta := bigquery.TableMetadataToUpdate{
		// This example updates a view into the shakespeare dataset to exclude works named after kings.
		ViewQuery: "SELECT word, word_count, corpus, corpus_date FROM `bigquery-public-data.samples.shakespeare` WHERE corpus NOT LIKE '%king%'",
	}

	if _, err := view.Update(ctx, newMeta, meta.ETag); err != nil {
		return err
	}
	return nil
}

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;
import com.google.cloud.bigquery.TableInfo;
import com.google.cloud.bigquery.ViewDefinition;

// Sample to update query on a view
public class UpdateViewQuery {

  public static void runUpdateViewQuery() {
    // TODO(developer): Replace these variables before running the sample.
    String datasetName = "MY_DATASET_NAME";
    String tableName = "MY_TABLE_NAME";
    String viewName = "MY_VIEW_NAME";
    String updateQuery =
        String.format("SELECT TimestampField, StringField FROM %s.%s", datasetName, tableName);
    updateViewQuery(datasetName, viewName, updateQuery);
  }

  public static void updateViewQuery(String datasetName, String viewName, String query) {
    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();

      // Retrieve existing view metadata
      TableInfo viewMetadata = bigquery.getTable(TableId.of(datasetName, viewName));

      // Update view query
      ViewDefinition viewDefinition = viewMetadata.getDefinition();
      viewDefinition.toBuilder().setQuery(query).build();

      // Set metadata
      bigquery.update(viewMetadata.toBuilder().setDefinition(viewDefinition).build());

      System.out.println("View query updated successfully");
    } catch (BigQueryException e) {
      System.out.println("View query was not updated. \n" + e.toString());
    }
  }
}

Node.js

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

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

// Import the Google Cloud client library and create a client
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();

async function updateViewQuery() {
  // Updates a view named "my_existing_view" in "my_dataset".

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const datasetId = "my_existing_dataset"
  // const tableId = "my_existing_table"
  const dataset = await bigquery.dataset(datasetId);

  // This example updates a view into the USA names dataset to include state.
  const newViewQuery = `SELECT name, state 
  FROM \`bigquery-public-data.usa_names.usa_1910_current\`
  LIMIT 10`;

  // Retrieve existing view
  const [view] = await dataset.table(tableId).get();

  // Retrieve existing view metadata
  const [metadata] = await view.getMetadata();

  // Update view query
  metadata.view = newViewQuery;

  // Set metadata
  await view.setMetadata(metadata);

  console.log(`View ${tableId} updated.`);
}

Python

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

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

from google.cloud import bigquery

client = bigquery.Client()

view_id = "my-project.my_dataset.my_view"
source_id = "my-project.my_dataset.my_table"
view = bigquery.Table(view_id)

# The source table in this example is created from a CSV file in Google
# Cloud Storage located at
# `gs://cloud-samples-data/bigquery/us-states/us-states.csv`. It contains
# 50 US states, while the view returns only those states with names
# starting with the letter 'M'.
view.view_query = f"SELECT name, post_abbr FROM `{source_id}` WHERE name LIKE 'M%'"

# Make an API request to update the query property of the view.
view = client.update_table(view, ["view_query"])
print(f"Updated {view.table_type}: {str(view.reference)}")

更新視圖的到期時間

您可以設定資料集層級 (會同時影響資料表和視圖) 的資料表預設到期時間,也可以在建立視圖時設定視圖的到期時間。如果您在建立檢視表時設定到期時間,系統將會忽略資料集的資料表預設到期時間。如果您未在資料集層級設定資料表的預設到期時間,且未在建立資料檢視時設定到期時間,則資料檢視永遠不會過期,您必須手動刪除資料檢視。

建立檢視表後,您可以隨時透過以下方式更新檢視表的到期時間:

  • 使用 Google Cloud 主控台
  • 使用以 GoogleSQL 語法編寫的資料定義語言 (DDL) 陳述式
  • 使用 bq 指令列工具的 bq update 指令
  • 呼叫 tables.patch API 方法
  • 使用用戶端程式庫

如何更新檢視表的到期時間:

主控台

  1. 在導覽窗格中選取檢視表。

  2. 在「View Details」(檢視表詳細資料) 頁面上,按一下 [Details] (詳細資料) 分頁標籤。

  3. 在 [View info] (檢視表資訊) 右側,按一下編輯圖示 (鉛筆圖案)。

  4. 在 [View info] (檢視表資訊) 對話方塊的 [View expiration] (檢視表到期時間) 部分,點選 [Specify date] (指定日期)

  5. 在日期選擇器中,輸入到期日期與時間,然後按一下 [Ok] (確定)

  6. 按一下 [Update] (更新)。已更新的到期時間會顯示在「View info」(檢視表資訊) 區段中。

SQL

使用 ALTER VIEW SET OPTIONS DDL 陳述式

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

    前往 BigQuery

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

     ALTER VIEW DATASET_ID.MY_VIEW
     SET OPTIONS (
      expiration_timestamp = TIMESTAMP('NEW_TIMESTAMP'));

    請依指示取代下列項目:

    • DATASET_ID:包含檢視表的資料集 ID
    • MY_VIEW:要更新的檢視畫面名稱
    • NEW_TIMESTAMPTIMESTAMP 值

  3. 按一下 「Run」

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

bq

發出含有 --expiration 旗標的 bq update 指令。如果您要更新在預設專案以外的專案中的檢視表,請使用下列格式將專案 ID 新增至資料集名稱:project_id:dataset

bq update \
    --expiration integer \
    project_id:dataset.view

請依指示取代下列項目:

  • integer:資料表的預設生命週期 (以秒為單位)。最小值是 3600 秒 (1 小時)。到期時間為目前時間加整數值。
  • project_id:您的專案 ID
  • dataset:含有您要更新的檢視表的資料集名稱
  • view:您要更新的檢視畫面名稱

範例

輸入下列指令,將 mydataset 中的 myview 到期時間更新為 5 天 (432000 秒)。mydataset 位於您的預設專案中。

bq update \
    --expiration 432000 \
    mydataset.myview

輸入下列指令,將 mydataset 中的 myview 到期時間更新為 5 天 (432000 秒)。mydatasetmyotherproject 中,而不是您的預設專案中。

bq update \
    --expiration 432000 \
    myotherproject:mydataset.myview

API

呼叫 tables.patch 方法並使用資料表資源中的 expirationTime 屬性。由於 tables.update 方法會取代整個資料表資源,因此建議使用 tables.patch 方法。使用 REST API 時,檢視表到期時間會以毫秒為單位表示。

Go

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

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

import (
	"context"
	"fmt"
	"time"

	"cloud.google.com/go/bigquery"
)

// updateTableExpiration demonstrates setting the table expiration of a table to a specific point in time
// in the future, at which time it will be deleted.
func updateTableExpiration(projectID, datasetID, tableID 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()

	tableRef := client.Dataset(datasetID).Table(tableID)
	meta, err := tableRef.Metadata(ctx)
	if err != nil {
		return err
	}
	update := bigquery.TableMetadataToUpdate{
		ExpirationTime: time.Now().Add(time.Duration(5*24) * time.Hour), // table expiration in 5 days.
	}
	if _, err = tableRef.Update(ctx, update, meta.ETag); err != nil {
		return err
	}
	return nil
}

Java

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

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

Table beforeTable = bigquery.getTable(datasetName, tableName);

// Set table to expire 5 days from now.
long expirationMillis = DateTime.now().plusDays(5).getMillis();
TableInfo tableInfo = beforeTable.toBuilder()
        .setExpirationTime(expirationMillis)
        .build();
Table afterTable = bigquery.update(tableInfo);

Node.js

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

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

// Import the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();

async function updateTableExpiration() {
  // Updates a table's expiration.

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const datasetId = 'my_dataset', // Existing dataset
  // const tableId = 'my_table', // Existing table
  // const expirationTime = Date.now() + 1000 * 60 * 60 * 24 * 5 // 5 days from current time in ms

  // Retreive current table metadata
  const table = bigquery.dataset(datasetId).table(tableId);
  const [metadata] = await table.getMetadata();

  // Set new table expiration to 5 days from current time
  metadata.expirationTime = expirationTime.toString();
  const [apiResponse] = await table.setMetadata(metadata);

  const newExpirationTime = apiResponse.expirationTime;
  console.log(`${tableId} expiration: ${newExpirationTime}`);
}

Python

更新檢視表到期時間的程序與更新資料表到期時間的程序相同。

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

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

from google.cloud import bigquery

client = bigquery.Client()

# TODO(dev): Change table_id to the full name of the table you want to update.
table_id = "your-project.your_dataset.your_table_name"

# TODO(dev): Set table to expire for desired days days from now.
expiration = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
    days=5
)
table = client.get_table(table_id)  # Make an API request.
table.expires = expiration
table = client.update_table(table, ["expires"])  # API request

print(f"Updated {table_id}, expires {table.expires}.")

更新視圖的說明

您可以透過以下方式更新檢視表的說明:

  • 使用 Google Cloud 主控台
  • 使用以 GoogleSQL 語法編寫的資料定義語言 (DDL) 陳述式
  • 使用 bq 指令列工具的 bq update 指令
  • 呼叫 tables.patch API 方法
  • 使用用戶端程式庫

如何更新檢視表的說明:

主控台

使用 Google Cloud 主控台建立檢視表時,您無法新增說明。建立資料檢視後,您可以在「Details」頁面中新增說明。

  1. 在「Explorer」面板中展開專案和資料集,然後選取檢視畫面。

  2. 按一下 [Details] (詳細資料) 分頁標籤。

  3. 按一下「Description」(說明) 旁邊的鉛筆圖示。

    編輯檢視表說明

  4. 在隨即顯示的對話方塊中輸入說明,然後按一下 [Update] (更新) 以儲存新的說明。

SQL

使用 ALTER VIEW SET OPTIONS DDL 陳述式

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

    前往 BigQuery

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

     ALTER VIEW DATASET_ID.MY_VIEW
     SET OPTIONS (
      description = 'NEW_DESCRIPTION');

    請依指示取代下列項目:

    • DATASET_ID:包含檢視表的資料集 ID
    • MY_VIEW:要更新的檢視畫面名稱
    • NEW_DESCRIPTION:新檢視畫面說明

  3. 按一下 「Run」

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

bq

發出含有 --description 旗標的 bq update 指令。如果您要更新在預設專案以外的專案中的檢視表,請使用下列格式將專案 ID 新增至資料集名稱:[PROJECT_ID]:[DATASET]

bq update \
    --description "description" \
    project_id:dataset.view

更改下列內容:

  • description:描述檢視表的文字 (以引號表示)
  • project_id:您的專案 ID。
  • dataset:含有您要更新的檢視表的資料集名稱
  • view:您要更新的檢視畫面名稱

範例

輸入下列指令,將 mydataset 中的 myview 說明變更為 「Description of mydataset」(mydataset 的說明)。mydataset 位於您的預設專案中。

bq update \
    --description "Description of myview" \
    mydataset.myview

輸入下列指令,將 mydataset 中的 myview 說明變更為 「Description of mydataset」(mydataset 的說明)。mydatasetmyotherproject 中,而不是您的預設專案中。

bq update \
    --description "Description of myview" \
    myotherproject:mydataset.myview

API

呼叫 tables.patch 方法並使用 description 屬性更新資料表資源中的檢視表說明。由於 tables.update 方法會取代整個資料表資源,因此建議使用 tables.patch 方法。

Go

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

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

import (
	"context"
	"fmt"

	"cloud.google.com/go/bigquery"
)

// updateTableDescription demonstrates how to fetch a table's metadata and updates the Description metadata.
func updateTableDescription(projectID, datasetID, tableID 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()

	tableRef := client.Dataset(datasetID).Table(tableID)
	meta, err := tableRef.Metadata(ctx)
	if err != nil {
		return err
	}
	update := bigquery.TableMetadataToUpdate{
		Description: "Updated description.",
	}
	if _, err = tableRef.Update(ctx, update, meta.ETag); err != nil {
		return err
	}
	return nil
}

Java

更新檢視表說明的程序與更新資料表說明的程序相同。

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

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

// String datasetName = "my_dataset_name";
// String tableName = "my_table_name";
// String newDescription = "new_description";

Table beforeTable = bigquery.getTable(datasetName, tableName);
TableInfo tableInfo = beforeTable.toBuilder()
    .setDescription(newDescription)
    .build();
Table afterTable = bigquery.update(tableInfo);

Node.js

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

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

// Import the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();

async function updateTableDescription() {
  // Updates a table's description.

  // Retreive current table metadata
  const table = bigquery.dataset(datasetId).table(tableId);
  const [metadata] = await table.getMetadata();

  // Set new table description
  const description = 'New table description.';
  metadata.description = description;
  const [apiResponse] = await table.setMetadata(metadata);
  const newDescription = apiResponse.description;

  console.log(`${tableId} description: ${newDescription}`);
}

Python

更新檢視表說明的程序與更新資料表說明的程序相同。

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

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

# from google.cloud import bigquery
# client = bigquery.Client()
# project = client.project
# dataset_ref = bigquery.DatasetReference(project, dataset_id)
# table_ref = dataset_ref.table('my_table')
# table = client.get_table(table_ref)  # API request

assert table.description == "Original description."
table.description = "Updated description."

table = client.update_table(table, ["description"])  # API request

assert table.description == "Updated description."

複製檢視畫面

您可以使用 Google Cloud 主控台複製檢視畫面。

您無法使用 bq 指令列工具、REST API 或用戶端程式庫複製檢視表,但可以複製目標資料集中的檢視表

所需權限

如要在 Google Cloud 控制台中複製檢視表,您必須具備來源和目標資料集的 IAM 權限。

  • 在來源資料集中,您需要具備下列項目:

    • bigquery.tables.get
    • bigquery.tables.getData (必須具備此權限,才能存取檢視表 SQL 查詢所參照的資料表)
  • 在目的地資料集上,您需要執行下列操作:

    • bigquery.tables.create (可讓您在目的地資料集中建立檢視表副本)

以下每個預先定義的 IAM 角色都包含複製檢視畫面所需的權限:

  • roles/bigquery.dataEditor
  • roles/bigquery.dataOwner
  • roles/bigquery.admin

此外,如果您具備 bigquery.datasets.create 權限,就可以在所建立的資料集中複製檢視表。除非您是目的地資料集的建立者,否則也需要對其具備存取權。

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

複製檢視表

如要複製檢視表:

  1. 在「Explorer」面板中展開專案和資料集,然後選取檢視畫面。

  2. 在詳細資料面板中,按一下「複製檢視畫面」

  3. 在「Copy View」(複製檢視表) 對話方塊中:

    • 在「Source」(來源) 區段中,驗證您的「Project name」(專案名稱)、「Dataset name」(資料集名稱) 和「Table name」(資料表名稱) 是否正確。
    • 在「Destination」(目的地) 區段中:

      • 在「Project name」(專案名稱) 部分,選擇要複製檢視表的專案。
      • 在「Dataset name」(資料集名稱) 部分,選擇要納入檢視表副本的資料集。
      • 在「Table name」(資料表名稱) 部分,輸入檢視表的名稱。您可以在方塊中輸入新的檢視表名稱,以重新命名檢視表。您輸入的新名稱必須遵循檢視表命名規則。

      複製檢視表對話方塊

    • 按一下「複製」

複製工作適用限制。詳情請參閱「配額與限制」。

重新命名檢視表

目前,您只能在使用 Google Cloud 主控台複製檢視表時才能重新命名檢視表。如需在複製檢視表時重新命名的操作說明,請參閱「複製檢視表」一節。

您無法使用 bq 指令列工具、API 或用戶端程式庫變更現有檢視表的名稱。因此,您必須以新名稱重新建立檢視表

刪除檢視

您可以透過下列方式刪除檢視表:

  • 使用 Google Cloud 主控台
  • 使用 bq 指令列工具的 bq rm 指令
  • 呼叫 tables.delete API 方法

您目前可以透過任何可用的方法,一次只刪除一個檢視表。

如要在指定時段過後自動刪除檢視表,請設定資料集層級的預設到期時間,或者在建立檢視表時設定到期時間。

刪除授權檢視表時,系統最多可能要過 24 小時才會從來源資料集的授權檢視表清單中移除已刪除的檢視表。

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

所需權限

如要刪除檢視畫面,您必須具備下列 IAM 權限:

  • bigquery.tables.delete

以下每個預先定義的 IAM 角色都包含刪除檢視畫面所需的權限:

  • roles/bigquery.dataOwner
  • roles/bigquery.dataEditor
  • roles/bigquery.admin

此外,如果您具備 bigquery.datasets.create 權限,就能刪除所建立資料集中的檢視表。

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

刪除檢視表

如何刪除視圖:

主控台

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

    前往 BigQuery

  2. 在「Explorer」面板中展開專案和資料集,然後選取檢視畫面。

  3. 在詳細資料面板中,按一下「Delete view」(刪除檢視畫面)

  4. 在對話方塊中輸入 "delete",然後按一下「Delete」 確認。

SQL

使用 DROP VIEW DDL 陳述式

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

    前往 BigQuery

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

    DROP VIEW mydataset.myview;

    請依指示取代下列項目:

    • DATASET_ID:包含檢視表的資料集 ID
    • MY_VIEW:要更新的檢視畫面名稱
    • NEW_DESCRIPTION:新檢視畫面說明

  3. 按一下 「Run」

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

bq

請使用 bq rm 指令,搭配 --table 旗標 (或 -t 捷徑) 來刪除檢視表。使用 bq 指令列工具移除檢視表時,必須確認該操作。您可以使用 --force 旗標 (或 -f 捷徑) 來略過確認程序。

如果檢視表位於非預設專案中的資料集裡,請使用下列格式將專案 ID 新增至資料集名稱:project_id:dataset

bq rm \
-f \
-t \
project_id:dataset.view

其中:

  • project_id 是您的專案 ID。
  • dataset 是包含該資料表之資料集的名稱。
  • view 是您要刪除的視圖名稱。

範例:

您可以使用 bq 指令列工具執行 bq 指令。

在 Google Cloud 控制台中啟用 Cloud Shell

啟用 Cloud Shell

輸入下列指令從 mydataset 刪除 myviewmydataset 在您的預設專案中。

bq rm -t mydataset.myview

輸入下列指令從 mydataset 刪除 myviewmydatasetmyotherproject 中,而不是您的預設專案中。

bq rm -t myotherproject:mydataset.myview

輸入下列指令從 mydataset 刪除 myviewmydataset 在您的預設專案中。這個指令使用 -f 捷徑略過確認程序。

bq rm -f -t mydataset.myview

API

呼叫 tables.delete API 方法並使用tableId 參數指定要刪除的檢視表。

C#

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

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


using Google.Cloud.BigQuery.V2;
using System;

public class BigQueryDeleteTable
{
    public void DeleteTable(
        string projectId = "your-project-id",
        string datasetId = "your_dataset_id",
        string tableId = "your_table_id"
    )
    {
        BigQueryClient client = BigQueryClient.Create(projectId);
        client.DeleteTable(datasetId, tableId);
        Console.WriteLine($"Table {tableId} deleted.");
    }
}

Go

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

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

import (
	"context"
	"fmt"

	"cloud.google.com/go/bigquery"
)

// deleteTable demonstrates deletion of a BigQuery table.
func deleteTable(projectID, datasetID, tableID 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()

	table := client.Dataset(datasetID).Table(tableID)
	if err := table.Delete(ctx); err != nil {
		return err
	}
	return nil
}

Java

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

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

TableId tableId = TableId.of(projectId, datasetName, tableName);
boolean deleted = bigquery.delete(tableId);
if (deleted) {
  // the table was deleted
} else {
  // the table was not found
}

Node.js

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

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

// Import the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();

async function deleteTable() {
  // Deletes "my_table" from "my_dataset".

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const datasetId = "my_dataset";
  // const tableId = "my_table";

  // Delete the table
  await bigquery
    .dataset(datasetId)
    .table(tableId)
    .delete();

  console.log(`Table ${tableId} deleted.`);
}

PHP

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

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

use Google\Cloud\BigQuery\BigQueryClient;

/** Uncomment and populate these variables in your code */
// $projectId = 'The Google project ID';
// $datasetId = 'The BigQuery dataset ID';
// $tableId = 'The BigQuery table ID';

$bigQuery = new BigQueryClient([
    'projectId' => $projectId,
]);
$dataset = $bigQuery->dataset($datasetId);
$table = $dataset->table($tableId);
$table->delete();
printf('Deleted table %s.%s' . PHP_EOL, $datasetId, $tableId);

Python

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

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


from google.cloud import bigquery

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

# TODO(developer): Set table_id to the ID of the table to fetch.
# table_id = 'your-project.your_dataset.your_table'

# If the table does not exist, delete_table raises
# google.api_core.exceptions.NotFound unless not_found_ok is True.
client.delete_table(table_id, not_found_ok=True)  # Make an API request.
print("Deleted table '{}'.".format(table_id))

Ruby

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

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

require "google/cloud/bigquery"

def delete_table dataset_id = "my_dataset_id", table_id = "my_table_id"
  bigquery = Google::Cloud::Bigquery.new
  dataset  = bigquery.dataset dataset_id
  table    = dataset.table table_id

  table.delete

  puts "Table #{table_id} deleted."
end

還原檢視畫面

您無法直接還原已刪除的檢視畫面,但在某些情況下,可以使用下列因應措施:

  • 如果檢視畫面是因父項資料集遭到刪除而刪除,您可以取消刪除資料集來擷取檢視畫面。
  • 如果明確刪除檢視表,您可以使用建立或更新檢視表時的最後一次查詢,重新建立檢視表。您可以在記錄中找到檢視畫面建立或更新作業的查詢定義。

查看安全性

如要控管 BigQuery 中的檢視表存取權,請參閱「授權檢視表」。

後續步驟