建立分區資料表

本頁面說明如何在 BigQuery 中建立分區資料表。如需分區資料表的總覽,請參閱分區資料表簡介一文。

事前準備

授予身分與存取權管理 (IAM) 角色,讓使用者取得執行本文件中各項工作的必要權限。

所需權限

如要建立資料表,您必須具備下列 IAM 權限:

  • bigquery.tables.create
  • bigquery.tables.updateData
  • bigquery.jobs.create

此外,您可能需要 bigquery.tables.getData 權限,才能存取您寫入資料表的資料。

以下每個預先定義的 IAM 角色都包含建立資料表所需的權限:

  • roles/bigquery.dataEditor
  • roles/bigquery.dataOwner
  • roles/bigquery.admin (包含 bigquery.jobs.create 權限)
  • roles/bigquery.user (包含 bigquery.jobs.create 權限)
  • roles/bigquery.jobUser (包含 bigquery.jobs.create 權限)

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

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

建立空白分區資料表

在 BigQuery 中建立分區資料表的步驟與建立標準資料表的步驟類似,唯一的差異在於您需要指定分區選項,以及其他任何資料表選項。

建立時間單位資料欄分區資料表

如何使用結構定義建立空白時間單位資料欄分區資料表:

主控台

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

    前往 BigQuery

  2. 在「Explorer」窗格中展開專案,然後選取資料集。
  3. 在「資料集資訊」部分,按一下 「建立資料表」
  4. 在「Create table」面板中,指定下列詳細資料:
    1. 在「Source」部分,選取「Create table from」清單中的「Empty table」
    2. 在「Destination」(目的地) 部分中,指定下列詳細資料:
      1. 在「Dataset」(資料集) 部分,選取要建立資料表的資料集。
      2. 在「Table」(資料表) 欄位中,輸入要建立的資料表名稱。
      3. 確認「Table type」欄位已設為「Native table」
    3. 在「Schema」區段中,輸入結構定義。結構定義必須包含分區欄的 DATETIMESTAMPDATETIME 資料欄。詳情請參閱「指定結構定義」。您可以使用下列任一方式,手動輸入結構定義資訊:
      • 選項 1:按一下「Edit as Text」(以文字形式編輯),然後以 JSON 陣列的形式貼上結構定義。如果您使用 JSON 陣列,可透過與建立 JSON 結構定義檔一樣的程序產生結構定義。您可以輸入下列指令,查看現有資料表的 JSON 格式結構定義:
            bq show --format=prettyjson dataset.table
            
      • 選項 2:按一下「新增欄位」,然後輸入表格結構定義。指定每個欄位的「Name」、「Type」 和「Mode」
    4. 在「Partition and cluster settings」(分區與叢集設定) 區段的「Partitioning」(分區) 清單中,選取「Partition by field」(依欄位分區),然後選擇分區欄位。只有在結構定義包含 DATETIMESTAMPDATETIME 資料欄時,才能使用這個選項。
    5. 選用:如要要求在對這個資料表進行的所有查詢中使用分區篩選器,請選取「Require partition filter」(需要分區篩選器) 核取方塊。分區篩選器可以降低成本並提升效能。詳情請參閱「設定分區篩選器規定」。
    6. 選取「Partitioning type」,選擇每日、每小時、每月或每年的分區。
    7. 選用步驟:如果您想使用客戶管理的加密金鑰,請在「Advanced options」(進階選項) 部分選取「Use a customer-managed encryption key (CMEK)」(使用客戶管理的加密金鑰 (CMEK)) 選項。根據預設,BigQuery 會使用 Google-owned and Google-managed encryption key加密靜態儲存的客戶內容
    8. 點選「建立資料表」。

SQL

如要建立時間單位資料欄分區資料表,請使用 CREATE TABLE DDL 陳述式,並搭配 PARTITION BY 子句

以下範例會根據 transaction_date 資料欄,建立每日分區的資料表:

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

    前往 BigQuery

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

    CREATE TABLE
      mydataset.newtable (transaction_id INT64, transaction_date DATE)
    PARTITION BY
      transaction_date
      OPTIONS (
        partition_expiration_days = 3,
        require_partition_filter = TRUE);

    使用 OPTIONS 子句設定資料表選項,例如分區到期日分區篩選器要求

  3. 按一下 「Run」

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

DATE 欄位的預設分區類型為每日分區。如要指定其他分割類型,請在 PARTITION BY 子句中加入 DATE_TRUNC 函式。例如,下列查詢會建立每月分區的資料表:

CREATE TABLE
  mydataset.newtable (transaction_id INT64, transaction_date DATE)
PARTITION BY
  DATE_TRUNC(transaction_date, MONTH)
  OPTIONS (
    partition_expiration_days = 3,
    require_partition_filter = TRUE);

您也可以指定 TIMESTAMPDATETIME 資料欄做為分區資料欄。在這種情況下,請在 PARTITION BY 子句中加入 TIMESTAMP_TRUNCDATETIME_TRUNC 函式,指定分割區類型。舉例來說,以下陳述式會建立資料表,其中包含根據 TIMESTAMP 資料欄建立的每日分區:

CREATE TABLE
  mydataset.newtable (transaction_id INT64, transaction_ts TIMESTAMP)
PARTITION BY
  TIMESTAMP_TRUNC(transaction_ts, DAY)
  OPTIONS (
    partition_expiration_days = 3,
    require_partition_filter = TRUE);

bq

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 請使用 bq mk 指令,並加上 --table 旗標 (或 -t 捷徑):

    bq mk \
       --table \
       --schema SCHEMA \
       --time_partitioning_field COLUMN \
       --time_partitioning_type UNIT_TIME \
       --time_partitioning_expiration EXPIRATION_TIME \
       --require_partition_filter=BOOLEAN
       PROJECT_ID:DATASET.TABLE

    更改下列內容:

    • SCHEMA:格式為 column:data_type,column:data_type 的結構定義,或您本機電腦上的 JSON 結構定義檔路徑。詳情請參閱「指定結構定義」。
    • COLUMN:區隔資料欄的名稱。在資料表結構定義中,這個欄必須是 TIMESTAMPDATETIMEDATE 類型。
    • UNIT_TIME:分區類型。支援的值包括 DAYHOURMONTHYEAR
    • EXPIRATION_TIME:資料表分區的到期時間,以秒為單位。--time_partitioning_expiration 是選用旗標。詳情請參閱「設定分割區到期時間」。
    • BOOLEAN:如果 true,則對這個資料表的查詢必須包含分區篩選器。--require_partition_filter 是選用旗標。詳情請參閱「設定分區篩選器規定」。
    • PROJECT_ID:專案 ID。如果未指定,系統會使用預設專案。
    • DATASET:專案中的資料集名稱。
    • TABLE:要建立的資料表名稱。

    如需其他指令列選項,請參閱 bq mk

    下列範例會使用每小時分區,建立名為 mytable 的資料表,並在 ts 資料欄上進行分區。分區到期時間為 259,200 秒 (3 天)。

    bq mk \
       -t \
       --schema 'ts:TIMESTAMP,qtr:STRING,sales:FLOAT' \
       --time_partitioning_field ts \
       --time_partitioning_type HOUR \
       --time_partitioning_expiration 259200  \
       mydataset.mytable

Terraform

使用 google_bigquery_table 資源。

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

以下範例會建立名為 mytable 的資料表,這個資料表按天分區:

resource "google_bigquery_dataset" "default" {
  dataset_id                      = "mydataset"
  default_partition_expiration_ms = 2592000000  # 30 days
  default_table_expiration_ms     = 31536000000 # 365 days
  description                     = "dataset description"
  location                        = "US"
  max_time_travel_hours           = 96 # 4 days

  labels = {
    billing_group = "accounting",
    pii           = "sensitive"
  }
}

resource "google_bigquery_table" "default" {
  dataset_id          = google_bigquery_dataset.default.dataset_id
  table_id            = "mytable"
  deletion_protection = false # set to "true" in production

  time_partitioning {
    type          = "DAY"
    field         = "Created"
    expiration_ms = 432000000 # 5 days
  }
  require_partition_filter = true

  schema = <<EOF
[
  {
    "name": "ID",
    "type": "INT64",
    "mode": "NULLABLE",
    "description": "Item ID"
  },
  {
    "name": "Created",
    "type": "TIMESTAMP",
    "description": "Record creation timestamp"
  },
  {
    "name": "Item",
    "type": "STRING",
    "mode": "NULLABLE"
  }
]
EOF

}

如要在 Google Cloud 專案中套用 Terraform 設定,請完成下列各節中的步驟。

準備 Cloud Shell

  1. 啟動 Cloud Shell
  2. 設定要套用 Terraform 設定的預設 Google Cloud 專案。

    您只需為每個專案執行這個指令一次,而且可以在任何目錄中執行。

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    如果您在 Terraform 設定檔中設定明確的值,系統就會覆寫環境變數。

準備目錄

每個 Terraform 設定檔都必須有自己的目錄 (也稱為根模組)。

  1. Cloud Shell 中建立目錄,並在該目錄中建立新檔案。檔案名稱必須包含 .tf 副檔名,例如 main.tf。在本教學課程中,檔案稱為 main.tf
    mkdir DIRECTORY && cd DIRECTORY && touch main.tf
  2. 如果您正在參考教學課程,可以複製各個章節或步驟中的程式碼範例。

    將範例程式碼複製到新建立的 main.tf 中。

    您可以視需要從 GitHub 複製程式碼。如果 Terraform 程式碼片段是端對端解決方案的一部分,建議您採用這種做法。

  3. 查看並修改要套用至環境的範例參數。
  4. 儲存變更。
  5. 初始化 Terraform。這項操作只需對每個目錄執行一次。
    terraform init

    如要使用最新版的 Google 供應器,您可以選擇加入 -upgrade 選項:

    terraform init -upgrade

套用變更

  1. 檢查設定,確認 Terraform 要建立或更新的資源符合您的預期:
    terraform plan

    視需要修正設定。

  2. 執行下列指令,並在提示中輸入 yes,即可套用 Terraform 設定:
    terraform apply

    等待 Terraform 顯示「Apply complete!」(套用完成) 訊息。

  3. 開啟 Google Cloud 專案即可查看結果。在 Google Cloud 控制台中,前往 UI 中的資源,確認 Terraform 已建立或更新這些資源。

API

使用指定 timePartitioning 屬性和 schema 屬性的已定義資料表資源呼叫 tables.insert 方法。

Go

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

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

import (
	"context"
	"fmt"
	"time"

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

// createTablePartitioned demonstrates creating a table and specifying a time partitioning configuration.
func createTablePartitioned(projectID, datasetID, tableID string) error {
	// projectID := "my-project-id"
	// datasetID := "mydatasetid"
	// tableID := "mytableid"
	ctx := context.Background()

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

	sampleSchema := bigquery.Schema{
		{Name: "name&quot;, Type: bigquery.StringFieldType},
		{Name: &quot;post_abbr"&, Type: bigquery.IntegerFieldType},
		{Name:& "date", Type: bigquery.DateFieldType},
	}
	metadata := bigquery.TableMetadata{
		TimePartitioning: bigquery.TimePartitioning{
			Field:      "date",
			Expiration: 90 * 24 * time.Hour,
		},
		Schema: sampleSchema,
	}
	tableRef := client.Dataset(datasetID).Table(tableID)
	if err := tableRef.Create(ctx, metadata); 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.Field;
import com.google.cloud.bigquery.Schema;
import com.google.cloud.bigquery.StandardSQLTypeName;
import com.google.cloud.bigquery.StandardTableDefinition;
import com.google.cloud.bigquery.TableId;
import com.google.cloud.bigquery.TableInfo;
import com.google.cloud.bigquery.TimePartitioning;

// Sample to create a partition table
public class CreatePartitionedTable {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String datasetName = "MY_DATASET_NAME";
    String tableName = "MY_TABLE_NAME";
    Schema schema =
        Schema.of(
            Field.of("name", StandardSQLTypeName.STRING),
            Field.of(&quot;post_abbr", StandardSQLTypeName.STRING),
            Field.of("date", StandardSQLTypeName.DATE));
    createPartitionedTable(datasetName, tableName, schema);
  }

  public static void createPartitionedTable(String datasetName, String tableName, Schema schema) {
    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, tableName);

      TimePartitioning partitioning =
          TimePartitioning.newBuilder(TimePartitioning.Type.DAY)
              .setField("date") //  name of column to use for partitioning
              .setExpirationMs(7776000000L) // 90 days
              .build();

      StandardTableDefinition tableDefinition =
          StandardTableDefinition.newBuilder()
              .setSchema(schema)
              .setTimePartitioning(partitioning)
              .build();
      TableInfo tableInfo = TableInfo.newBuilder(tableId, tableDefinition).build();

      bigquery.create(tableInfo);
      System.out.println("Partitioned table created successfully");
    } catch (BigQueryException e) {
      System.out.println("Partitioned table was not created. \n" + e.toString());
    }
  }
}

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 createTablePartitioned() {
  // Creates a new partitioned table named "my_table" in "my_dataset".

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const datasetId = "my_dataset";
  // const tableId = "my_table";
  const schema = 'Name:string, Post_Abbr:string, Date:date';

  // For all options, see https://cloud.google.com/bigquery/docs/reference/v2/tables#resource
  const options = {
    schema: schema,
    location: 'US',
    timePartitioning: {
      type: 'DAY',
      expirationMS: '7776000000',
      field: 'date',
    },
  };

  // Create a new table in the dataset
  const [table] = await bigquery
    .dataset(datasetId)
    .createTable(tableId, options);
  console.log(`Table ${table.id} created with partitioning: `);
  console.log(table.metadata.timePartitioning);
}

Python

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

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

from google.cloud import bigquery

client = bigquery.Client()

# Use format "your-project.your_dataset.your_table_name" for table_id
table_id = your_fully_qualified_table_id
schema = [
    bigquery.SchemaField("name&quot;, &quot;STRING&quot;),
    bigquery.SchemaField("post_abbr&quot;, "STRING"),
    bigquery.SchemaField("date", "DATE"),
]
table = bigquery.Table(table_id, schema=schema)
table.time_partitioning = bigquery.TimePartitioning(
    type_=bigquery.TimePartitioningType.DAY,
    field="date",  # name of column to use for partitioning
    expiration_ms=1000 * 60 * 60 * 24 * 90,
)  # 90 days

table = client.create_table(table)

print(
    f"Created table {table.project}.{table.dataset_id}.{table.table_id}, "
    f"partitioned on column {table.time_partitioning.field}."
)

建立擷取時間分區資料表

如何使用結構定義建立空白擷取時間分區資料表:

主控台

  1. 在 Google Cloud 控制台開啟「BigQuery」頁面。

    前往「BigQuery」頁面

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

  3. 展開 「動作」選項,然後按一下「開啟」

  4. 在詳細資料面板中,按一下「Create table」(建立資料表) 圖示

  5. 在「Create table」(建立資料表) 頁面的「Source」(來源) 區段中,選取 [Empty table] (空白資料表)

  6. 在「Destination」(目的地) 區段中:

    • 在「Dataset name」(資料集名稱) 部分選擇適當的資料集。
    • 在「Table name」(資料表名稱) 欄位中,輸入資料表名稱。
    • 確認「Table type」(資料表類型) 設為「Native table」(原生資料表)
  7. 在「Schema」(結構定義) 部分輸入結構定義

  8. 在「Partition and cluster settings」(分區與叢集設定) 區段的「Partitioning」(分區) 中,按一下「Partition by ingestion time」(依擷取時間分區)

  9. (選用) 如要要求在對這個資料表進行的所有查詢中使用分區篩選器,請選取「Require partition filter」(需要分區篩選器) 核取方塊。使用分區篩選器可以降低成本並提升效能。詳情請參閱「設定分區篩選器規定」。

  10. 點選「建立資料表」。

SQL

如要建立擷取時間分區資料表,請使用 CREATE TABLE 陳述式,並搭配依 _PARTITIONDATE 分區的 PARTITION BY 子句

以下範例會建立每日分區的資料表:

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

    前往 BigQuery

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

    CREATE TABLE
      mydataset.newtable (transaction_id INT64)
    PARTITION BY
      _PARTITIONDATE
      OPTIONS (
        partition_expiration_days = 3,
        require_partition_filter = TRUE);

    使用 OPTIONS 子句設定資料表選項,例如分區到期日分區篩選器要求

  3. 按一下 「Run」

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

擷取時間分區的預設分區類型為每日分區。如要指定不同的分割類型,請在 PARTITION BY 子句中加入 DATE_TRUNC 函式。例如,下列查詢會建立每月分區的資料表:

CREATE TABLE
  mydataset.newtable (transaction_id INT64)
PARTITION BY
  DATE_TRUNC(_PARTITIONTIME, MONTH)
  OPTIONS (
    partition_expiration_days = 3,
    require_partition_filter = TRUE);

bq

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 請使用 bq mk 指令,並加上 --table 旗標 (或 -t 捷徑):

    bq mk \
       --table \
       --schema SCHEMA \
       --time_partitioning_type UNIT_TIME \
       --time_partitioning_expiration EXPIRATION_TIME \
       --require_partition_filter=BOOLEAN  \
       PROJECT_ID:DATASET.TABLE

    更改下列內容:

    • SCHEMA:格式為 column:data_type,column:data_type 的定義,或本機上 JSON 結構定義檔的路徑。詳情請參閱「指定結構定義」。
    • UNIT_TIME:分區類型。支援的值包括 DAYHOURMONTHYEAR
    • EXPIRATION_TIME:資料表分區的到期時間,以秒為單位。--time_partitioning_expiration 是選用旗標。詳情請參閱「設定分割區到期時間」。
    • BOOLEAN:如果 true,則對這個資料表的查詢必須包含分區篩選器。--require_partition_filter 是選用旗標。詳情請參閱「設定分區篩選器規定」。
    • PROJECT_ID:專案 ID。如果未指定,系統會使用預設專案。
    • DATASET:專案中的資料集名稱。
    • TABLE:要建立的資料表名稱。

    如需其他指令列選項,請參閱 bq mk

    以下範例會建立名為 mytable 的擷取時間分區資料表。這個資料表採用每日分區,分區到期時間為 259,200 秒 (3 天)。

    bq mk \
       -t \
       --schema qtr:STRING,sales:FLOAT,year:STRING \
       --time_partitioning_type DAY \
       --time_partitioning_expiration 259200 \
       mydataset.mytable

Terraform

使用 google_bigquery_table 資源。

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

以下範例會建立名為 mytable 的資料表,並按擷取時間分區:

resource "google_bigquery_dataset" "default" {
  dataset_id                      = "mydataset"
  default_partition_expiration_ms = 2592000000  # 30 days
  default_table_expiration_ms     = 31536000000 # 365 days
  description                     = "dataset description"
  location                        = "US"
  max_time_travel_hours           = 96 # 4 days

  labels = {
    billing_group = "accounting",
    pii           = "sensitive"
  }
}

resource "google_bigquery_table" "default" {
  dataset_id          = google_bigquery_dataset.default.dataset_id
  table_id            = "mytable"
  deletion_protection = false # set to "true" in production

  time_partitioning {
    type          = "MONTH"
    expiration_ms = 604800000 # 7 days
  }
  require_partition_filter = true

  schema = <<EOF
[
  {
    "name": "ID",
    "type": "INT64",
    "mode": "NULLABLE",
    "description": "Item ID"
  },
  {
    "name": "Item",
    "type": "STRING",
    "mode": "NULLABLE"
  }
]
EOF

}

如要在 Google Cloud 專案中套用 Terraform 設定,請完成下列各節中的步驟。

準備 Cloud Shell

  1. 啟動 Cloud Shell
  2. 設定要套用 Terraform 設定的預設 Google Cloud 專案。

    您只需為每個專案執行這個指令一次,而且可以在任何目錄中執行。

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    如果您在 Terraform 設定檔中設定明確的值,系統就會覆寫環境變數。

準備目錄

每個 Terraform 設定檔都必須有自己的目錄 (也稱為根模組)。

  1. Cloud Shell 中建立目錄,並在該目錄中建立新檔案。檔案名稱必須包含 .tf 副檔名,例如 main.tf。在本教學課程中,檔案稱為 main.tf
    mkdir DIRECTORY && cd DIRECTORY && touch main.tf
  2. 如果您正在參考教學課程,可以複製各個章節或步驟中的程式碼範例。

    將範例程式碼複製到新建立的 main.tf 中。

    您可以視需要從 GitHub 複製程式碼。如果 Terraform 程式碼片段是端對端解決方案的一部分,建議您採用這種做法。

  3. 查看並修改要套用至環境的範例參數。
  4. 儲存變更。
  5. 初始化 Terraform。這項操作只需對每個目錄執行一次。
    terraform init

    如要使用最新版的 Google 供應器,您可以選擇加入 -upgrade 選項:

    terraform init -upgrade

套用變更

  1. 檢查設定,確認 Terraform 要建立或更新的資源符合您的預期:
    terraform plan

    視需要修正設定。

  2. 執行下列指令,並在提示中輸入 yes,即可套用 Terraform 設定:
    terraform apply

    等待 Terraform 顯示「Apply complete!」(套用完成) 訊息。

  3. 開啟 Google Cloud 專案即可查看結果。在 Google Cloud 控制台中,前往 UI 中的資源,確認 Terraform 已建立或更新這些資源。

API

使用指定 timePartitioning 屬性和 schema 屬性的已定義資料表資源呼叫 tables.insert 方法。

建立整數範圍分區資料表

如何使用結構定義建立空白整數範圍分區資料表:

主控台

  1. 在 Google Cloud 控制台開啟「BigQuery」頁面。

    前往「BigQuery」頁面

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

  3. 展開 「動作」選項,然後按一下「開啟」

  4. 在詳細資料面板中,按一下「Create table」(建立資料表) 圖示

  5. 在「Create table」(建立資料表) 頁面的「Source」(來源) 區段中,選取 [Empty table] (空白資料表)

  6. 在「Destination」(目的地) 區段中:

    • 在「Dataset name」(資料集名稱) 部分選擇適當的資料集。
    • 在「Table name」(資料表名稱) 欄位中,輸入資料表名稱。
    • 確認「Table type」(資料表類型) 設為「Native table」(原生資料表)
  7. 在「Schema」區段中輸入結構定義。請確認結構定義包含分區資料欄的 INTEGER 欄。詳情請參閱「指定結構定義」。

  8. 在「Partition and cluster settings」(分區與叢集設定) 區段的「Partitioning」(分區) 下拉式清單中,選取「Partition by field」(依欄位分區),然後選擇分區欄位。只有在結構定義包含 INTEGER 資料欄時,才能使用這個選項。

  9. 請為「Start」、「End」和「Interval」提供值:

    • 「Start」是第一個分區範圍的起始值 (含)。
    • 「End」 是最後一個分區範圍的結束值 (不含)。
    • 「Interval」是每個分區範圍的寬度。

    超出這些範圍的值會放入特殊的 __UNPARTITIONED__ 分區。

  10. (選用) 如要要求在對這個資料表進行的所有查詢中使用分區篩選器,請選取「Require partition filter」(需要分區篩選器) 核取方塊。使用分區篩選器可以降低成本並提升效能。詳情請參閱「設定分區篩選器規定」。

  11. 點選「建立資料表」。

SQL

如要建立整數範圍分區資料表,請使用 CREATE TABLE DDL 陳述式,並搭配 PARTITION BY 子句

以下範例會建立在 customer_id 資料欄上進行分區的資料表,這個分區的起始值為 0、結束值為 100,且數字間隔為 10:

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

    前往 BigQuery

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

    CREATE TABLE mydataset.newtable (customer_id INT64, date1 DATE)
    PARTITION BY
      RANGE_BUCKET(customer_id, GENERATE_ARRAY(0, 100, 10))
      OPTIONS (
        require_partition_filter = TRUE);

    使用 OPTIONS 子句設定表格選項,例如分區篩選器要求

  3. 按一下 「Run」

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

bq

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 請使用 bq mk 指令,並加上 --table 旗標 (或 -t 捷徑):

    bq mk \
       --schema schema \
       --range_partitioning=COLUMN_NAME,START,END,INTERVAL \
       --require_partition_filter=BOOLEAN  \
       PROJECT_ID:DATASET.TABLE

    更改下列內容:

    • SCHEMA:格式為 column:data_type,column:data_type 的內嵌結構定義,或您本機電腦上的 JSON 結構定義檔案路徑。詳情請參閱「指定結構定義」。
    • COLUMN_NAME:區隔資料欄的名稱。在資料表結構定義中,此欄必須是 INTEGER 類型。
    • START:第一個分區範圍的起始值 (含)。
    • END:最後一個分區範圍的結束值 (不含)。
    • INTERVAL:每個分區範圍的寬度。
    • BOOLEAN:如果 true,則對這個資料表的查詢必須包含分區篩選器。--require_partition_filter 是選用旗標。詳情請參閱「設定分區篩選器規定」。
    • PROJECT_ID:專案 ID。如果未指定,系統會使用預設專案。
    • DATASET:專案中的資料集名稱。
    • TABLE:要建立的資料表名稱。

    超出分區範圍的值會放入特殊的 __UNPARTITIONED__ 分區。

    如需其他指令列選項,請參閱 bq mk

    以下範例會建立名為 mytable 的資料表,這個資料表會根據 customer_id 資料欄分區。

    bq mk \
       -t \
       --schema 'customer_id:INTEGER,qtr:STRING,sales:FLOAT' \
       --range_partitioning=customer_id,0,100,10 \
       mydataset.mytable

Terraform

使用 google_bigquery_table 資源。

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

以下範例會建立名為 mytable 的資料表,並按整數範圍分區:

resource "google_bigquery_dataset" "default" {
  dataset_id                      = "mydataset"
  default_partition_expiration_ms = 2592000000  # 30 days
  default_table_expiration_ms     = 31536000000 # 365 days
  description                     = "dataset description"
  location                        = "US"
  max_time_travel_hours           = 96 # 4 days

  labels = {
    billing_group = "accounting",
    pii           = "sensitive"
  }
}

resource "google_bigquery_table" "default" {
  dataset_id          = google_bigquery_dataset.default.dataset_id
  table_id            = "mytable"
  deletion_protection = false # set to "true" in production

  range_partitioning {
    field = "ID"
    range {
      start    = 0
      end      = 1000
      interval = 10
    }
  }
  require_partition_filter = true

  schema = <<EOF
[
  {
    "name": "ID",
    "type": "INT64",
    "description": "Item ID"
  },
  {
    "name": "Item",
    "type": "STRING",
    "mode": "NULLABLE"
  }
]
EOF

}

如要在 Google Cloud 專案中套用 Terraform 設定,請完成下列各節中的步驟。

準備 Cloud Shell

  1. 啟動 Cloud Shell
  2. 設定要套用 Terraform 設定的預設 Google Cloud 專案。

    您只需為每個專案執行這個指令一次,而且可以在任何目錄中執行。

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    如果您在 Terraform 設定檔中設定明確的值,系統就會覆寫環境變數。

準備目錄

每個 Terraform 設定檔都必須有自己的目錄 (也稱為根模組)。

  1. Cloud Shell 中建立目錄,並在該目錄中建立新檔案。檔案名稱必須包含 .tf 副檔名,例如 main.tf。在本教學課程中,檔案稱為 main.tf
    mkdir DIRECTORY && cd DIRECTORY && touch main.tf
  2. 如果您正在參考教學課程,可以複製各個章節或步驟中的程式碼範例。

    將範例程式碼複製到新建立的 main.tf 中。

    您可以視需要從 GitHub 複製程式碼。如果 Terraform 程式碼片段是端對端解決方案的一部分,建議您採用這種做法。

  3. 查看並修改要套用至環境的範例參數。
  4. 儲存變更。
  5. 初始化 Terraform。這項操作只需對每個目錄執行一次。
    terraform init

    如要使用最新版的 Google 供應器,您可以選擇加入 -upgrade 選項:

    terraform init -upgrade

套用變更

  1. 檢查設定,確認 Terraform 要建立或更新的資源符合您的預期:
    terraform plan

    視需要修正設定。

  2. 執行下列指令,並在提示中輸入 yes,即可套用 Terraform 設定:
    terraform apply

    等待 Terraform 顯示「Apply complete!」(套用完成) 訊息。

  3. 開啟 Google Cloud 專案即可查看結果。在 Google Cloud 控制台中,前往 UI 中的資源,確認 Terraform 已建立或更新這些資源。

API

使用指定 rangePartitioning 屬性和 schema 屬性的已定義資料表資源呼叫 tables.insert 方法。

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.Field;
import com.google.cloud.bigquery.RangePartitioning;
import com.google.cloud.bigquery.Schema;
import com.google.cloud.bigquery.StandardSQLTypeName;
import com.google.cloud.bigquery.StandardTableDefinition;
import com.google.cloud.bigquery.TableId;
import com.google.cloud.bigquery.TableInfo;

// Sample to create a range partitioned table
public class CreateRangePartitionedTable {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String datasetName = "MY_DATASET_NAME";
    String tableName = "MY_TABLE_NAME";
    Schema schema =
        Schema.of(
            Field.of("integerField", StandardSQLTypeName.INT64),
            Field.of(&quot;stringField", StandardSQLTypeName.STRING),
            Field.of("booleanField&quot;, StandardSQLTypeName.BOOL),
            Field.of("dateField", StandardSQLTypeName.DATE));
    createRangePartitionedTable(datasetName, tableName, schema);
  }

  public static void createRangePartitionedTable(
      String datasetName, String tableName, Schema schema) {
    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, tableName);

      // Note: The field must be a top- level, NULLABLE/REQUIRED field.
      // The only supported type is INTEGER/INT64
      RangePartitioning partitioning =
          RangePartitioning.newBuilder()
              .setField("integerField")
              .setRange(
                  RangePartitioning.Range.newBuilder()
                      .setStart(1L)
                      .setInterval(2L)
                      .setEnd(10L)
                      .build())
              .build();

      StandardTableDefinition tableDefinition =
          StandardTableDefinition.newBuilder()
              .setSchema(schema)
              .setRangePartitioning(partitioning)
              .build();
      TableInfo tableInfo = TableInfo.newBuilder(tableId, tableDefinition).build();

      bigquery.create(tableInfo);
      System.out.println("Range partitioned table created successfully");
    } catch (BigQueryException e) {
      System.out.println("Range partitioned table was not created. \n" + e.toString());
    }
  }
}

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 createTableRangePartitioned() {
  // Creates a new integer range partitioned table named "my_table"
  // in "my_dataset".

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

  const schema = [
    {name: 'fullName', type: 'STRING'},
    {name: 'city', type: 'STRING'},
    {name: 'zipcode', type: 'INTEGER'},
  ];

  // To use integer range partitioning, select a top-level REQUIRED or
  // NULLABLE column with INTEGER / INT64 data type. Values that are
  // outside of the range of the table will go into the UNPARTITIONED
  // partition. Null values will be in the NULL partition.
  const rangePartition = {
    field: 'zipcode',
    range: {
      start: 0,
      end: 100000,
      interval: 10,
    },
  };

  // For all options, see https://cloud.google.com/bigquery/docs/reference/v2/tables#resource
  const options = {
    schema: schema,
    rangePartitioning: rangePartition,
  };

  // Create a new table in the dataset
  const [table] = await bigquery
    .dataset(datasetId)
    .createTable(tableId, options);

  console.log(`Table ${table.id} created with integer range partitioning: `);
  console.log(table.metadata.rangePartitioning);
}

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 create.
# table_id = "your-project.your_dataset.your_table_name"

schema = [
    bigquery.SchemaField("full_name&quot;, &quot;STRING&quot;),
    bigquery.SchemaField(&quot;city&quot;, "STRING"),
    bigquery.SchemaField("zipcode", "INTEGER"),
]

table = bigquery.Table(table_id, schema=schema)
table.range_partitioning = bigquery.RangePartitioning(
    # To use integer range partitioning, select a top-level REQUIRED /
    # NULLABLE column with INTEGER / INT64 data type.
    field="zipcode",
    range_=bigquery.PartitionRange(start=0, end=100000, interval=10),
)
table = client.create_table(table)  # Make an API request.
print(
    &quot;Created table {}.{}.{}".format(table.project, table.dataset_id, table.table_id)
)

從查詢結果建立分區資料表

您可以透過下列方式,從查詢結果建立分區資料表:

  • 在 SQL 中,請使用 CREATE TABLE ... AS SELECT 陳述式。您可以使用這種方法建立以時間單位欄或整數範圍分區的資料表,但不能以擷取時間分區。
  • 使用 bq 指令列工具或 BigQuery API 為查詢設定目的地資料表。查詢執行時,BigQuery 會將結果寫入目的地資料表。您可以將此方法用於任何分割類型。
  • 呼叫 jobs.insert API 方法,並在 timePartitioning 屬性或 rangePartitioning 屬性中指定分區。

SQL

使用 CREATE TABLE 陳述式。加入 PARTITION BY 子句來設定分割作業。

以下範例會建立以 transaction_date 欄分區的資料表:

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

    前往 BigQuery

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

    CREATE TABLE
      mydataset.newtable (transaction_id INT64, transaction_date DATE)
    PARTITION BY
      transaction_date
    AS (
      SELECT
        transaction_id, transaction_date
      FROM
        mydataset.mytable
    );

    使用 OPTIONS 子句設定表格選項,例如分區篩選器要求

  3. 按一下 「Run」

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

bq

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 如要從查詢建立分區資料表,請使用 bq query 指令搭配 --destination_table 旗標和 --time_partitioning_type 旗標。

    時間單位資料欄分區:

    bq query \
       --use_legacy_sql=false \
       --destination_table TABLE_NAME \
       --time_partitioning_field COLUMN \
       --time_partitioning_type UNIT_TIME \
       &#39;QUERY_STATEMENT'

    擷取時間分區:

    bq query \
       --use_legacy_sql=false \
       --destination_table TABLE_NAME \
       --time_partitioning_type UNIT_TIME \
       &#39;QUERY_STATEMENT'

    整數範圍分區:

    bq query \
       --use_legacy_sql=false \
       --destination_table PROJECT_ID:DATASET.TABLE \
       --range_partitioning COLUMN,START,END,INTERVAL \
       &#39;QUERY_STATEMENT'

    更改下列內容:

    • PROJECT_ID:專案 ID。如果未指定,系統會使用預設專案。
    • DATASET:專案中的資料集名稱。
    • TABLE:要建立的資料表名稱。
    • COLUMN:區隔資料欄的名稱。
    • UNIT_TIME:分區類型。支援的值包括 DAYHOURMONTHYEAR
    • START:範圍分區的起始值 (含)。
    • END:範圍分區的結束值 (不含)。
    • INTERVAL:分區內每個範圍的寬度。
    • QUERY_STATEMENT:用於填入資料表的查詢。

    下列範例會使用每月分區,建立以 transaction_date 資料欄分區的資料表。

    bq query \
       --use_legacy_sql=false \
       --destination_table mydataset.newtable \
       --time_partitioning_field transaction_date \
       --time_partitioning_type MONTH \
       'SELECT transaction_id, transaction_date FROM mydataset.mytable'

    以下範例會使用整數範圍分區,在 customer_id 資料欄上建立分區資料表。

    bq query \
       --use_legacy_sql=false \
       --destination_table mydataset.newtable \
       --range_partitioning customer_id,0,100,10 \
       'SELECT * FROM mydataset.ponies'

    對於擷取時間分區資料表,您也可以使用分區修飾符將資料載入特定分區。以下範例會建立新的擷取時間分區資料表,並將資料載入 20180201 (2018 年 2 月 1 日) 分區:

    bq query \
       --use_legacy_sql=false  \
       --time_partitioning_type=DAY \
       --destination_table='newtable$20180201' \
       'SELECT * FROM mydataset.mytable'

API

如要將查詢結果儲存至分區資料表,請呼叫 jobs.insert 方法。設定 query 工作。在 destinationTable 中指定目標資料表。在 timePartitioning 屬性或 rangePartitioning 屬性中指定分割作業。

將日期資料分割資料表轉換成擷取時間分區資料表

如果您之前已建立日期資料分割資料表,可以在 bq 指令列工具中使用 partition 指令,將整組相關資料表轉換成一個擷取時間分區資料表。

bq --location=LOCATION partition \
    --time_partitioning_type=PARTITION_TYPE \
    --time_partitioning_expiration INTEGER \
    PROJECT_ID:SOURCE_DATASET.SOURCE_TABLE \
    PROJECT_ID:DESTINATION_DATASET.DESTINATION_TABLE

更改下列內容:

  • LOCATION:位置名稱。--location 是選用旗標。
  • PARTITION_TYPE:分區類型。可能的值包括 DAYHOURMONTHYEAR
  • INTEGER:分區到期時間,以秒為單位。這個值沒有下限。到期時間為分區的世界標準時間日期加整數值。time_partitioning_expiration 是選用旗標。
  • PROJECT_ID:您的專案 ID。
  • SOURCE_DATASET:包含日期區塊的資料表資料集。
  • SOURCE_TABLE:日期資料分割資料表的前置字串。
  • DESTINATION_DATASET:新分區資料表的資料集。
  • DESTINATION_TABLE:要建立的分區資料表名稱。

partition 指令不支援 --label--expiration--add_tags--description 標記。您可以在建立資料表後,在其中加入標籤、資料表到期時間、標記和說明。

執行 partition 指令時,BigQuery 會建立複製工作,從資料分割資料表產生分區。

以下範例會從一組前置符號為 sourcetable_ 的日期資料分割資料表,建立名為 mytable_partitioned 的擷取時間分區資料表。新資料表每天會進行分區,分區到期時間為 259,200 秒 (3 天)。

bq partition \
    --time_partitioning_type=DAY \
    --time_partitioning_expiration 259200 \
    mydataset.sourcetable_ \
    mydataset.mytable_partitioned

如果日期資料分割資料表是 sourcetable_20180126sourcetable_20180127,則這項指令會建立下列分區:mydataset.mytable_partitioned$20180126mydataset.mytable_partitioned$20180127

分區資料表安全性

分區資料表的存取權控管與標準資料表的存取權控管相同。詳情請參閱「資料表存取權控管簡介」。

後續步驟