管理資料集

本文件說明如何在 BigQuery 中複製資料集、在其他位置重新建立資料集、保護資料集、刪除資料集,以及從已刪除的資料集中還原資料表。如要瞭解如何還原 (或取消刪除) 已刪除的資料集,請參閱「還原已刪除的資料集」。

身為 BigQuery 管理員,您可以整理及控管分析師使用的資料表檢視畫面存取權。如要進一步瞭解資料集,請參閱「資料集簡介」。

資料集建立之後,您就無法變更名稱或重新指派位置。如要變更資料集名稱,您可以複製資料集,然後變更目的地資料集的名稱。如要重新指派資料集,您可以按照下列任一方法操作:

必要的角色

本節說明管理資料集所需的角色和權限。如果來源或目的地資料集與用於複製的專案位於相同專案中,則不需要在該資料集上設定額外的權限或角色。

如要取得管理資料集所需的權限,請要求管理員授予您下列 IAM 角色:

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

這些預先定義的角色包含管理資料集所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

如要管理資料集,您必須具備下列權限:

  • 複製資料集:
    • bigquery.transfers.update 在目的地專案中
    • bigquery.jobs.create 在目的地專案中
    • 來源和目的地資料集的 bigquery.datasets.get
    • 來源和目的地資料集的 bigquery.tables.list
    • bigquery.datasets.update 在目的地資料集上
    • bigquery.tables.create 在目的地資料集上
  • 刪除資料集:
    • bigquery.datasets.delete 專案
    • bigquery.tables.delete 專案

您或許還可透過自訂角色或其他預先定義的角色取得這些權限。

如要進一步瞭解 BigQuery 中的 IAM 角色和權限,請參閱「IAM 簡介」。

複製資料集

您可以複製資料集 (包括區域內或跨區域的分區資料),而不需要擷取、移動或重新載入資料到 BigQuery。BigQuery 會使用後端的 BigQuery 資料移轉服務來複製資料集。如要瞭解資料移轉時的位置考量,請參閱「資料位置和移轉作業」。

針對每一個資料集複製作業設定,您一次可以有一個有效的移轉作業。其他轉移作業將排入佇列。如果您使用 Google Cloud 控制台,可以安排週期性複製作業,並透過 BigQuery 資料移轉服務設定電子郵件或 Pub/Sub 通知。

限制

複製資料集時,請注意下列限制:

  • 您無法從來源資料集複製下列資源:

    • 觀看次數。
    • 日常安排,包括 UDF。
    • 外部資料表。
    • 如果複製作業跨區域,請使用變更資料擷取 (CDC) 資料表。支援在同一區域內複製 CDC 資料表。
    • 如果目的地資料集並未使用 CMEK 加密,且未提供 CMEK,則資料表無法使用客戶管理的加密金鑰 (CMEK) 加密時,系統不支援跨區域的資料表複製工作。系統支援跨地區複製以預設方式加密的資料表。

      您可以複製同地區內的所有加密資料表,包括使用 CMEK 加密的資料表。

  • 您無法將下列資源用於複製工作的目的地資料集:

    • 寫入最佳化儲存空間。
    • 如果複製工作跨區域,且來源資料表未以 CMEK 加密,則資料集會以 CMEK 加密。

      不過,如果是在同一個區域內複製資料,則可使用以 CMEK 加密的資料表做為目的地資料表。

  • 每個複製作業之間的時間間隔下限為 12 小時。

  • 不支援將資料附加到目的地資料集中的分區或非分區資料表。如果來源資料表沒有任何變更,系統會略過該資料表。如果來源資料表更新,目的地資料表會完全截斷並取代。

  • 如果來源資料集和目的地資料集中有資料表,且上次成功複製後來源資料表沒有任何變更,就會略過此資料表。即使勾選「覆寫目的地資料表」核取方塊,系統也會略過來源資料表。

  • 截斷目的地資料集中的資料表時,資料集複製作業在開始複製作業之前,不會偵測對目的地資料集中資源所做的任何變更。資料集複製作業會覆寫目的地資料集中的所有資料,包括資料表和結構定義。

  • 目的地資料表可能不會反映複製工作開始後對來源資料表所做的變更。

  • BigQuery Omni 區域不支援複製資料集。

  • 如要將資料集複製到其他 VPC Service Controls 服務範圍中的專案,您必須設定下列輸出規則:

    • 在目的專案的 VPC Service Controls 服務範圍設定中,IAM 主體必須具備下列方法:

      • bigquery.datasets.get
      • bigquery.tables.list
      • bigquery.tables.get
      • bigquery.tables.getData
    • 在來源專案的 VPC Service Controls 服務範圍設定中,使用的 IAM 主體必須將方法設為 All Methods

複製資料集

選取下列選項之一:

主控台

  1. 為目的地資料集啟用 BigQuery 資料移轉服務

    啟用 BigQuery 資料移轉服務 API

  2. 確認您具備必要角色

    如果您想要為 Pub/Sub 設定移轉執行通知 (步驟中的選項 2),就必須具備 pubsub.topics.setIamPolicy 權限。

    如果您只想設定電子郵件通知,則不需要 Pub/Sub 權限。詳情請參閱 BigQuery 資料移轉服務的執行通知

  3. 在與來源資料集相同或不同的地區建立 BigQuery 資料集

選項 1:使用 BigQuery 複製函式

如要建立一次性移轉作業,請使用 BigQuery 的複製函式:

  1. 前往「BigQuery」頁面

    前往 BigQuery

  2. 在「Explorer」面板中展開專案並選取資料集。

  3. 在「Dataset info」部分,按一下 「Copy」,然後執行下列操作:

    1. 在「Dataset」欄位中,建立新的資料集,或從清單中選取現有的資料集 ID。

      同一專案中的資料集名稱不得重複。專案和資料集可能位於不同地區,但並非所有地區都支援跨區資料集複製功能。

      在「位置」欄位中,系統會顯示來源資料集的位置。

    2. 選用:如要使用來源資料表覆寫目的地資料表的資料和結構定義,請選取「Overwrite destination tables」核取方塊。來源和目的地資料表都必須具有相同的分割結構定義。

    3. 如要複製資料集,請按一下「複製」

選項 2:使用 BigQuery 資料移轉服務

如要排定週期性複製作業並設定電子郵件或 Pub/Sub 通知,請在目標專案的 Google Cloud 控制台中使用 BigQuery 資料移轉服務:

  1. 前往「資料移轉」頁面。

    前往「資料移轉」

  2. 按一下「建立移轉作業」

  3. 在「Source」清單中,選取「Dataset Copy」

  4. 在「Display name」欄位中,輸入移轉作業的名稱。

  5. 在「Schedule options」(排程選項) 部分執行下列操作:

    1. 在「Repeat frequency」(重複頻率) 部分,選擇多久執行一次移轉作業的選項:

      如果選取「自訂」,請輸入自訂頻率,例如 every day 00:00。詳情請參閱「設定時間表格式」。

    2. 在「Start date and run time」(開始日期和執行時間) 部分,輸入開始移轉的日期與時間。如果您選擇 [Start now] (立即開始),系統就會停用這個選項。

  6. 在「Destination settings」(目的地設定) 部分,選取要用來儲存轉移資料的目的地資料集。您也可以先按一下「CREATE NEW DATASET」建立新的資料集,再選取該資料集進行轉移。

  7. 在「資料來源詳細資料」部分輸入以下資訊:

    1. 針對「Source dataset」(來源資料集),請輸入要複製的資料集 ID。
    2. 針對「Source project」(來源專案),請輸入來源資料集的專案 ID。
  8. 如要使用來源資料表覆寫目的地資料表的資料和結構定義,請選取「Overwrite destination tables」核取方塊。來源和目的地資料表都必須使用相同的分割作業結構定義。

  9. 在「Service Account」(服務帳戶) 選單,選取與貴組織Google Cloud 專案相關聯的服務帳戶。您可以將服務帳戶與移轉作業建立關聯,這樣就不需要使用者憑證。如要進一步瞭解如何搭配使用服務帳戶與資料移轉作業,請參閱使用服務帳戶的相關說明。

    • 如果使用聯合身分登入,您必須擁有服務帳戶才能建立移轉作業。如果是以 Google 帳戶登入,則不一定要透過服務帳戶建立移轉作業。
    • 服務帳戶必須具備必要角色
  10. 選用:在「Notification options」(通知選項) 專區,執行下列操作:

    • 如要啟用電子郵件通知,請點選切換按鈕。啟用這個選項之後,若移轉失敗,移轉設定的擁有者就會收到電子郵件通知。
    • 如要啟用 Pub/Sub 通知,請按一下切換按鈕,然後從清單中選取主題名稱,或按一下「建立主題」。這個選項會針對移轉作業設定 Pub/Sub 執行通知
  11. 按一下 [儲存]

bq

  1. 為目的地資料集啟用 BigQuery 資料移轉服務

  2. 確認您具備必要角色

  3. 如要建立 BigQuery 資料集,請使用 bq mk 指令,搭配資料集建立旗標 --datasetlocation 旗標:

    bq mk \
      --dataset \
      --location=LOCATION \
      PROJECT:DATASET

    更改下列內容:

    • LOCATION:您要複製資料集的位置
    • PROJECT:目標資料集的專案 ID
    • DATASET:目標資料集的名稱
  4. 如要複製資料集,請使用 bq mk 指令搭配轉移建立標記 --transfer_config--data_source 標記。您必須將 --data_source 旗標設為 cross_region_copy。如需 --data_source 標記的有效值完整清單,請參閱 bq 指令列工具參考資料中的轉移設定標記

    bq mk \
      --transfer_config \
      --project_id=PROJECT \
      --data_source=cross_region_copy \
      --target_dataset=DATASET \
      --display_name=NAME \
     --service_account_name=SERCICE_ACCOUNT \
      --params='PARAMETERS'

    更改下列內容:

    • NAME:複製作業或移轉設定的顯示名稱

    • SERVICE_ACCOUNT:用於驗證轉移作業的服務帳戶名稱。服務帳戶應由用於建立轉移作業的 project_id 擁有,且應具備所有必要權限

    • PARAMETERS:移轉設定的 JSON 格式參數

      資料集複製作業設定的參數包括:

      • source_dataset_id:您要複製的來源資料集 ID
      • source_project_id:來源資料集所在專案的 ID。
      • overwrite_destination_table:可選標記,可讓您截斷前一個副本的資料表並重新整理所有資料

      來源和目的地資料表都必須具有相同的分割結構定義。

    以下範例會根據系統環境顯示參數的格式:

    • Linux:使用單引號括住 JSON 字串,例如:

      '{"source_dataset_id":"mydataset","source_project_id":"mysourceproject","overwrite_destination_table":"true"}'
      
    • Windows 命令列:使用雙引號括住 JSON 字串,並使用反斜線逸出字串中的雙引號,例如:

      "{\"source_dataset_id\":\"mydataset\",\"source_project_id\":\"mysourceproject\",\"overwrite_destination_table\":\"true\"}"
      
    • PowerShell:使用單引號括住 JSON 字串,並使用反斜線逸出字串中的雙引號,例如:

      '{\"source_dataset_id\":\"mydataset\",\"source_project_id\":\"mysourceproject\",\"overwrite_destination_table\":\"true\"}'
      

    舉例來說,下列指令會分別建立名為 My Transfer 的資料集複製作業設定、名為 mydataset 的目標資料集和 ID 為 myproject 的專案。

    bq mk \
      --transfer_config \
      --project_id=myproject \
      --data_source=cross_region_copy \
      --target_dataset=mydataset \
      --display_name='My Transfer' \
      --params='{
          "source_dataset_id":"123_demo_eu",
          "source_project_id":"mysourceproject",
          "overwrite_destination_table":"true"
          }'

API

  1. 為目的地資料集啟用 BigQuery 資料移轉服務

  2. 確認您具備必要角色

  3. 如要建立 BigQuery 資料集,請呼叫 datasets.insert 方法,搭配已定義的資料集資源

  4. 如要複製資料集,請使用 projects.locations.transferConfigs.create 方法,並提供 TransferConfig 資源的例項。

Java

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

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

import com.google.api.gax.rpc.ApiException;
import com.google.cloud.bigquery.datatransfer.v1.CreateTransferConfigRequest;
import com.google.cloud.bigquery.datatransfer.v1.DataTransferServiceClient;
import com.google.cloud.bigquery.datatransfer.v1.ProjectName;
import com.google.cloud.bigquery.datatransfer.v1.TransferConfig;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

// Sample to copy dataset from another gcp project
public class CopyDataset {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    final String destinationProjectId = "MY_DESTINATION_PROJECT_ID";
    final String destinationDatasetId = "MY_DESTINATION_DATASET_ID";
    final String sourceProjectId = "MY_SOURCE_PROJECT_ID";
    final String sourceDatasetId = "MY_SOURCE_DATASET_ID";
    Map<String, Value> params = new HashMap<>();
    params.put("source_project_id", Value.newBuilder().setStringValue(sourceProjectId).build());
    params.put("source_dataset_id", Value.newBuilder().setStringValue(sourceDatasetId).build());
    TransferConfig transferConfig =
        TransferConfig.newBuilder()
            .setDestinationDatasetId(destinationDatasetId)
            .setDisplayName("Your Dataset Copy Name")
            .setDataSourceId("cross_region_copy")
            .setParams(Struct.newBuilder().putAllFields(params).build())
            .setSchedule("every 24 hours")
            .build();
    copyDataset(destinationProjectId, transferConfig);
  }

  public static void copyDataset(String projectId, TransferConfig transferConfig)
      throws IOException {
    try (DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient.create()) {
      ProjectName parent = ProjectName.of(projectId);
      CreateTransferConfigRequest request =
          CreateTransferConfigRequest.newBuilder()
              .setParent(parent.toString())
              .setTransferConfig(transferConfig)
              .build();
      TransferConfig config = dataTransferServiceClient.createTransferConfig(request);
      System.out.println("Copy dataset created successfully :" + config.getName());
    } catch (ApiException ex) {
      System.out.print("Copy dataset was not created." + ex.toString());
    }
  }
}

Python

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

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

請使用 pip install google-cloud-bigquery-datatransfer 安裝 BigQuery Data Transfer API 的 Python 用戶端。然後建立移轉設定來複製資料集。
from google.cloud import bigquery_datatransfer

transfer_client = bigquery_datatransfer.DataTransferServiceClient()

destination_project_id = "my-destination-project"
destination_dataset_id = "my_destination_dataset"
source_project_id = "my-source-project"
source_dataset_id = "my_source_dataset"
transfer_config = bigquery_datatransfer.TransferConfig(
    destination_dataset_id=destination_dataset_id,
    display_name="Your Dataset Copy Name",
    data_source_id="cross_region_copy",
    params={
        "source_project_id": source_project_id,
        "source_dataset_id": source_dataset_id,
    },
    schedule="every 24 hours",
)
transfer_config = transfer_client.create_transfer_config(
    parent=transfer_client.common_project_path(destination_project_id),
    transfer_config=transfer_config,
)
print(f"Created transfer config: {transfer_config.name}")

為了避免產生額外的儲存空間費用,建議您刪除先前的資料集

查看資料集複製作業

如要在Google Cloud 主控台中查看資料集複製工作的狀態和詳細資料,請按照下列步驟操作:

  1. 在 Google Cloud 控制台中,前往「資料移轉」頁面。

    前往「資料移轉」

  2. 選取要查看轉移詳細資料的轉移作業,然後執行下列操作:

    1. 在「Transfer details」(移轉作業詳細資料) 頁面中,選取移轉作業。

    2. 如要重新整理,請按一下 「重新整理」

在其他位置重新建立資料集

如要手動將資料集移至其他位置,請按照下列步驟操作:

  1. 將 BigQuery 資料表中的資料匯出至 Cloud Storage 值區。

    從 BigQuery 中匯出資料並不需要付費,但是在 Cloud Storage 儲存匯出的資料則會產生費用。BigQuery 匯出作業會受到匯出工作的相關限制。

  2. 從匯出 Cloud Storage 值區中複製或移動資料,然後匯出至您在目的地位置建立的新值區。舉例來說,如果您要將資料從 US 多地區位置移到 asia-northeast1 東京地區,則必須將資料移轉到您在東京建立的值區。如要瞭解如何轉移 Cloud Storage 物件,請參閱 Cloud Storage 說明文件中的「複製、重新命名及移動物件」一文。

    在不同地區之間轉移資料將導致 Cloud Storage 產生網路輸出費用

  3. 在新位置建立新的 BigQuery 資料集,然後將資料從 Cloud Storage 值區載入新資料集。

    將資料載入 BigQuery 無須支付費用,但將資料儲存於 Cloud Storage 則須支付費用,直到您刪除資料或值區為止。載入資料之後,將資料儲存至 BigQuery 亦須支付相關費用。將資料載入 BigQuery 時會受到載入工作限制。

您也可以使用 Cloud Composer,透過程式碼移動及複製大型資料集。

如要進一步瞭解如何使用 Cloud Storage 儲存及移動大型資料集,請參閱「搭配大數據使用 Cloud Storage」。

安全的資料集

如要控管 BigQuery 資料集的存取權,請參閱「控管資料集存取權」。如要進一步瞭解資料加密,請參閱「靜態資料加密」。

刪除資料集

使用 Google Cloud 控制台刪除資料集時,資料集中的資料表和檢視表 (及其資料) 都會遭到刪除。使用 bq 指令列工具刪除資料集時,您必須使用 -r 標記刪除資料表和檢視表。

如要刪除資料集,請選取下列其中一個選項:

主控台

  1. 前往「BigQuery」頁面

    前往 BigQuery

  2. 在「Explorer」窗格中展開專案並選取資料集。

  3. 展開 「Actions」 選項,然後按一下「Delete」

  4. 在「Delete dataset」(刪除資料集) 對話方塊中,在欄位中輸入 delete,然後按一下「Delete」(刪除)

SQL

如要刪除資料集,請使用 DROP SCHEMA DDL 陳述式

以下範例會刪除名為 mydataset 的資料集:

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

    前往 BigQuery

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

    DROP SCHEMA IF EXISTS mydataset;

    根據預設,這項功能只能用來刪除空資料集。如要刪除資料集及其所有內容,請使用 CASCADE 關鍵字:

    DROP SCHEMA IF EXISTS mydataset CASCADE;

  3. 按一下 「Run」

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

bq

請使用 bq rm 指令,並加上 --dataset-d 旗標 (選用)。如果資料集中包含資料表,您就必須使用 -r 標記來移除資料集中的所有資料表。如果您使用 -r 標記,可以省略 --dataset-d 標記。

執行指令後,系統會要求您確認。您可以使用 -f 標記來略過確認程序。

如要刪除非預設專案中的資料表,請使用下列格式將專案 ID 新增至資料集名稱:PROJECT_ID:DATASET

bq rm -r -f -d PROJECT_ID:DATASET

更改下列內容:

  • PROJECT_ID:您的專案 ID
  • DATASET:您要刪除的資料集名稱

範例:

輸入下列指令,即可從預設專案中移除名為 mydataset 的資料集及其所有資料表。這個指令會使用 -d 旗標。

bq rm -r -d mydataset

當系統提示時,請輸入 y,然後按下 Enter 鍵。

輸入下列指令,即可從 myotherproject 中移除 mydataset 及其中的所有資料表。這個指令不會使用選用的 -d 標記。-f 標記可用來略過確認程序。

bq rm -r -f myotherproject:mydataset

您可以使用 bq ls 指令確認資料集是否已刪除。

API

呼叫 datasets.delete 方法來刪除資料集,然後將 deleteContents 參數設為 true 來刪除當中的資料表。

C#

以下程式碼範例會刪除空白資料集。

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

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

請使用 pip install google-cloud-bigquery-datatransfer 安裝 BigQuery Data Transfer API 的 Python 用戶端。然後建立移轉設定來複製資料集。

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

public class BigQueryDeleteDataset
{
    public void DeleteDataset(
        string projectId = "your-project-id",
        string datasetId = "your_empty_dataset"
    )
    {
        BigQueryClient client = BigQueryClient.Create(projectId);
        // Delete a dataset that does not contain any tables
        client.DeleteDataset(datasetId: datasetId);
        Console.WriteLine($"Dataset {datasetId} deleted.");
    }
}

以下程式碼範例會刪除資料集及其所有內容:

// Copyright(c) 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//

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

public class BigQueryDeleteDatasetAndContents
{
    public void DeleteDatasetAndContents(
        string projectId = "your-project-id",
        string datasetId = "your_dataset_with_tables"
    )
    {
        BigQueryClient client = BigQueryClient.Create(projectId);
        // Use the DeleteDatasetOptions to delete a dataset and its contents
        client.DeleteDataset(
            datasetId: datasetId,
            options: new DeleteDatasetOptions() { DeleteContents = true }
        );
        Console.WriteLine($"Dataset {datasetId} and contents deleted.");
    }
}

Go

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

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

請使用 pip install google-cloud-bigquery-datatransfer 安裝 BigQuery Data Transfer API 的 Python 用戶端。然後建立移轉設定來複製資料集。
import (
	"context"
	"fmt"

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

// deleteDataset demonstrates the deletion of an empty dataset.
func deleteDataset(projectID, datasetID string) error {
	// projectID := "my-project-id"
	// datasetID := "mydataset"
	ctx := context.Background()

	client, err := bigquery.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("bigquery.NewClient: %v", err)
	}
	defer client.Close()

	// To recursively delete a dataset and contents, use DeleteWithContents.
	if err := client.Dataset(datasetID).Delete(ctx); err != nil {
		return fmt.Errorf("Delete: %v", err)
	}
	return nil
}

Java

以下程式碼範例會刪除空白資料集。

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

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

請使用 pip install google-cloud-bigquery-datatransfer 安裝 BigQuery Data Transfer API 的 Python 用戶端。然後建立移轉設定來複製資料集。
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQuery.DatasetDeleteOption;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.DatasetId;

public class DeleteDataset {

  public static void runDeleteDataset() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "MY_PROJECT_ID";
    String datasetName = "MY_DATASET_NAME";
    deleteDataset(projectId, datasetName);
  }

  public static void deleteDataset(String projectId, String datasetName) {
    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();

      DatasetId datasetId = DatasetId.of(projectId, datasetName);
      boolean success = bigquery.delete(datasetId, DatasetDeleteOption.deleteContents());
      if (success) {
        System.out.println("Dataset deleted successfully");
      } else {
        System.out.println("Dataset was not found");
      }
    } catch (BigQueryException e) {
      System.out.println("Dataset was not deleted. \n" + e.toString());
    }
  }
}

以下程式碼範例會刪除資料集及其所有內容:

/*
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.bigquery;

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

// Sample to delete dataset with contents.
public class DeleteDatasetAndContents {

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

  public static void deleteDatasetAndContents(String projectId, String datasetName) {
    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();

      DatasetId datasetId = DatasetId.of(projectId, datasetName);
      // Use the force parameter to delete a dataset and its contents
      boolean success = bigquery.delete(datasetId, BigQuery.DatasetDeleteOption.deleteContents());
      if (success) {
        System.out.println("Dataset deleted with contents successfully");
      } else {
        System.out.println("Dataset was not found");
      }
    } catch (BigQueryException e) {
      System.out.println("Dataset was not deleted with contents. \n" + e.toString());
    }
  }
}

Node.js

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

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

請使用 pip install google-cloud-bigquery-datatransfer 安裝 BigQuery Data Transfer API 的 Python 用戶端。然後建立移轉設定來複製資料集。
// Import the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();

async function deleteDataset() {
  // Deletes a dataset named "my_dataset".

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

  // Create a reference to the existing dataset
  const dataset = bigquery.dataset(datasetId);

  // Delete the dataset and its contents
  await dataset.delete({force: true});
  console.log(`Dataset ${dataset.id} deleted.`);
}

PHP

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

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

請使用 pip install google-cloud-bigquery-datatransfer 安裝 BigQuery Data Transfer API 的 Python 用戶端。然後建立移轉設定來複製資料集。
use Google\Cloud\BigQuery\BigQueryClient;

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

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

Python

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

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

請使用 pip install google-cloud-bigquery-datatransfer 安裝 BigQuery Data Transfer API 的 Python 用戶端。然後建立移轉設定來複製資料集。

from google.cloud import bigquery

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

# TODO(developer): Set model_id to the ID of the model to fetch.
# dataset_id = 'your-project.your_dataset'

# Use the delete_contents parameter to delete a dataset and its contents.
# Use the not_found_ok parameter to not receive an error if the dataset has already been deleted.
client.delete_dataset(
    dataset_id, delete_contents=True, not_found_ok=True
)  # Make an API request.

print("Deleted dataset '{}'.".format(dataset_id))

Ruby

以下程式碼範例會刪除空白資料集。

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

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

請使用 pip install google-cloud-bigquery-datatransfer 安裝 BigQuery Data Transfer API 的 Python 用戶端。然後建立移轉設定來複製資料集。
require "google/cloud/bigquery"

def delete_dataset dataset_id = "my_empty_dataset"
  bigquery = Google::Cloud::Bigquery.new

  # Delete a dataset that does not contain any tables
  dataset = bigquery.dataset dataset_id
  dataset.delete
  puts "Dataset #{dataset_id} deleted."
end

以下程式碼範例會刪除資料集及其所有內容:

# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "google/cloud/bigquery"

def delete_dataset_and_contents dataset_id = "my_dataset_with_tables"
  bigquery = Google::Cloud::Bigquery.new

  # Use the force parameter to delete a dataset and its contents
  dataset = bigquery.dataset dataset_id
  dataset.delete force: true
  puts "Dataset #{dataset_id} and contents deleted."
end

從已刪除的資料集還原資料表

您可以在資料集的時間回溯期內,從已刪除的資料集中還原資料表。如要還原整個資料集,請參閱「還原已刪除的資料集」。

  1. 建立名稱相同的資料集,並放在原始資料集所在的位置。
  2. 使用 Epoch 紀元時間起算的毫秒數格式,選擇原始資料集刪除前的時間戳記,例如 1418864998000
  3. 將時間為 1418864998000originaldataset.table1 資料表複製到新資料集:

    bq cp originaldataset.table1@1418864998000 mydataset.mytable
    

    如要找出已刪除資料集中非空資料表的名稱,請在時間回溯期間查詢資料集的 INFORMATION_SCHEMA.TABLE_STORAGE 檢視畫面

還原已刪除的資料集

如要瞭解如何還原 (或取消刪除) 已刪除的資料集,請參閱「還原已刪除的資料集」一文。

配額

如要瞭解複製配額,請參閱「複製工作」。複製工作的用法可在 INFORMATION_SCHEMA 中找到。如要瞭解如何查詢 INFORMATION_SCHEMA.JOBS 檢視畫面,請參閱「JOBS 檢視畫面」。

定價

如需複製資料集的定價資訊,請參閱「資料複製定價」。

BigQuery 會傳送壓縮資料以跨地區進行複製,因此計費的資料可能小於資料集的實際大小。詳情請參閱 BigQuery 價格一文。

後續步驟