建立及使用資料表

本文說明如何在 BigQuery 中建立及使用標準 (內建) 資料表。如要瞭解如何建立其他類型的資料表,請參閱以下文章:

建立資料表後,您可以執行下列作業:

  • 控管資料表資料的存取權。
  • 取得資料表的相關資訊。
  • 列出資料集中的資料表。
  • 取得資料表中繼資料。

如要進一步瞭解如何管理資料表,包括更新資料表屬性、複製資料表及刪除資料表,請參閱「管理資料表」一文。

事前準備

在 BigQuery 中建立資料表之前,請先執行以下操作:

資料表命名

在 BigQuery 中建立資料表時,每個資料集裡的資料表名稱不得重複。資料表名稱可以:

  • 包含的字元總數上限為 1,024 個 UTF-8 位元組。
  • 包含 L (字母)、M (符號)、N (數字)、Pc (連接號,包括底線)、Pd (破折號)、Zs (空格) 類別的萬國碼字元。詳情請參閱「一般類別」。

以下是有效資料表名稱的範例:table 01ग्राहक00_お客様étudiant-01

注意事項:

  • 根據預設,表格名稱會區分大小寫。mytableMyTable 可在同一資料集中共存,除非它們屬於已關閉大小寫敏感度的資料集
  • 我們已保留部分表格名稱和表格名稱前置字串,如果您收到錯誤訊息,指出表格名稱或前置字串已保留,請選取其他名稱,然後再試一次。
  • 如果序列中包含多個點運算子 (.),系統會隱含地移除重複的運算子。

    例如: project_name....dataset_name..table_name

    變成: project_name.dataset_name.table_name

製作表格

您可以透過下列方式在 BigQuery 中建立資料表:

  • 手動使用 Google Cloud 控制台或 bq 指令列工具的 bq mk 指令。
  • 呼叫 tables.insert API 方法,透過程式建立。
  • 使用用戶端程式庫。
  • 從查詢結果建立。
  • 定義參照外部資料來源的資料表。
  • 載入資料時。
  • 使用 CREATE TABLE 資料定義語言 (DDL) 陳述式。

所需權限

如要建立資料表,您必須具備下列 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 角色和權限,請參閱「預先定義的角色與權限」一文。

使用結構定義建立空白資料表

您可以透過下列方式建立具有結構定義的空白資料表:

  • 使用 Google Cloud 主控台輸入結構定義。
  • 使用 bq 指令列工具以內嵌方式提供結構定義。
  • 使用 bq 指令列工具提交 JSON 結構定義檔案。
  • 呼叫 API 的 tables.insert 方法時,在資料表資源中提供結構定義。

如要進一步瞭解如何指定資料表結構定義,請參閱「指定結構定義」。

您可以在建立資料表後於其中載入資料,或透過寫入查詢結果填入資料。

如何建立含結構定義的空白資料表:

主控台

  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」(結構定義) 部分輸入結構定義。您可以使用下列任一方法,手動輸入結構定義資訊:
      • 選項 1:按一下「Edit as Text」(以文字形式編輯),然後以 JSON 陣列的形式貼上結構定義。如果您使用 JSON 陣列,可透過與建立 JSON 結構定義檔一樣的程序產生結構定義。您可以輸入下列指令,查看現有資料表的 JSON 格式結構定義:
            bq show --format=prettyjson dataset.table
            
      • 選項 2:按一下 「新增欄位」,然後輸入表格結構定義。指定每個欄位的「Name」、「Type」 和「Mode」
    4. 選用步驟:指定「分區與叢集設定」。如需更多資訊,請參閱「建立分區資料表」和「建立及使用叢集資料表」。
    5. 選用步驟:如果您想使用客戶管理的加密金鑰,請在「Advanced options」(進階選項) 部分選取「Use a customer-managed encryption key (CMEK)」(使用客戶管理的加密金鑰 (CMEK)) 選項。根據預設,BigQuery 會使用 Google-owned and Google-managed encryption key加密靜態儲存的客戶內容
    6. 點選「建立資料表」。

SQL

以下範例會建立名為 newtable 且到期時間為 2023 年 1 月 1 日的資料表:

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

    前往 BigQuery

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

    CREATE TABLE mydataset.newtable (
      x INT64 OPTIONS (description = 'An optional INTEGER field'),
      y STRUCT <
        a ARRAY <STRING> OPTIONS (description = 'A repeated STRING field'),
        b BOOL
      >
    ) OPTIONS (
        expiration_timestamp = TIMESTAMP '2023-01-01 00:00:00 UTC',
        description = 'a table that expires in 2023',
        labels = [('org_unit', 'development')]);

  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 旗標。您可以透過內嵌方式或 JSON 結構定義檔提供資料表結構定義資訊。如需參數的完整清單,請參閱 bq mk --table 參考資料。部分選用參數包括:

    • --expiration
    • --description
    • --time_partitioning_field
    • --time_partitioning_type
    • --range_partitioning
    • --clustering_fields
    • --destination_kms_key
    • --label

    --time_partitioning_field--time_partitioning_type--range_partitioning--clustering_fields--destination_kms_key 在此處未示範。如要進一步瞭解這些選用參數,請參閱下列連結:

    • 如要進一步瞭解 --time_partitioning_field--time_partitioning_type--range_partitioning,請參閱分區資料表
    • 如要進一步瞭解 --clustering_fields,請參閱叢集資料表
    • 如要進一步瞭解 --destination_kms_key,請參閱客戶管理的加密金鑰

    如要建立非預設專案中的資料表,請使用下列格式將專案 ID 新增至資料集:project_id:dataset

    如要在具有結構定義的現有資料集中建立空白資料表,請輸入下列內容:

    bq mk \
    --table \
    --expiration=integer \
    --description=description \
    --label=key_1:value_1 \
    --label=key_2:value_2 \
    --add_tags=key_3:value_3[,...] \
    project_id:dataset.table \
    schema

    更改下列內容:

    • integer 是資料表的預設生命週期 (以秒為單位),最小值是 3600 秒 (1 小時)。到期時間為目前世界標準時間加上 [INTEGER] 中的整數值。如果您在建立資料表時設定了資料表的到期時間,則系統會忽略資料集的預設資料表到期時間設定。
    • description 是置於括號中的資料表說明。
    • key_1:value_1key_2:value_2 是指定標籤的鍵/值組合。
    • key_3:value_3 是指定代碼的鍵/值組合。在同一個標記下方新增多個標記,並在鍵/值組合之間使用逗號分隔。
    • project_id 是您的專案 ID。
    • dataset 是專案中的資料集。
    • table 是您所建立的資料表名稱。
    • schema 是格式為 field:data_type,field:data_type 的內嵌結構定義,或您本機電腦上的 JSON 結構定義檔路徑。

    在指令列中指定結構定義時,無法加入 RECORD (STRUCT) 類型和資料欄說明,也不能指定資料欄模式。所有模式均會使用預設設定 NULLABLE。如要加入說明、模式和 RECORD 類型,請改為提供 JSON 結構定義檔

    範例:

    輸入以下指令,使用內嵌結構定義建立資料表。這個指令會在預設專案的 mydataset 中建立名為 mytable 的資料表。資料表的到期時間設為 3600 秒 (一小時)、說明設為 This is my table,標籤則設為 organization:development。此指令使用 -t 捷徑,而非 --table。結構定義以內嵌方式指定為:qtr:STRING,sales:FLOAT,year:STRING

    bq mk \
     -t \
     --expiration 3600 \
     --description "This is my table" \
     --label organization:development \
     mydataset.mytable \
     qtr:STRING,sales:FLOAT,year:STRING

    輸入下列指令,使用 JSON 結構定義檔建立資料表。這個指令會在預設專案的 mydataset 中建立名為 mytable 的資料表。資料表的到期時間設為 3600 秒 (一小時)、說明設為 This is my table,標籤則設為 organization:development。結構定義檔的路徑為 /tmp/myschema.json

    bq mk \
     --table \
     --expiration 3600 \
     --description "This is my table" \
     --label organization:development \
     mydataset.mytable \
     /tmp/myschema.json

    輸入下列指令,使用 JSON 結構定義檔建立資料表。這個指令會在 myotherprojectmydataset 中建立名為 mytable 的資料表。資料表的到期時間設為 3600 秒 (一小時)、說明設為 This is my table,標籤則設為 organization:development。結構定義檔的路徑為 /tmp/myschema.json

    bq mk \
     --table \
     --expiration 3600 \
     --description "This is my table" \
     --label organization:development \
     myotherproject:mydataset.mytable \
     /tmp/myschema.json

    您可以在建立資料表後,更新資料表的到期時間、說明和標籤。您也可以修改結構定義

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

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

}

建立資料表並授予存取權

下列範例會建立名為 mytable 的資料表,然後使用 google_bigquery_table_iam_policy 資源授予存取權。只有在您想將資料表存取權授予不具資料表所在資料集存取權的主體時,才需要執行這個步驟。

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

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

}

data "google_iam_policy" "default" {
  binding {
    role = "roles/bigquery.dataOwner"
    members = [
      "user:raha@altostrat.com",
    ]
  }
}

resource "google_bigquery_table_iam_policy" "policy" {
  dataset_id  = google_bigquery_table.default.dataset_id
  table_id    = google_bigquery_table.default.table_id
  policy_data = data.google_iam_policy.default.policy_data
}

使用客戶管理的加密金鑰建立資料表

以下範例會建立名為 mytable 的資料表,並使用 google_kms_crypto_keygoogle_kms_key_ring 資源,為資料表指定 Cloud Key Management Service 金鑰。您必須先啟用 Cloud Key Management Service API,才能執行這個範例。

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

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

  encryption_configuration {
    kms_key_name = google_kms_crypto_key.crypto_key.id
  }

  depends_on = [google_project_iam_member.service_account_access]
}

resource "google_kms_crypto_key" "crypto_key" {
  name     = "example-key"
  key_ring = google_kms_key_ring.key_ring.id
}

resource "random_id" "default" {
  byte_length = 8
}

resource "google_kms_key_ring" "key_ring" {
  name     = "${random_id.default.hex}-example-keyring"
  location = "us"
}

# Enable the BigQuery service account to encrypt/decrypt Cloud KMS keys
data "google_project" "project" {
}

resource "google_project_iam_member" "service_account_access" {
  project = data.google_project.project.project_id
  role    = "roles/cloudkms.cryptoKeyEncrypterDecrypter"
  member  = "serviceAccount:bq-${data.google_project.project.number}@bigquery-encryption.iam.gserviceaccount.com"
}

如要在 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

使用已定義的資料表資源呼叫 tables.insert 方法。

C#

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

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


using Google.Cloud.BigQuery.V2;

public class BigQueryCreateTable
{
    public BigQueryTable CreateTable(
        string projectId = "your-project-id",
        string datasetId = "your_dataset_id"
    )
    {
        BigQueryClient client = BigQueryClient.Create(projectId);
        var dataset = client.GetDataset(datasetId);
        // Create schema for new table.
        var schema = new TableSchemaBuilder
        {
            { "full_name", BigQueryDbType.String },
            { "age", BigQueryDbType.Int64 }
        }.Build();
        // Create the table
        return dataset.CreateTable(tableId: "your_table_id", schema: schema);
    }
}

Go

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

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

import (
	"context"
	"fmt"
	"time"

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

// createTableExplicitSchema demonstrates creating a new BigQuery table and specifying a schema.
func createTableExplicitSchema(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: "full_name", Type: bigquery.StringFieldType},
		{Name: "age", Type: bigquery.IntegerFieldType},
	}

	metaData := &bigquery.TableMetadata{
		Schema:         sampleSchema,
		ExpirationTime: time.Now().AddDate(1, 0, 0), // Table will be automatically deleted in 1 year.
	}
	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.TableDefinition;
import com.google.cloud.bigquery.TableId;
import com.google.cloud.bigquery.TableInfo;

public class CreateTable {

  public static void runCreateTable() {
    // 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("stringField", StandardSQLTypeName.STRING),
            Field.of("booleanField", StandardSQLTypeName.BOOL));
    createTable(datasetName, tableName, schema);
  }

  public static void createTable(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);
      TableDefinition tableDefinition = StandardTableDefinition.of(schema);
      TableInfo tableInfo = TableInfo.newBuilder(tableId, tableDefinition).build();

      bigquery.create(tableInfo);
      System.out.println("Table created successfully");
    } catch (BigQueryException e) {
      System.out.println("Table was not created. \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 createTable() {
  // Creates a new 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, Age:integer, Weight:float, IsMagic:boolean';

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

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

  console.log(`Table ${table.id} created.`);
}

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';
// $fields = [
//    [
//        'name' => 'field1',
//        'type' => 'string',
//        'mode' => 'required'
//    ],
//    [
//        'name' => 'field2',
//        'type' => 'integer'
//    ],
//];

$bigQuery = new BigQueryClient([
    'projectId' => $projectId,
]);
$dataset = $bigQuery->dataset($datasetId);
$schema = ['fields' => $fields];
$table = $dataset->createTable($tableId, ['schema' => $schema]);
printf('Created table %s' . PHP_EOL, $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 create.
# table_id = "your-project.your_dataset.your_table_name"

schema = [
    bigquery.SchemaField("full_name", "STRING", mode="REQUIRED"),
    bigquery.SchemaField("age", "INTEGER", mode="REQUIRED"),
]

table = bigquery.Table(table_id, schema=schema)
table = client.create_table(table)  # Make an API request.
print(
    "Created table {}.{}.{}".format(table.project, table.dataset_id, table.table_id)
)

Ruby

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

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

require "google/cloud/bigquery"

def create_table dataset_id = "my_dataset"
  bigquery = Google::Cloud::Bigquery.new
  dataset  = bigquery.dataset dataset_id
  table_id = "my_table"

  table = dataset.create_table table_id do |updater|
    updater.string  "full_name", mode: :required
    updater.integer "age",       mode: :required
  end

  puts "Created table: #{table_id}"
end

不使用結構定義建立空白資料表

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

// Sample to create a table without schema
public class CreateTableWithoutSchema {

  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";
    createTableWithoutSchema(datasetName, tableName);
  }

  public static void createTableWithoutSchema(String datasetName, String tableName) {
    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);
      TableDefinition tableDefinition = StandardTableDefinition.of(Schema.of());
      TableInfo tableInfo = TableInfo.newBuilder(tableId, tableDefinition).build();

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

從查詢結果建立資料表

如要從查詢結果建立資料表,請將結果寫入目標資料表。

主控台

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

    前往「BigQuery」頁面

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

  3. 輸入有效的 SQL 查詢。

  4. 按一下「More」,然後選取「Query settings」

    查詢設定

  5. 選取「Set a destination table for query results」(為查詢結果設定目標資料表) 選項。

    設定目的地

  6. 在「Destination」(目的地) 部分,選取要建立資料表的「Dataset」(資料集),然後選擇「Table ID」(資料表 ID)

  7. 在「Destination table write preference」(目標資料表寫入偏好設定) 區段,選擇下列其中一項:

    • [Write if empty] (空白時寫入):僅在資料表空白時將查詢結果寫入資料表。
    • [Append to table] (附加到資料表中):將查詢結果附加到現有的資料表。
    • [Overwrite table] (覆寫資料表):使用查詢結果覆寫名稱相同的現有資料表。
  8. 選用:在「Data location」(資料位置),選擇您的位置

  9. 如要更新查詢設定,請按一下「儲存」

  10. 按一下「執行」。這會建立一個查詢工作,將查詢結果寫入您指定的資料表。

如果您在執行查詢前忘記指定目標資料表,也可以按一下編輯器上方的 「儲存結果」按鈕,將快取結果資料表複製至永久性資料表。

SQL

以下範例使用 CREATE TABLE 陳述式,根據公開 bikeshare_trips 資料表中的資料建立 trips 資料表:

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

    前往 BigQuery

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

    CREATE TABLE mydataset.trips AS (
      SELECT
        bike_id,
        start_time,
        duration_minutes
      FROM
        bigquery-public-data.austin_bikeshare.bikeshare_trips
    );

  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 旗標,根據查詢結果建立永久性資料表。指定 use_legacy_sql=false 旗標以使用 GoogleSQL 語法。如要將查詢結果寫入不在預設專案內的資料表,請使用下列格式將專案 ID 新增至資料集名稱:project_id:dataset

    選用:提供 --location 旗標,並將值設為您的位置

    如要控管現有目標資料表的寫入配置,請指定下列其中一種選用標記:

    • --append_table:如果目標資料表已存在,查詢結果會附加至該資料表。
    • --replace:如果目標資料表已存在,查詢結果會覆寫該資料表。

      bq --location=location query \
      --destination_table project_id:dataset.table \
      --use_legacy_sql=false 'query'

      更改下列內容:

    • location 是用於處理查詢的位置名稱。--location 是選用旗標。舉例來說,如果您在東京地區使用 BigQuery,就可以將該旗標的值設為 asia-northeast1。您可以使用 .bigqueryrc 檔案設定位置的預設值。

    • project_id 是您的專案 ID。

    • dataset 是您要寫入查詢結果的資料表所屬資料集的名稱。

    • table 是您要寫入查詢結果的資料表名稱。

    • query 是採用 GoogleSQL 語法的查詢。

      如未指定任何寫入配置旗標,預設動作是僅在資料表空白時,才將結果寫入資料表。如果資料表存在且非空白,系統會傳回下列錯誤:BigQuery error in query operation: Error processing job project_id:bqjob_123abc456789_00000e1234f_1: Already Exists: Table project_id:dataset.table

      範例:

      輸入下列指令,將查詢結果寫入 mydataset 中名為 mytable 的目標資料表。該資料集位於預設專案中。由於您未在指令中指定任何寫入配置旗標,因此資料表必須為新資料表或空白資料表。否則,系統會傳回 Already exists 錯誤。查詢會從美國名稱資料公開資料集擷取資料。

      bq query \
      --destination_table mydataset.mytable \
      --use_legacy_sql=false \
      'SELECT
      name,
      number
      FROM
      `bigquery-public-data`.usa_names.usa_1910_current
      WHERE
      gender = "M"
      ORDER BY
      number DESC'

      輸入下列指令,使用查詢結果覆寫 mydataset 中名為 mytable 的目標資料表。該資料集位於預設專案中。該指令使用 --replace 旗標來覆寫目標資料表。

      bq query \
      --destination_table mydataset.mytable \
      --replace \
      --use_legacy_sql=false \
      'SELECT
      name,
      number
      FROM
      `bigquery-public-data`.usa_names.usa_1910_current
      WHERE
      gender = "M"
      ORDER BY
      number DESC'

      輸入下列指令,將查詢結果附加至 mydataset 中名為 mytable 的目標資料表。該資料集位於 my-other-project,而非預設專案。指令使用 --append_table 旗標將查詢結果附加至目標資料表。

      bq query \
      --append_table \
      --use_legacy_sql=false \
      --destination_table my-other-project:mydataset.mytable \
      'SELECT
      name,
      number
      FROM
      `bigquery-public-data`.usa_names.usa_1910_current
      WHERE
      gender = "M"
      ORDER BY
      number DESC'

      各範例的輸出內容如下。為了方便閱讀,以下僅顯示部分輸出內容。

      Waiting on bqjob_r123abc456_000001234567_1 ... (2s) Current status: DONE
      +---------+--------+
      |  name   | number |
      +---------+--------+
      | Robert  |  10021 |
      | John    |   9636 |
      | Robert  |   9297 |
      | ...              |
      +---------+--------+
      

API

如要將查詢結果儲存至永久資料表,請呼叫 jobs.insert 方法,設定 query 工作,然後加入 destinationTable 屬性的值。如要控管現有目標資料表的寫入配置,請設定 writeDisposition 屬性。

如要控管查詢工作的處理位置,請在工作資源jobReference 區段中指定 location 屬性。

Go

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

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

import (
	"context"
	"fmt"
	"io"

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

// queryWithDestination demonstrates saving the results of a query to a specific table by setting the destination
// via the API properties.
func queryWithDestination(w io.Writer, projectID, destDatasetID, destTableID 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()

	q := client.Query("SELECT 17 as my_col")
	q.Location = "US" // Location must match the dataset(s) referenced in query.
	q.QueryConfig.Dst = client.Dataset(destDatasetID).Table(destTableID)
	// Run the query and print results when the query job is completed.
	job, err := q.Run(ctx)
	if err != nil {
		return err
	}
	status, err := job.Wait(ctx)
	if err != nil {
		return err
	}
	if err := status.Err(); err != nil {
		return err
	}
	it, err := job.Read(ctx)
	for {
		var row []bigquery.Value
		err := it.Next(&row)
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		fmt.Fprintln(w, row)
	}
	return nil
}

Java

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

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

如要將查詢結果儲存至永久資料表,請在 QueryJobConfiguration 中將目標資料表設為所要的 TableId

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

public class SaveQueryToTable {

  public static void runSaveQueryToTable() {
    // TODO(developer): Replace these variables before running the sample.
    String query = "SELECT corpus FROM `bigquery-public-data.samples.shakespeare` GROUP BY corpus;";
    String destinationTable = "MY_TABLE";
    String destinationDataset = "MY_DATASET";

    saveQueryToTable(destinationDataset, destinationTable, query);
  }

  public static void saveQueryToTable(
      String destinationDataset, String destinationTableId, 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();

      // Identify the destination table
      TableId destinationTable = TableId.of(destinationDataset, destinationTableId);

      // Build the query job
      QueryJobConfiguration queryConfig =
          QueryJobConfiguration.newBuilder(query).setDestinationTable(destinationTable).build();

      // Execute the query.
      bigquery.query(queryConfig);

      // The results are now saved in the destination table.

      System.out.println("Saved query ran successfully");
    } catch (BigQueryException | InterruptedException e) {
      System.out.println("Saved query did not run \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 queryDestinationTable() {
  // Queries the U.S. given names dataset for the state of Texas
  // and saves results to permanent table.

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

  // Create destination table reference
  const dataset = bigquery.dataset(datasetId);
  const destinationTable = dataset.table(tableId);

  const query = `SELECT name
    FROM \`bigquery-public-data.usa_names.usa_1910_2013\`
    WHERE state = 'TX'
    LIMIT 100`;

  // For all options, see https://cloud.google.com/bigquery/docs/reference/v2/tables#resource
  const options = {
    query: query,
    // Location must match that of the dataset(s) referenced in the query.
    location: 'US',
    destination: destinationTable,
  };

  // Run the query as a job
  const [job] = await bigquery.createQueryJob(options);

  console.log(`Job ${job.id} started.`);
  console.log(`Query results loaded to table ${destinationTable.id}`);
}

Python

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

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

如要將查詢結果儲存至永久性資料表,請建立 QueryJobConfig,並將目的地設為所需的 TableReference。將工作設定傳送至查詢方法
from google.cloud import bigquery

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

# TODO(developer): Set table_id to the ID of the destination table.
# table_id = "your-project.your_dataset.your_table_name"

job_config = bigquery.QueryJobConfig(destination=table_id)

sql = """
    SELECT corpus
    FROM `bigquery-public-data.samples.shakespeare`
    GROUP BY corpus;
"""

# Start the query, passing in the extra configuration.
query_job = client.query(sql, job_config=job_config)  # Make an API request.
query_job.result()  # Wait for the job to complete.

print("Query results loaded to the table {}".format(table_id))

建立參照外部資料來源的資料表

「外部資料來源」是指可以直接透過 BigQuery 查詢的資料來源,即使資料未儲存在 BigQuery 儲存空間中也一樣。例如,您可能有資料在其他 Google Cloud 資料庫、Cloud Storage 的檔案或其他雲端產品中,而且想在不遷移資料的狀況下,在 BigQuery 中進行分析。

詳情請參閱外部資料來源簡介

在載入資料時建立資料表

將資料載入 BigQuery 時,您可將資料載入新的資料表或分區、將資料附加至現有的資料表或分區,或是覆寫資料表或分區。您不必在載入資料前先建立空白的資料表,因為系統可讓您在建立新資料表時一併載入資料。

將資料載入 BigQuery 時,您可以提供資料表或分區結構定義,或是將結構定義自動偵測用於支援此功能的資料格式。

有關如何載入資料的詳情,請參閱將資料載入 BigQuery 的簡介

控管資料表的存取權

如要設定資料表和檢視表的存取權,您可以在下列層級為實體授予 IAM 角色,這些層級依允許的資源範圍排序 (從大到小):

  • Google Cloud 資源階層中的高層級,例如專案、資料夾或機構層級
  • 資料集層級
  • 資料表或檢視畫面層級

您也可以使用下列方法,限制資料表內的資料存取權:

任何受 IAM 保護的資源存取權都是疊加的。舉例來說,如果實體沒有專案等高層級的存取權,您可以授予實體資料集層級的存取權,這樣實體就能存取資料集中的資料表和檢視畫面。同樣地,如果實體沒有高層級或資料集層級的存取權,您可以在資料表或檢視表層級授予實體存取權。

Google Cloud資源階層中的較高層級 (例如專案、資料夾或機構層級) 授予 IAM 角色,可讓實體存取更多資源。舉例來說,在專案層級將特定角色授予實體,可讓該實體擁有適用於專案中所有資料集的權限。

在資料集層級授予角色,即可讓實體對特定資料集裡的資料表和檢視表執行指定作業,即使實體沒有較高層級的存取權也是如此。如要進一步瞭解如何設定資料集層級的存取權控管設定,請參閱「控管資料集存取權」一文。

在資料表或檢視表層級授予角色,即可讓實體對特定資料表和檢視表執行指定作業,即使實體沒有較高層級的存取權也是如此。如要瞭解如何設定資料表層級存取權控管設定,請參閱「控管資料表和檢視表存取權」一文。

您也可以建立 IAM 自訂角色。建立自訂角色之後,您就能依據要讓實體執行的特定作業授予權限。

您無法對任何由 IAM 保護的資源設定「拒絕」權限。

如要進一步瞭解角色和權限,請參閱 IAM 說明文件中的「瞭解角色」一節,以及 BigQuery 的「IAM 角色和權限」一文。

取得資料表相關資訊

您可以透過下列方式取得資料表的相關資訊或中繼資料:

所需權限

您至少要具備 bigquery.tables.get 權限,才能取得資料表相關資訊。以下是具有 bigquery.tables.get 權限的預先定義 IAM 角色:

  • bigquery.metadataViewer
  • bigquery.dataViewer
  • bigquery.dataOwner
  • bigquery.dataEditor
  • bigquery.admin

此外,當具備 bigquery.datasets.create 權限的使用者建立資料集時,會獲得該資料集的 bigquery.dataOwner 存取權。bigquery.dataOwner 存取權可讓使用者擷取資料表的中繼資料。

如要進一步瞭解 BigQuery 中的身分與存取權管理角色和權限,請參閱「存取權控管」一文。

取得資料表資訊

如何取得資料表的相關資訊:

主控台

  1. 在導覽面板的「Resources」(資源) 區段,展開您的專案,然後選取資料集。

  2. 按一下資料集名稱來展開資料集,資料集中的資料表和檢視表會隨即顯示。

  3. 按一下資料表名稱。

  4. 在「Details」面板中,按一下「Details」,即可顯示資料表的說明和相關資訊。

  5. 您也可以切換至「結構定義」分頁標籤,查看資料表的結構定義。

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 show 指令,即可顯示所有資料表資訊。使用 --schema 旗標可以只顯示資料表結構定義資訊。--format 旗標可用來控制輸出內容。

    如果您要取得非預設專案中之資料表的相關資訊,請使用下列格式將專案 ID 新增至資料集:project_id:dataset

    bq show \
    --schema \
    --format=prettyjson \
    project_id:dataset.table

    其中:

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

    範例:

    輸入下列指令,顯示 mydatasetmytable 的所有相關資訊。mydataset 在您的預設專案中。

    bq show --format=prettyjson mydataset.mytable

    輸入下列指令,顯示 mydatasetmytable 的所有相關資訊。mydatasetmyotherproject 中,而不是在您的預設專案中。

    bq show --format=prettyjson myotherproject:mydataset.mytable

    輸入下列指令,系統即會單獨顯示 mydatasetmytable 的結構定義資訊。mydatasetmyotherproject 中,而不是在您的預設專案中。

    bq show --schema --format=prettyjson myotherproject:mydataset.mytable

API

呼叫 tables.get 方法,並提供所有相關參數。

Go

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

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

import (
	"context"
	"fmt"
	"io"

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

// printTableInfo demonstrates fetching metadata from a table and printing some basic information
// to an io.Writer.
func printTableInfo(w io.Writer, 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()

	meta, err := client.Dataset(datasetID).Table(tableID).Metadata(ctx)
	if err != nil {
		return err
	}
	// Print basic information about the table.
	fmt.Fprintf(w, "Schema has %d top-level fields\n", len(meta.Schema))
	fmt.Fprintf(w, "Description: %s\n", meta.Description)
	fmt.Fprintf(w, "Rows in managed storage: %d\n", meta.NumRows)
	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.Table;
import com.google.cloud.bigquery.TableId;

public class GetTable {

  public static void runGetTable() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "bigquery_public_data";
    String datasetName = "samples";
    String tableName = "shakespeare";
    getTable(projectId, datasetName, tableName);
  }

  public static void getTable(String projectId, String datasetName, String tableName) {
    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(projectId, datasetName, tableName);
      Table table = bigquery.getTable(tableId);
      System.out.println("Table info: " + table.getDescription());
    } catch (BigQueryException e) {
      System.out.println("Table not retrieved. \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 getTable() {
  // Retrieves 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";

  // Retrieve table reference
  const dataset = bigquery.dataset(datasetId);
  const [table] = await dataset.table(tableId).get();

  console.log('Table:');
  console.log(table.metadata.tableReference);
}
getTable();

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);

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 model to fetch.
# table_id = 'your-project.your_dataset.your_table'

table = client.get_table(table_id)  # Make an API request.

# View table properties
print(
    "Got table '{}.{}.{}'.".format(table.project, table.dataset_id, table.table_id)
)
print("Table schema: {}".format(table.schema))
print("Table description: {}".format(table.description))
print("Table has {} rows".format(table.num_rows))

使用 INFORMATION_SCHEMA 取得資料表資訊

INFORMATION_SCHEMA 是一系列的檢視表,可提供資料集、處理常式、資料表、檢視表、工作、保留項目和串流資料的中繼資料存取權。

您可以查詢下列檢視,取得資料表資訊:

  • 使用 INFORMATION_SCHEMA.TABLESINFORMATION_SCHEMA.TABLE_OPTIONS 檢視表,擷取專案中資料表和檢視表的中繼資料。
  • 使用 INFORMATION_SCHEMA.COLUMNSINFORMATION_SCHEMA.COLUMN_FIELD_PATHS 檢視表,擷取資料表中資料欄 (欄位) 的相關中繼資料。
  • 使用 INFORMATION_SCHEMA.TABLE_STORAGE 檢視畫面,擷取表格目前和歷來儲存空間用量的中繼資料。

TABLESTABLE_OPTIONS 檢視表也包含檢視表的相關高階資訊。如需詳細資訊,請改為查詢 INFORMATION_SCHEMA.VIEWS 檢視表。

TABLES 個檢視表

查詢 INFORMATION_SCHEMA.TABLES 檢視表時,資料集中的每個資料表或檢視表都會有一列相對應的查詢結果。如需檢視項目的詳細資訊,請改為查詢 INFORMATION_SCHEMA.VIEWS 檢視項目

INFORMATION_SCHEMA.TABLES 檢視表具有下列結構定義:

資料欄名稱 資料類型
table_catalog STRING 包含資料集的專案 ID。
table_schema STRING 包含資料表或檢視畫面的資料集名稱。也稱為 datasetId
table_name STRING 資料表或檢視表的名稱。也稱為 tableId
table_type STRING 資料表類型,可能是下列其中一個值:
is_insertable_into STRING YESNO,視資料表是否支援 DML INSERT 陳述式而定
is_typed STRING 此值一律為 NO
is_change_history_enabled STRING YESNO,視是否啟用變更記錄而定
creation_time TIMESTAMP 資料表的建立時間
base_table_catalog STRING 對於資料表本機副本資料表快照,則為基本資料表的專案。僅適用於 table_type 設為 CLONESNAPSHOT 的資料表。
base_table_schema STRING 對於資料表複本資料表快照,則是基礎資料表的資料集。僅適用於 table_type 設為 CLONESNAPSHOT 的資料表。
base_table_name STRING 對於資料表複本資料表快照,則是基礎資料表的名稱。僅適用於 table_type 設為 CLONESNAPSHOT 的資料表。
snapshot_time_ms TIMESTAMP 對於資料表本機副本資料表快照,則是指在基本資料表上執行本機副本快照作業以建立此資料表的時間。如果使用時間旅行,這個欄位就會包含時間旅行時間戳記。否則,snapshot_time_ms 欄位與 creation_time 欄位相同。僅適用於 table_type 設為 CLONESNAPSHOT 的資料表。
replica_source_catalog STRING 對於具體化檢視表備用資源,則為基礎具體化檢視表的專案。
replica_source_schema STRING 對於物化檢視表備用資源,則為基礎物化檢視表的資料集。
replica_source_name STRING 對於具體化檢視表備用資源,則為基礎具體化檢視表的名稱。
replication_status STRING 對於具體化檢視表備用資源,從基本具體化檢視表到具體化檢視表備用資源的複製狀態;以下任一項:
  • REPLICATION_STATUS_UNSPECIFIED
  • ACTIVE:複製功能已啟用,且沒有錯誤
  • SOURCE_DELETED:已刪除來源具體化檢視表
  • PERMISSION_DENIED:在包含用於建立具體化檢視表的查詢中使用的來源 Amazon S3 BigLake 資料表的資料集中,來源具體化檢視表尚未經過授權
  • UNSUPPORTED_CONFIGURATION:除了來源 materialized view 授權外,備份資源的必要條件也出現問題。
replication_error STRING 如果 replication_status 指出已實體化的檢視區塊副本有複寫問題,replication_error 會提供問題的詳細資訊。
ddl STRING 可用來重新建立資料表的 DDL 陳述式,例如 CREATE TABLECREATE VIEW
default_collation_name STRING 預設排序規格的名稱 (如果有的話);否則為 NULL
upsert_stream_apply_watermark TIMESTAMP 如果是使用變更資料擷取 (CDC) 的資料表,則為上次套用資料列修改時間。詳情請參閱「監控資料表上傳/插入作業進度」。

範例

範例 1:

以下範例會擷取名為 mydataset 的資料集中所有資料表的資料表中繼資料。系統傳回的是預設專案 mydatasetmydataset 內所有類型的資料表中繼資料。

mydataset 包含下列資料表:

  • mytable1:標準的 BigQuery 資料表
  • myview1:BigQuery 檢視表

如要對預設專案以外的專案執行查詢,請使用以下格式將專案 ID 新增至資料集:`project_id`.dataset.INFORMATION_SCHEMA.view;例如 `myproject`.mydataset.INFORMATION_SCHEMA.TABLES

SELECT
  table_catalog, table_schema, table_name, table_type,
  is_insertable_into, creation_time, ddl
FROM
  mydataset.INFORMATION_SCHEMA.TABLES;

結果類似下列內容。為了方便閱讀,我們已從結果中排除部分資料欄。

+----------------+---------------+----------------+------------+--------------------+---------------------+---------------------------------------------+
| table_catalog  | table_schema  |   table_name   | table_type | is_insertable_into |    creation_time    |                     ddl                     |
+----------------+---------------+----------------+------------+--------------------+---------------------+---------------------------------------------+
| myproject      | mydataset     | mytable1       | BASE TABLE | YES                | 2018-10-29 20:34:44 | CREATE TABLE `myproject.mydataset.mytable1` |
|                |               |                |            |                    |                     | (                                           |
|                |               |                |            |                    |                     |   id INT64                                  |
|                |               |                |            |                    |                     | );                                          |
| myproject      | mydataset     | myview1        | VIEW       | NO                 | 2018-12-29 00:19:20 | CREATE VIEW `myproject.mydataset.myview1`   |
|                |               |                |            |                    |                     | AS SELECT 100 as id;                        |
+----------------+---------------+----------------+------------+--------------------+---------------------+---------------------------------------------+
範例 2:

以下範例會從 INFORMATION_SCHEMA.TABLES 檢視表擷取 CLONESNAPSHOT 類型的所有資料表中繼資料。系統傳回的是預設專案 mydataset 內的所有資料表中繼資料。

如要對預設專案以外的專案執行查詢,請使用以下格式將專案 ID 新增至資料集:`project_id`.dataset.INFORMATION_SCHEMA.view;例如 `myproject`.mydataset.INFORMATION_SCHEMA.TABLES

  SELECT
    table_name, table_type, base_table_catalog,
    base_table_schema, base_table_name, snapshot_time_ms
  FROM
    mydataset.INFORMATION_SCHEMA.TABLES
  WHERE
    table_type = 'CLONE'
  OR
    table_type = 'SNAPSHOT';

結果類似下列內容。為了方便閱讀,我們已從結果中排除部分資料欄。

  +--------------+------------+--------------------+-------------------+-----------------+---------------------+
  | table_name   | table_type | base_table_catalog | base_table_schema | base_table_name | snapshot_time_ms    |
  +--------------+------------+--------------------+-------------------+-----------------+---------------------+
  | items_clone  | CLONE      | myproject          | mydataset         | items           | 2018-10-31 22:40:05 |
  | orders_bk    | SNAPSHOT   | myproject          | mydataset         | orders          | 2018-11-01 08:22:39 |
  +--------------+------------+--------------------+-------------------+-----------------+---------------------+

範例 3:

以下範例會從 census_bureau_usa 資料集中的 population_by_zip_2010 資料表,擷取 INFORMATION_SCHEMA.TABLES 檢視表的 table_nameddl 欄。這個資料集是 BigQuery 公開資料集方案的一部分。

由於您要查詢的資料表位於另一個專案中,因此您應使用下列格式將專案 ID 新增至資料集:`project_id`.dataset.INFORMATION_SCHEMA.view。在這個範例中,這個值為 `bigquery-public-data`.census_bureau_usa.INFORMATION_SCHEMA.TABLES

SELECT
  table_name, ddl
FROM
  `bigquery-public-data`.census_bureau_usa.INFORMATION_SCHEMA.TABLES
WHERE
  table_name = 'population_by_zip_2010';

結果大致如下:

+------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|       table_name       |                                                                                                            ddl                                                                                                             |
+------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| population_by_zip_2010 | CREATE TABLE `bigquery-public-data.census_bureau_usa.population_by_zip_2010`                                                                                                                                               |
|                        | (                                                                                                                                                                                                                          |
|                        |   geo_id STRING OPTIONS(description="Geo code"),                                                                                                                                                                           |
|                        |   zipcode STRING NOT NULL OPTIONS(description="Five digit ZIP Code Tabulation Area Census Code"),                                                                                                                          |
|                        |   population INT64 OPTIONS(description="The total count of the population for this segment."),                                                                                                                             |
|                        |   minimum_age INT64 OPTIONS(description="The minimum age in the age range. If null, this indicates the row as a total for male, female, or overall population."),                                                          |
|                        |   maximum_age INT64 OPTIONS(description="The maximum age in the age range. If null, this indicates the row as having no maximum (such as 85 and over) or the row is a total of the male, female, or overall population."), |
|                        |   gender STRING OPTIONS(description="male or female. If empty, the row is a total population summary.")                                                                                                                    |
|                        | )                                                                                                                                                                                                                          |
|                        | OPTIONS(                                                                                                                                                                                                                   |
|                        |   labels=[("freebqcovid", "")]                                                                                                                                                                                             |
|                        | );                                                                                                                                                                                                                         |
+------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  

TABLE_OPTIONS 個檢視表

查詢 INFORMATION_SCHEMA.TABLE_OPTIONS 檢視表時,查詢結果會針對資料集中的每個資料表或檢視表,為每個選項分別列出一個資料列。如需檢視項目的詳細資訊,請改為查詢 INFORMATION_SCHEMA.VIEWS 檢視項目

INFORMATION_SCHEMA.TABLE_OPTIONS 檢視表具有下列結構定義:

資料欄名稱 資料類型
TABLE_CATALOG STRING 包含資料集的專案 ID
TABLE_SCHEMA STRING 資料表或檢視表所屬資料集的名稱 (又稱為 datasetId)
TABLE_NAME STRING 資料表或檢視表的名稱 (又稱為 tableId)
OPTION_NAME STRING 選項表格中的其中一個名稱值
OPTION_TYPE STRING 選項表格中的其中一個資料類型值
OPTION_VALUE STRING 選項表格中的其中一個值選項
選項表格

OPTION_NAME

OPTION_TYPE

OPTION_VALUE

description

STRING

資料表的說明

enable_refresh

BOOL

是否為具體化檢視表啟用自動重新整理功能

expiration_timestamp

TIMESTAMP

這個資料表的到期時間

friendly_name

STRING

資料表的描述性名稱

kms_key_name

STRING

用來加密資料表的 Cloud KMS 金鑰名稱

labels

ARRAY<STRUCT<STRING, STRING>>

代表資料表標籤的 STRUCT 陣列

partition_expiration_days

FLOAT64

分區資料表中所有分區的預設生命週期 (以天為單位)

refresh_interval_minutes

FLOAT64

重新整理具體化檢視表的頻率

require_partition_filter

BOOL

查詢資料表時是否需要分區篩選器

tags

ARRAY<STRUCT<STRING, STRING>>

在命名空間限定的 <key, value> 語法中,附加至資料表的標記。詳情請參閱「標記和條件式存取」。

針對外部資料表,您可以使用下列選項:

選項
allow_jagged_rows

BOOL

如果為 true,則可接受缺少結尾自選欄的資料列。

適用於 CSV 資料。

allow_quoted_newlines

BOOL

如果是 true,則允許在檔案中使用包含換行符號字元的引用資料區段。

適用於 CSV 資料。

bigtable_options

STRING

僅適用於建立 Bigtable 外部資料表。

以 JSON 格式指定 Bigtable 外部資料表的結構定義。

如需 Bigtable 資料表定義選項清單,請參閱 REST API 參考資料中的 BigtableOptions

column_name_character_map

STRING

定義支援的資料欄名稱字元範圍,以及如何處理不支援的字元。預設設定為 STRICT,表示不支援的字元會導致 BigQuery 擲回錯誤。V1V2 會將任何不支援的字元替換為底線。

支援的值包括:

compression

STRING

資料來源的壓縮類型。支援的值包括:GZIP。如果未指定,資料來源會經過解壓縮。

適用於 CSV 和 JSON 資料。

decimal_target_types

ARRAY<STRING>

決定轉換 Decimal 類型的方式。等同於 ExternalDataConfiguration.decimal_target_types

範例:["NUMERIC", "BIGNUMERIC"]

description

STRING

這個資料表的說明。

enable_list_inference

BOOL

如果是 true,請專門針對 Parquet LIST 邏輯型別使用結構定義推論。

適用於 Parquet 資料。

enable_logical_types

BOOL

如果為 true,則將 Avro 邏輯類型轉換為對應的 SQL 類型。詳情請參閱「 邏輯類型」。

適用於 Avro 資料。

encoding

STRING

資料的字元編碼。支援的值包括:UTF8 (或 UTF-8)、ISO_8859_1 (或 ISO-8859-1)。

適用於 CSV 資料。

enum_as_string

BOOL

如果為 true,則預設會將 Parquet ENUM 邏輯類型推斷為 STRING,而非 BYTES。

適用於 Parquet 資料。

expiration_timestamp

TIMESTAMP

這個資料表的到期時間。如未指定,資料表就不會過期。

範例:"2025-01-01 00:00:00 UTC"

field_delimiter

STRING

CSV 檔案中的欄位分隔符。

適用於 CSV 資料。

format

STRING

外部資料的格式。 CREATE EXTERNAL TABLE 支援的值包括:AVROCLOUD_BIGTABLECSVDATASTORE_BACKUPDELTA_LAKE (預覽)、GOOGLE_SHEETSNEWLINE_DELIMITED_JSON (或 JSON)、ORCPARQUET

LOAD DATA 支援的值包括:AVROCSVDELTA_LAKE (預覽)、NEWLINE_DELIMITED_JSON (或 JSON)、ORCPARQUET

JSON 相當於 NEWLINE_DELIMITED_JSON

hive_partition_uri_prefix

STRING

分區索引鍵編碼開始前,所有來源 URI 的通用前置字串。僅適用於以 Hive 分區的外部資料表。

適用於 Avro、CSV、JSON、Parquet 和 ORC 資料。

範例:"gs://bucket/path"

file_set_spec_type

STRING

指定如何解讀載入工作和外部資料表的來源 URI。

支援的值包括:

  • FILE_SYSTEM_MATCH:透過列出物件儲存庫中的檔案,展開來源 URI。這是未設定 FileSetSpecType 時的預設行為。
  • NEW_LINE_DELIMITED_MANIFEST:表示所提供的 URI 是使用換行符號分隔的資訊清單檔案,每行一個 URI。資訊清單檔案不支援萬用字元 URI,且所有參照的資料檔案都必須與資訊清單檔案位於相同的值區。

舉例來說,如果來源 URI 為 "gs://bucket/path/file",而 file_set_spec_typeFILE_SYSTEM_MATCH,則該檔案會直接用作資料檔案。如果 file_set_spec_typeNEW_LINE_DELIMITED_MANIFEST,檔案中的每一行都會解讀為指向資料檔案的 URI。

ignore_unknown_values

BOOL

如果為 true,系統會忽略不在資料表結構定義中的其他值,但不會傳回錯誤。

適用於 CSV 和 JSON 資料。

json_extension

STRING

針對 JSON 資料,表示特定的 JSON 交換格式。如果未指定,BigQuery 會將資料讀取為一般 JSON 記錄。

支援的值包括:
GEOJSON。以換行符號分隔的 GeoJSON 資料。詳情請參閱「從以換行符號分隔的 GeoJSON 檔案建立外部資料表」。

max_bad_records

INT64

讀取資料時可忽略的錯誤記錄數量上限。

適用於:CSV、JSON 和 Google 試算表資料。

max_staleness

INTERVAL

適用於 BigLake 資料表物件資料表

指定作業是否會使用針對資料表的快取中繼資料,以及作業必須使用多新鮮的快取中繼資料。

如要停用中繼資料快取功能,請指定 0。這是目前的預設做法。

如要啟用中繼資料快取功能,請指定介於 30 分鐘至 7 天之間的 間隔文字常值。例如,指定 INTERVAL 4 HOUR 的過時間隔為 4 小時。使用這個值時,如果資料表已在過去 4 小時內重新整理,對資料表執行的作業會使用快取的中繼資料。如果快取的中繼資料較舊,則該作業會改為從 Cloud Storage 擷取中繼資料。

null_marker

STRING

代表 CSV 檔案中 NULL 值的字串。

適用於 CSV 資料。

object_metadata

STRING

只有在建立物件資料表時才需要。

建立物件資料表時,請將這個選項的值設為 SIMPLE

preserve_ascii_control_characters

BOOL

如果是 true,則會保留嵌入的 ASCII 控制字元,也就是 ASCII 表格中前 32 個字元,範圍從 '\x00' 到 '\x1F'。

適用於 CSV 資料。

projection_fields

STRING

要載入的實體屬性清單。

適用於 Datastore 資料。

quote

STRING

在 CSV 檔案中用來引用資料區段的字串。如果資料包含引用的換行符號字元,請將 allow_quoted_newlines 屬性設為 true

適用於 CSV 資料。

reference_file_schema_uri

STRING

使用者提供的參考檔案,其中包含資料表結構定義。

適用於 Parquet/ORC/AVRO 資料。

範例:"gs://bucket/path/reference_schema_file.parquet"

require_hive_partition_filter

BOOL

如果為 true,則對這個資料表的所有查詢都需要分區篩選器,可用於在讀取資料時刪除分區。僅適用於以 Hive 分區的外部資料表。

適用於 Avro、CSV、JSON、Parquet 和 ORC 資料。

sheet_range

STRING

要查詢的 Google 試算表試算表範圍。

適用於 Google 試算表資料。

例如:"sheet1!A1:B20"

skip_leading_rows

INT64

讀取資料時,要略過檔案開頭的列數。

適用於 CSV 和 Google 試算表資料。

tags <ARRAY<STRUCT<STRING, STRING>>>

資料表的 IAM 標記陣列,以鍵/值組合表示。鍵應為命名空間限定鍵名稱,值則應為簡稱

time_zone

STRING

(預覽)

如果剖析的時間戳記值沒有特定時區,就會採用這個預設時區。

請查看有效的時區名稱

如果沒有這個值,則會使用預設時區 (UTC) 剖析沒有特定時區的時間戳記值。

適用於 CSV 和 JSON 資料。

date_format

STRING

(預覽)

格式元素,可定義輸入檔案中的 DATE 值格式 (例如 MM/DD/YYYY)。

如果存在這個值,這個格式是唯一相容的日期格式。結構定義自動偵測功能也會根據這個格式,而非現有格式,決定 DATE 欄的類型。

如果沒有這個值,系統會使用預設格式剖析日期欄位。

適用於 CSV 和 JSON 資料。

datetime_format

STRING

(預覽)

格式元素,可定義輸入檔案中的 DATETIME 值格式 (例如 MM/DD/YYYY HH24:MI:SS.FF3)。

如果存在這個值,這個格式是唯一相容的 DATETIME 格式。結構定義自動偵測功能也會根據這個格式,而非現有格式,決定 DATETIME 欄類型。

如果沒有這個值,系統會使用預設格式剖析 DATETIME 欄位。

適用於 CSV 和 JSON 資料。

time_format

STRING

(預覽)

格式元素,可定義輸入檔案中的 TIME 值格式 (例如 HH24:MI:SS.FF3)。

如果存在這個值,這個格式是唯一相容的 TIME 格式。結構定義自動偵測功能也會根據這個格式,而非現有格式,決定 TIME 欄的類型。

如果沒有這個值,系統會使用預設格式剖析 TIME 欄位。

適用於 CSV 和 JSON 資料。

timestamp_format

STRING

(預覽)

格式元素,可定義輸入檔案中的 TIMESTAMP 值格式 (例如 MM/DD/YYYY HH24:MI:SS.FF3)。

如果存在這個值,這個格式是唯一相容的 TIMESTAMP 格式。結構定義自動偵測功能也會根據這個格式,而非現有格式,決定 TIMESTAMP 欄類型。

如果沒有這個值,系統會使用預設格式剖析 TIMESTAMP 欄位。

適用於 CSV 和 JSON 資料。

uris

針對非 Bigtable 資料表的外部資料表 (包括物件資料表):

ARRAY<STRING>

外部資料位置的完整 URI 陣列。每個 URI 可包含一個星號 (*) 萬用字元,且必須出現在值區名稱之後。指定目標為多個檔案的 uris 值時,所有檔案都必須共用相容的結構定義。

以下範例顯示有效的 uris 值:

  • ['gs://bucket/path1/myfile.csv']
  • ['gs://bucket/path1/*.csv']
  • ['gs://bucket/path1/*', 'gs://bucket/path2/file00*']

針對 Bigtable 資料表:

STRING

這個 URI 會標示要用來做為資料來源的 Bigtable 資料表。您只能指定一個 Bigtable URI。

示例: https://googleapis.com/bigtable/projects/project_id/instances/instance_id[/appProfiles/app_profile]/tables/table_name

如要進一步瞭解如何建構 Bigtable URI,請參閱「擷取 Bigtable URI」。

範例

範例 1:

下列範例會透過查詢 INFORMATION_SCHEMA.TABLE_OPTIONS 檢視表,擷取預設專案 (myproject) 中 mydataset 內所有資料表的預設資料表到期時間。

如要對預設專案以外的專案執行查詢,請使用以下格式將專案 ID 新增至資料集:`project_id`.dataset.INFORMATION_SCHEMA.view;例如 `myproject`.mydataset.INFORMATION_SCHEMA.TABLE_OPTIONS

  SELECT
    *
  FROM
    mydataset.INFORMATION_SCHEMA.TABLE_OPTIONS
  WHERE
    option_name = 'expiration_timestamp';

結果大致如下:

  +----------------+---------------+------------+----------------------+-------------+--------------------------------------+
  | table_catalog  | table_schema  | table_name |     option_name      | option_type |             option_value             |
  +----------------+---------------+------------+----------------------+-------------+--------------------------------------+
  | myproject      | mydataset     | mytable1   | expiration_timestamp | TIMESTAMP   | TIMESTAMP "2020-01-16T21:12:28.000Z" |
  | myproject      | mydataset     | mytable2   | expiration_timestamp | TIMESTAMP   | TIMESTAMP "2021-01-01T21:12:28.000Z" |
  +----------------+---------------+------------+----------------------+-------------+--------------------------------------+
  

範例 2:

以下範例會擷取 mydataset 中包含測試資料的所有資料表相關中繼資料。此查詢使用 description 選項中的值來尋找說明中的任意位置包含「test」的資料表。mydataset 在您的預設專案 (myproject) 中。

如要對預設專案以外的專案執行查詢,請使用以下格式將專案 ID 新增至資料集:`project_id`.dataset.INFORMATION_SCHEMA.view;例如 `myproject`.mydataset.INFORMATION_SCHEMA.TABLE_OPTIONS

  SELECT
    *
  FROM
    mydataset.INFORMATION_SCHEMA.TABLE_OPTIONS
  WHERE
    option_name = 'description'
    AND option_value LIKE '%test%';

結果大致如下:

  +----------------+---------------+------------+-------------+-------------+--------------+
  | table_catalog  | table_schema  | table_name | option_name | option_type | option_value |
  +----------------+---------------+------------+-------------+-------------+--------------+
  | myproject      | mydataset     | mytable1   | description | STRING      | "test data"  |
  | myproject      | mydataset     | mytable2   | description | STRING      | "test data"  |
  +----------------+---------------+------------+-------------+-------------+--------------+
  

COLUMNS 個檢視表

當您查詢 INFORMATION_SCHEMA.COLUMNS 檢視表時,系統會在查詢結果中,針對資料集中的每個資料欄 (欄位),分別列出一個相對應的資料列。

INFORMATION_SCHEMA.COLUMNS 檢視表具有下列結構定義:

資料欄名稱 資料類型
TABLE_CATALOG STRING 包含資料集的專案 ID
TABLE_SCHEMA STRING 資料表所屬資料集的名稱 (又稱為 datasetId)
TABLE_NAME STRING 資料表或檢視表的名稱 (又稱為 tableId)
COLUMN_NAME STRING 資料欄的名稱
ORDINAL_POSITION INT64 資料表中資料欄的 1 索引偏移;如果是虛擬資料欄 (例如 _PARTITIONTIME 或 _PARTITIONDATE),則值為 NULL
IS_NULLABLE STRING YESNO,視資料欄的模式是否允許使用 NULL 值而定
DATA_TYPE STRING 資料欄的 GoogleSQL 資料類型
IS_GENERATED STRING 此值一律為 NEVER
GENERATION_EXPRESSION STRING 此值一律為 NULL
IS_STORED STRING 此值一律為 NULL
IS_HIDDEN STRING YESNO,視資料欄是否為虛擬資料欄 (例如 _PARTITIONTIME 或 _PARTITIONDATE) 而定
IS_UPDATABLE STRING 此值一律為 NULL
IS_SYSTEM_DEFINED STRING YESNO,視資料欄是否為虛擬資料欄 (例如 _PARTITIONTIME 或 _PARTITIONDATE) 而定
IS_PARTITIONING_COLUMN STRING YESNO,視資料欄是否為分區資料欄而定
CLUSTERING_ORDINAL_POSITION INT64 在資料表的叢集資料欄中,資料欄的 1 索引偏移。如果資料表不是叢集資料表,則此值為 NULL
COLLATION_NAME STRING 如果存在,則為排序規則的名稱;否則為 NULL

如果傳入 STRINGARRAY<STRING>,則會傳回排序規則 (如果存在);否則會傳回 NULL
COLUMN_DEFAULT STRING 資料欄的預設值 (如果存在);否則,值為 NULL
ROUNDING_MODE STRING 如果欄位類型為參數化 NUMERICBIGNUMERIC,則會使用這個值的四捨五入模式;否則,值為 NULL

範例

以下範例會從 census_bureau_usa 資料集中的 population_by_zip_2010 資料表,擷取 INFORMATION_SCHEMA.COLUMNS 檢視表的中繼資料。這個資料集是 BigQuery 公開資料集方案的一部分。

由於您要查詢的資料表位於另一個專案 (bigquery-public-data) 中,因此您應使用以下格式將專案 ID 新增至資料集:`project_id`.dataset.INFORMATION_SCHEMA.view;例如 `bigquery-public-data`.census_bureau_usa.INFORMATION_SCHEMA.TABLES

目前以下資料欄會從查詢結果中排除,保留供未來使用:

  • IS_GENERATED
  • GENERATION_EXPRESSION
  • IS_STORED
  • IS_UPDATABLE
  SELECT
    * EXCEPT(is_generated, generation_expression, is_stored, is_updatable)
  FROM
    `bigquery-public-data`.census_bureau_usa.INFORMATION_SCHEMA.COLUMNS
  WHERE
    table_name = 'population_by_zip_2010';

結果類似下列內容。為了方便閱讀,我們已從結果中排除部分資料欄。

+------------------------+-------------+------------------+-------------+-----------+-----------+-------------------+------------------------+-----------------------------+
|       table_name       | column_name | ordinal_position | is_nullable | data_type | is_hidden | is_system_defined | is_partitioning_column | clustering_ordinal_position |
+------------------------+-------------+------------------+-------------+-----------+-----------+-------------------+------------------------+-----------------------------+
| population_by_zip_2010 | zipcode     |                1 | NO          | STRING    | NO        | NO                | NO                     |                        NULL |
| population_by_zip_2010 | geo_id      |                2 | YES         | STRING    | NO        | NO                | NO                     |                        NULL |
| population_by_zip_2010 | minimum_age |                3 | YES         | INT64     | NO        | NO                | NO                     |                        NULL |
| population_by_zip_2010 | maximum_age |                4 | YES         | INT64     | NO        | NO                | NO                     |                        NULL |
| population_by_zip_2010 | gender      |                5 | YES         | STRING    | NO        | NO                | NO                     |                        NULL |
| population_by_zip_2010 | population  |                6 | YES         | INT64     | NO        | NO                | NO                     |                        NULL |
+------------------------+-------------+------------------+-------------+-----------+-----------+-------------------+------------------------+-----------------------------+
  

COLUMN_FIELD_PATHS 個檢視表

查詢 INFORMATION_SCHEMA.COLUMN_FIELD_PATHS 檢視表時,以巢狀結構形式放置在 RECORD (或 STRUCT) 資料欄中的每個資料欄,在查詢結果中都會有一個相對應的資料列。

INFORMATION_SCHEMA.COLUMN_FIELD_PATHS 檢視表具有下列結構定義:

資料欄名稱 資料類型
TABLE_CATALOG STRING 包含資料集的專案 ID
TABLE_SCHEMA STRING 資料表所屬資料集的名稱 (又稱為 datasetId)
TABLE_NAME STRING 資料表或檢視表的名稱 (又稱為 tableId)
COLUMN_NAME STRING 資料欄的名稱
FIELD_PATH STRING 巢狀結構形式放置在 RECORD (或 STRUCT) 資料欄中之資料欄的路徑
DATA_TYPE STRING 資料欄的 GoogleSQL 資料類型
DESCRIPTION STRING 資料欄的說明
COLLATION_NAME STRING 如果存在校正規則,則傳回該名稱;否則傳回 NULL

如果傳入 STRUCT 中的 STRINGARRAY<STRING>STRING 欄位,則會傳回校正規則 (如果存在);否則傳回 NULL
ROUNDING_MODE STRING 將精確度和比例套用至參數化 NUMERICBIGNUMERIC 值時使用的捨入模式;否則,值為 NULL

範例

以下範例會從 github_repos 資料集中的 commits 資料表,擷取 INFORMATION_SCHEMA.COLUMN_FIELD_PATHS 檢視表的中繼資料。這個資料集是 BigQuery 公開資料集方案的一部分。

由於您要查詢的資料表位於另一個專案 (bigquery-public-data) 中,因此您應使用以下格式將專案 ID 新增至資料集:`project_id`.dataset.INFORMATION_SCHEMA.view;例如 `bigquery-public-data`.github_repos.INFORMATION_SCHEMA.COLUMN_FIELD_PATHS

commits 資料表中包含下列巢狀結構資料欄及巢狀與重複的資料欄:

  • author:巢狀結構 RECORD 資料欄
  • committer:巢狀結構 RECORD 資料欄
  • trailer:巢狀與重複的 RECORD 資料欄
  • difference:巢狀與重複的 RECORD 資料欄

如要查看 authordifference 欄位相關的中繼資料,請執行下列查詢。

SELECT
  *
FROM
  `bigquery-public-data`.github_repos.INFORMATION_SCHEMA.COLUMN_FIELD_PATHS
WHERE
  table_name = 'commits'
  AND (column_name = 'author' OR column_name = 'difference');

結果類似下列內容。為了方便閱讀,我們已從結果中排除部分資料欄。

  +------------+-------------+---------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------+-------------+
  | table_name | column_name |     field_path      |                                                                      data_type                                                                      | description |
  +------------+-------------+---------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------+-------------+
  | commits    | author      | author              | STRUCT<name STRING, email STRING, time_sec INT64, tz_offset INT64, date TIMESTAMP>                                                                  | NULL        |
  | commits    | author      | author.name         | STRING                                                                                                                                              | NULL        |
  | commits    | author      | author.email        | STRING                                                                                                                                              | NULL        |
  | commits    | author      | author.time_sec     | INT64                                                                                                                                               | NULL        |
  | commits    | author      | author.tz_offset    | INT64                                                                                                                                               | NULL        |
  | commits    | author      | author.date         | TIMESTAMP                                                                                                                                           | NULL        |
  | commits    | difference  | difference          | ARRAY<STRUCT<old_mode INT64, new_mode INT64, old_path STRING, new_path STRING, old_sha1 STRING, new_sha1 STRING, old_repo STRING, new_repo STRING>> | NULL        |
  | commits    | difference  | difference.old_mode | INT64                                                                                                                                               | NULL        |
  | commits    | difference  | difference.new_mode | INT64                                                                                                                                               | NULL        |
  | commits    | difference  | difference.old_path | STRING                                                                                                                                              | NULL        |
  | commits    | difference  | difference.new_path | STRING                                                                                                                                              | NULL        |
  | commits    | difference  | difference.old_sha1 | STRING                                                                                                                                              | NULL        |
  | commits    | difference  | difference.new_sha1 | STRING                                                                                                                                              | NULL        |
  | commits    | difference  | difference.old_repo | STRING                                                                                                                                              | NULL        |
  | commits    | difference  | difference.new_repo | STRING                                                                                                                                              | NULL        |
  +------------+-------------+---------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------+-------------+
  

TABLE_STORAGE 個檢視表

TABLE_STORAGETABLE_STORAGE_BY_ORGANIZATION 檢視畫面具有下列結構定義:

資料欄名稱 資料類型
PROJECT_ID STRING 包含資料集的專案 ID。
PROJECT_NUMBER INT64 包含資料集的專案專案編號。
TABLE_CATALOG STRING 包含資料集的專案 ID。
TABLE_SCHEMA STRING 資料表或具象化檢視表所屬資料集的名稱 (又稱為 datasetId)。
TABLE_NAME STRING 資料表或已具象化檢視表的名稱,又稱為 tableId
CREATION_TIME TIMESTAMP 資料表的建立時間。
TOTAL_ROWS INT64 資料表或物化檢視畫面中的資料列總數。
TOTAL_PARTITIONS INT64 資料表或物化檢視畫面中的分區數。未分區的資料表會傳回 0。
TOTAL_LOGICAL_BYTES INT64 表格或具象化檢視畫面中的邏輯 (未壓縮) 位元組總數。
ACTIVE_LOGICAL_BYTES INT64 未滿 90 天的邏輯 (未經壓縮) 位元組數。
LONG_TERM_LOGICAL_BYTES INT64 超過 90 天的邏輯 (未壓縮) 位元組數。
CURRENT_PHYSICAL_BYTES INT64 在所有分區中,目前儲存資料表的實際位元組總數。
TOTAL_PHYSICAL_BYTES INT64 用於儲存空間的實體 (壓縮) 位元組總數,包括使用中、長期和時間回溯 (已刪除或變更的資料) 位元組。不會納入備用 (在時間旅行視窗後刪除或變更的資料) 位元組。
ACTIVE_PHYSICAL_BYTES INT64 90 天內的實體 (壓縮) 位元組數,包括時間旅行 (已刪除或已變更的資料) 位元組。
LONG_TERM_PHYSICAL_BYTES INT64 超過 90 天前的實體 (已壓縮) 位元組數。
TIME_TRAVEL_PHYSICAL_BYTES INT64 時間旅行儲存空間 (已刪除或變更的資料) 使用的實體 (壓縮) 位元組數。
STORAGE_LAST_MODIFIED_TIME TIMESTAMP 資料最近一次寫入資料表的時間。
DELETED BOOLEAN 指出資料表是否已刪除。
TABLE_TYPE STRING 資料表類型。例如 BASE TABLE
FAIL_SAFE_PHYSICAL_BYTES INT64 安全儲存空間 (已刪除或變更的資料) 使用的實體 (壓縮) 位元組數。
LAST_METADATA_INDEX_REFRESH_TIME TIMESTAMP 資料表上次更新中繼資料索引的時間。

範例

範例 1:

以下範例顯示目前專案的邏輯位元組總數。

SELECT
  SUM(total_logical_bytes) AS total_logical_bytes
FROM
  `region-REGION`.INFORMATION_SCHEMA.TABLE_STORAGE;

結果大致如下:

+---------------------+
| total_logical_bytes |
+---------------------+
| 971329178274633     |
+---------------------+
範例 2:

以下範例顯示目前專案的資料集層級,以 GiB 為單位顯示不同的儲存位元組。

SELECT
  table_schema AS dataset_name,
  -- Logical
  SUM(total_logical_bytes) / power(1024, 3) AS total_logical_gib,  
  SUM(active_logical_bytes) / power(1024, 3) AS active_logical_gib, 
  SUM(long_term_logical_bytes) / power(1024, 3) AS long_term_logical_gib, 
  -- Physical
  SUM(total_physical_bytes) / power(1024, 3) AS total_physical_gib,
  SUM(active_physical_bytes) / power(1024, 3) AS active_physical_gib,
  SUM(active_physical_bytes - time_travel_physical_bytes) / power(1024, 3) AS active_no_tt_physical_gib,
  SUM(long_term_physical_bytes) / power(1024, 3) AS long_term_physical_gib,
  SUM(time_travel_physical_bytes) / power(1024, 3) AS time_travel_physical_gib,
  SUM(fail_safe_physical_bytes) / power(1024, 3) AS fail_safe_physical_gib 
FROM
  `region-REGION`.INFORMATION_SCHEMA.TABLE_STORAGE 
WHERE 
  table_type ='BASE TABLE'
GROUP BY 
  table_schema  
ORDER BY 
  dataset_name 
範例 3:

以下範例說明如何預測未來 30 天內,邏輯和實體帳單模式之間每個資料集的價格差異。這個範例假設未來的儲存空間用量在查詢執行後的 30 天內保持不變。請注意,預測功能僅限於基本資料表,不包含資料集中的所有其他類型資料表。

這個查詢的價格變數中使用的價格適用於 us-central1 區域。如果您想針對其他區域執行這項查詢,請適當更新價格變數。如需價格資訊,請參閱「儲存空間定價」。

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

    前往「BigQuery」頁面

  2. 在「Query editor」(查詢編輯器) 方塊中輸入下列 GoogleSQL 查詢。INFORMATION_SCHEMA 需要使用 GoogleSQL 語法。GoogleSQL 是 Google Cloud 控制台的預設語法。

    DECLARE active_logical_gib_price FLOAT64 DEFAULT 0.02;
    DECLARE long_term_logical_gib_price FLOAT64 DEFAULT 0.01;
    DECLARE active_physical_gib_price FLOAT64 DEFAULT 0.04;
    DECLARE long_term_physical_gib_price FLOAT64 DEFAULT 0.02;
    
    WITH
     storage_sizes AS (
       SELECT
         table_schema AS dataset_name,
         -- Logical
         SUM(IF(deleted=false, active_logical_bytes, 0)) / power(1024, 3) AS active_logical_gib,
         SUM(IF(deleted=false, long_term_logical_bytes, 0)) / power(1024, 3) AS long_term_logical_gib,
         -- Physical
         SUM(active_physical_bytes) / power(1024, 3) AS active_physical_gib,
         SUM(active_physical_bytes - time_travel_physical_bytes) / power(1024, 3) AS active_no_tt_physical_gib,
         SUM(long_term_physical_bytes) / power(1024, 3) AS long_term_physical_gib,
         -- Restorable previously deleted physical
         SUM(time_travel_physical_bytes) / power(1024, 3) AS time_travel_physical_gib,
         SUM(fail_safe_physical_bytes) / power(1024, 3) AS fail_safe_physical_gib,
       FROM
         `region-REGION`.INFORMATION_SCHEMA.TABLE_STORAGE_BY_PROJECT
       WHERE total_physical_bytes + fail_safe_physical_bytes > 0
         -- Base the forecast on base tables only for highest precision results
         AND table_type  = 'BASE TABLE'
         GROUP BY 1
     )
    SELECT
      dataset_name,
      -- Logical
      ROUND(active_logical_gib, 2) AS active_logical_gib,
      ROUND(long_term_logical_gib, 2) AS long_term_logical_gib,
      -- Physical
      ROUND(active_physical_gib, 2) AS active_physical_gib,
      ROUND(long_term_physical_gib, 2) AS long_term_physical_gib,
      ROUND(time_travel_physical_gib, 2) AS time_travel_physical_gib,
      ROUND(fail_safe_physical_gib, 2) AS fail_safe_physical_gib,
      -- Compression ratio
      ROUND(SAFE_DIVIDE(active_logical_gib, active_no_tt_physical_gib), 2) AS active_compression_ratio,
      ROUND(SAFE_DIVIDE(long_term_logical_gib, long_term_physical_gib), 2) AS long_term_compression_ratio,
      -- Forecast costs logical
      ROUND(active_logical_gib * active_logical_gib_price, 2) AS forecast_active_logical_cost,
      ROUND(long_term_logical_gib * long_term_logical_gib_price, 2) AS forecast_long_term_logical_cost,
      -- Forecast costs physical
      ROUND((active_no_tt_physical_gib + time_travel_physical_gib + fail_safe_physical_gib) * active_physical_gib_price, 2) AS forecast_active_physical_cost,
      ROUND(long_term_physical_gib * long_term_physical_gib_price, 2) AS forecast_long_term_physical_cost,
      -- Forecast costs total
      ROUND(((active_logical_gib * active_logical_gib_price) + (long_term_logical_gib * long_term_logical_gib_price)) -
         (((active_no_tt_physical_gib + time_travel_physical_gib + fail_safe_physical_gib) * active_physical_gib_price) + (long_term_physical_gib * long_term_physical_gib_price)), 2) AS forecast_total_cost_difference
    FROM
      storage_sizes
    ORDER BY
      (forecast_active_logical_cost + forecast_active_physical_cost) DESC;
  3. 按一下「執行」

結果會與下列內容相似:

+--------------+--------------------+-----------------------+---------------------+------------------------+--------------------------+-----------------------------+------------------------------+----------------------------------+-------------------------------+----------------------------------+--------------------------------+
| dataset_name | active_logical_gib | long_term_logical_gib | active_physical_gib | long_term_physical_gib | active_compression_ratio | long_term_compression_ratio | forecast_active_logical_cost | forecaset_long_term_logical_cost | forecast_active_physical_cost | forecast_long_term_physical_cost | forecast_total_cost_difference |
+--------------+--------------------+-----------------------+---------------------+------------------------+--------------------------+-----------------------------+------------------------------+----------------------------------+-------------------------------+----------------------------------+--------------------------------+
| dataset1     |               10.0 |                  10.0 |                 1.0 |                    1.0 |                     10.0 |                        10.0 |                          0.2 |                              0.1 |                          0.04 |                             0.02 |                           0.24 |

列出資料集內的資料表

您可以透過下列方式列出資料集中的資料表:

  • 使用 Google Cloud 控制台。
  • 使用 bq 指令列工具的 bq ls 指令。
  • 呼叫 tables.list API 方法
  • 使用用戶端程式庫。

所需權限

您至少必須具備 bigquery.tables.list 權限,才能列出資料集裡的資料表。以下是具有 bigquery.tables.list 權限的預先定義 IAM 角色:

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

如要進一步瞭解 BigQuery 中的身分與存取權管理角色和權限,請參閱「存取權控管」一文。

列出表格

如何列出資料集中的資料表:

主控台

  1. 在 Google Cloud 主控台的導覽窗格中,按一下資料集以展開資料集。畫面便會顯示資料集裡的資料表和檢視表。

  2. 捲動清單來檢視該資料集中的資料表,資料表和檢視表會分別以不同的圖示呈現。

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 ls 指令。--format 旗標可用來控制輸出格式。如要列出非預設專案中的資料表,請使用下列格式將專案 ID 新增至資料集:project_id:dataset

    其他標記包括:

    • --max_results-n:用來表示結果數量上限的整數。預設值為 50
    bq ls \
    --format=pretty \
    --max_results integer \
    project_id:dataset

    其中:

    • integer 是整數,代表要列出的資料表數量。
    • project_id 是您的專案 ID。
    • dataset 是資料集名稱。

    執行指令時,Type 欄位會顯示 TABLEVIEW,例如:

    +-------------------------+-------+----------------------+-------------------+
    |         tableId         | Type  |        Labels        | Time Partitioning |
    +-------------------------+-------+----------------------+-------------------+
    | mytable                 | TABLE | department:shipping  |                   |
    | myview                  | VIEW  |                      |                   |
    +-------------------------+-------+----------------------+-------------------+
    

    範例:

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

       bq ls --format=pretty mydataset

    輸入下列指令,系統即會從 mydataset 傳回超過 50 個資料集 (50 為預設輸出數量)。mydataset 位於您的預設專案中。

       bq ls --format=pretty --max_results 60 mydataset

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

       bq ls --format=pretty myotherproject:mydataset

API

如要使用 API 列出資料表,請呼叫 tables.list 方法。

C#

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

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


using Google.Cloud.BigQuery.V2;
using System;
using System.Collections.Generic;
using System.Linq;

public class BigQueryListTables
{
    public void ListTables(
        string projectId = "your-project-id",
        string datasetId = "your_dataset_id"
    )
    {
        BigQueryClient client = BigQueryClient.Create(projectId);
        // Retrieve list of tables in the dataset
        List<BigQueryTable> tables = client.ListTables(datasetId).ToList();
        // Display the results
        if (tables.Count > 0)
        {
            Console.WriteLine($"Tables in dataset {datasetId}:");
            foreach (var table in tables)
            {
                Console.WriteLine($"\t{table.Reference.TableId}");
            }
        }
        else
        {
            Console.WriteLine($"{datasetId} does not contain any tables.");
        }
    }
}

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"
	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
}

Java

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

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

import com.google.api.gax.paging.Page;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQuery.TableListOption;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.DatasetId;
import com.google.cloud.bigquery.Table;

public class ListTables {

  public static void runListTables() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "bigquery-public-data";
    String datasetName = "samples";
    listTables(projectId, datasetName);
  }

  public static void listTables(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);
      Page<Table> tables = bigquery.listTables(datasetId, TableListOption.pageSize(100));
      tables.iterateAll().forEach(table -> System.out.print(table.getTableId().getTable() + "\n"));

      System.out.println("Tables listed successfully.");
    } catch (BigQueryException e) {
      System.out.println("Tables were not listed. Error occurred: " + 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 listTables() {
  // Lists tables in 'my_dataset'.

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

  // List all tables in the dataset
  const [tables] = await bigquery.dataset(datasetId).getTables();

  console.log('Tables:');
  tables.forEach(table => console.log(table.id));
}

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';

$bigQuery = new BigQueryClient([
    'projectId' => $projectId,
]);
$dataset = $bigQuery->dataset($datasetId);
$tables = $dataset->tables();
foreach ($tables as $table) {
    print($table->id() . PHP_EOL);
}

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))

Ruby

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

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

require "google/cloud/bigquery"

def list_tables dataset_id = "your_dataset_id"
  bigquery = Google::Cloud::Bigquery.new
  dataset  = bigquery.dataset dataset_id

  puts "Tables in dataset #{dataset_id}:"
  dataset.tables.each do |table|
    puts "\t#{table.table_id}"
  end
end

表格安全性

如要控管 BigQuery 中資料表的存取權,請參閱「使用 IAM 控管資源存取權」。

後續步驟

歡迎試用

如果您未曾使用過 Google Cloud,歡迎建立帳戶,親自體驗實際使用 BigQuery 的成效。新客戶可以獲得價值 $300 美元的免費抵免額,可用於執行、測試及部署工作負載。

免費試用 BigQuery