建立執行個體

Bigtable 執行個體是叢集和資料表的頂層容器,可讓您設定儲存空間,並在最多 8 個區域中複製資料,確保高可用性。您可以使用 Google Cloud 控制台、Google Cloud CLI、cbt CLI 或 Cloud Bigtable 用戶端程式庫,建立及設定執行個體。

事前準備

請務必熟悉 Bigtable 總覽和執行個體、叢集和節點。

準備環境:

  1. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  2. Verify that billing is enabled for your Google Cloud project.

  3. Enable the Cloud Bigtable API, Cloud Bigtable Admin API APIs, if any are not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

  4. Install the Google Cloud CLI.

  5. Configure the gcloud CLI to use your federated identity.

    For more information, see Sign in to the gcloud CLI with your federated identity.

  6. To initialize the gcloud CLI, run the following command:

    gcloud init
  7. 執行下列指令,安裝 cbt CLI:
    gcloud components install cbt

規劃設定:

  1. 選用:如果您打算啟用複製功能,請按照下列步驟操作:

  2. 選用:如要使用客戶自行管理的加密金鑰 (CMEK),而非預設的 Google 代管加密金鑰,請在建立新執行個體之前準備好 CMEK 金鑰 ID。執行個體建立後,您無法為其新增 CMEK 保護機制,也無法修改或更換 CMEK 金鑰。詳情請參閱「使用客戶自行管理的加密金鑰 (CMEK)」。

建立執行個體

如要建立 Bigtable 執行個體,請按照下列步驟操作:

控制台

  1. 前往 Google Cloud 控制台的「Create instance」(建立執行個體) 頁面。

    前往「Create instance」(建立執行個體) 頁面

  2. 輸入執行個體的名稱。

    Google Cloud 控制台會顯示這個名稱,用於識別執行個體。

  3. 輸入執行個體 ID。

    執行個體 ID 是執行個體的永久性識別碼。

  4. 按一下「繼續」。

  5. 在「Select your edition」(選取版本) 部分,選取 Bigtable 版本。

    如要比較各版本的規格,請按一下「Compare editions」(比較版本)。詳情請參閱「版本總覽」。

  6. 按一下「繼續」。

  7. 選擇要為叢集使用 SSD 或 HDD 磁碟。在多數情況下,SSD 是最佳選擇。如要啟用記憶體內層,請選取「SSD」。選定後即無法變更。

  8. 按一下「繼續」。

  9. 對第一個叢集輸入叢集 ID。

    叢集 ID 是叢集的永久識別碼。

  10. 請選擇第一個叢集執行的地區及區域。

  11. 選用:如要將叢集設為一律以兩個節點為單位調度資源,請選取「啟用 2 倍節點資源調度功能」。2 倍節點資源調度功能僅適用於部分可用區。Enterprise Plus 版本的預設選項是 2 倍節點資源調度。詳情請參閱「節點縮放比例係數」。

  12. 選用:如要在叢集層級使用記憶體內層,請選取「Enable in-memory」(啟用記憶體內層)。

  13. 選擇叢集的節點資源調度模式。在大多數情況下,建議您選擇自動調度資源。如需資源調度指南,請參閱「自動調度資源」。

    1. 在「Manual node allocation」(手動分配節點) 部分,輸入第一個叢集的 Bigtable 節點數量。如果不確定需要多少節點,請使用預設值。您可以稍後再新增更多節點。
    2. 在「自動調度資源」部分,輸入下列項目的值:
      • 節點數量下限
      • 節點數量上限
      • CPU 使用率目標
      • 儲存空間使用率目標
  14. 選用:如要使用 CMEK 保護執行個體,而非預設的 Google 代管加密,請完成下列步驟:

    1. 按一下「顯示加密選項」。
    2. 選取「Cloud KMS key」(Cloud KMS 金鑰)。
    3. 在「Key management type」(金鑰管理類型) 欄位中,選取下列其中一個選項:
      • 如要自動建立 Cloud KMS 金鑰,請選取「Cloud KMS with Autokey」,然後按一下「要求金鑰」。系統會顯示訊息,指出金鑰已成功建立並可供使用。
      • 如要手動新增金鑰,請選取「Cloud KMS」。選取或輸入要用於叢集的 CMEK 金鑰資源名稱。日後無法新增。如果系統提示您授予 CMEK 金鑰服務帳戶權限,請按一下「Grant」(授予)。您的使用者帳戶必須具備 Cloud KMS 管理員角色,才能完成這項工作。按一下「Save」(儲存)。
  15. 選用:如要立即啟用複製功能,請完成下列額外步驟:

    1. 按一下 [Show advanced options] (顯示進階選項)。
    2. 按一下「Add cluster」(新增叢集),輸入叢集設定,然後點選「Add」(新增)。重複這個步驟,在執行個體中建立其他叢集。您也可以稍後新增叢集來啟用複製功能。

    區域中的每個可用區只能包含一個叢集。如果「Add cluster」(新增叢集) 按鈕已停用,請變更第一個叢集的可用區。

    如要建立叢集數量超過六個的執行個體,請先建立叢集數量為六個的執行個體,然後在執行個體中新增更多叢集。

  16. 按一下「建立」,建立執行個體。

  17. 查看預設應用程式設定檔中的複製設定,確認是否符合複製用途。您可能需要更新預設應用程式設定檔或建立自訂應用程式設定檔。

gcloud

  1. 使用 bigtable instances create 指令建立執行個體:

    gcloud bigtable instances create INSTANCE_ID \
        --display-name=DISPLAY_NAME \
        [--edition=EDITION] \
        [--cluster-storage-type=CLUSTER_STORAGE_TYPE] \
        [--cluster-config=id=CLUSTER_ID,zone=CLUSTER_ZONE, \
        nodes=NODES] \
        [--cluster-config=id=CLUSTER_ID,zone=CLUSTER_ZONE, \
        autoscaling-min-nodes=AUTOSCALING_MIN_NODES, \
        autoscaling-max-nodes=AUTOSCALING_MAX_NODES, \
        autoscaling-cpu-target=AUTOSCALING_CPU_TARGET, \
        autoscaling-storage-target=AUTOSCALING_STORAGE_TARGET, \
        kms-key=KMS_KEY], \
        [node-scaling-factor=NODE_SCALING_FACTOR]
    

    更改下列內容:

    • INSTANCE_ID:執行個體的永久 ID
    • DISPLAY_NAME:在 Google Cloud 控制台中識別執行個體的人類可讀名稱。
    • CLUSTER_ID:叢集的永久 ID
    • CLUSTER_ZONE:叢集執行的可用區。

    您必須使用 --cluster-config 旗標,為執行個體設定至少一個叢集。如要建立具有多個叢集的執行個體,請為每個叢集重複 --cluster-config 旗標。

    如果是手動分配節點,則可選擇是否要在 --cluster-config 旗標中設定 nodes。如未設定任何值,Bigtable 會根據資料足跡自動為叢集分配節點,並將儲存空間使用率最佳化至 50%。自動分配節點會影響定價。如要控管叢集中的節點數量,請將 NODES 替換為叢集中所需的節點數量。進一步瞭解節點。

    在大多數情況下,請選擇自動調度資源,而非手動分配節點。如要使用自動調度資源,請在 --cluster-config 旗標中提供 autoscaling- 選項 (autoscaling-storage-target 為選用),且不要使用 nodes。如需選擇自動調度資源設定值的指引,請參閱「自動調度資源」。請替換 cluster-config 選項索引鍵的下列內容:

    • AUTOSCALING_MIN_NODES:叢集的節點數量下限。
    • AUTOSCALING_MAX_NODES:叢集的節點數量上限。
    • AUTOSCALING_CPU_TARGET:叢集的目標 CPU 使用率百分比。這個值必須介於 10 到 80 之間。
    • AUTOSCALING_STORAGE_TARGET:(選用) Bigtable 透過新增或移除節點,維持的儲存空間使用率目標 (以 GiB 為單位)。
    • KMS_KEY:叢集的 CMEK 金鑰。

      KMS_KEY 值必須採用下列格式:

      projects/PROJECT/locations/LOCATION/keyRings/KEYRING/cryptoKeys/KEY
      

      更改下列內容:

      • PROJECT:專案的永久 ID
      • LOCATION:叢集的位置
      • KEYRING:金鑰所屬金鑰環的名稱
      • KEY:金鑰名稱

      範例如下:

      projects/examplestore.com:dev/locations/us-east1/keyRings/devt-cmek-2/cryptoKeys/key2

      如果執行個體受 CMEK 保護,每個叢集都必須與其 CMEK 金鑰位於相同區域。您只能將 CMEK 叢集新增至已受 CMEK 保護的執行個體。

    該指令接受下列選用標記:

    • --edition=EDITION:要建立的執行個體版本。可接受的值為 ENTERPRISE 和 ENTERPRISE_PLUS。預設值為 ENTERPRISE。
    • --cluster-storage-type=CLUSTER_STORAGE_TYPE:執行個體要使用的儲存空間類型。預設值為 SSD。 在多數情況下,預設值是最佳選擇。選定後即無法變更。 瞭解詳情。

    • --project=PROJECT:要建立叢集的專案 (如果與目前專案不同)。

    • node-scaling-factor=NODE_SCALING_FACTOR:啟用 2 倍節點資源調度的旗標。無論是手動或自動調度資源,都能啟用這項功能。可接受的值為 node-scaling-factor-2x 或 node-scaling-factor-1x。

      如要查看不支援 2 倍節點資源調度功能的 Bigtable 可用區清單,請參閱「節點縮放比例係數限制」。

    • --tags=TAGKEY_NAME=TAGVALUE_NAME:這個旗標會將標記新增至新執行個體。您可以透過永久 ID 或命名空間限定名稱,指定標記鍵和標記值。您可以提供多個標記,並以逗號分隔的清單形式呈現,例如:

      • 使用永久 ID:
        --tags=tagKeys/984321798431=tagValues/567890123456,
        tagKeys/123456789012=tagValues/098765432109
      • 使用命名空間限定名稱:
        --tags=123456789012/environment=123456789012/environment/prod,
        123456789012/costcenter=123456789012/costcenter/marketing
  2. 查看預設應用程式設定檔中的複製設定,確認是否符合複製用途。您可能需要更新預設應用程式設定檔或建立自訂應用程式設定檔。

cbt

  1. 首先,請建立含有單一叢集的執行個體。使用 createinstance 指令建立執行個體:

    cbt createinstance INSTANCE_ID \
        DISPLAY_NAME \
        CLUSTER_ID \
        CLUSTER_ZONE \
        CLUSTER_NUM_NODES \
        CLUSTER_STORAGE_TYPE
    

    提供下列資訊:

    • INSTANCE_ID:執行個體的永久 ID
    • DISPLAY_NAME:在 Google Cloud 控制台中識別執行個體的人類可讀名稱。
    • CLUSTER_ID:叢集的永久 ID
    • CLUSTER_ZONE:叢集執行的可用區。
    • CLUSTER_NUM_NODES:這是選填欄位。如未設定任何值,Bigtable 會根據資料足跡自動分配節點,並將儲存空間使用率最佳化至 50%。如要控管叢集中的節點數量,請更新 CLUSTER_NUM_NODES 值。請確認節點數量設為非零值。進一步瞭解節點。
    • CLUSTER_STORAGE_TYPE: 叢集所使用的儲存類型。執行個體中的每一個叢集必須使用相同的儲存空間類型。接受 SSD 和 HDD 值。在多數情況下,SSD 是最佳選擇。決定後即無法更改。瞭解詳情。
  2. 如要啟用複製功能,請使用 createcluster 指令新增叢集:

    
    cbt -instance=INSTANCE_ID \
    createcluster CLUSTER_ID \
    ZONE \
    NUM_NODES \
    STORAGE_TYPE
    
    

    提供下列資訊:

    • INSTANCE_ID:您剛建立的執行個體永久 ID
    • CLUSTER_ID:叢集的永久 ID
    • ZONE:叢集執行的可用區。

      區域中的每個可用區只能包含一個叢集。舉例來說,如果執行個體在 us-east1-b 有叢集,您可以在同一區域的其他可用區 (例如 us-east1-c) 新增叢集,或在其他區域 (例如 europe-west2-a) 的可用區新增叢集。

    • NUM_NODES: 這是選填欄位。如未設定任何值,Bigtable 會根據資料足跡自動分配節點,並將儲存空間使用率最佳化至 50%。如要控管叢集中的節點數量,請更新 NUM_NODES 值。請確認節點數量設為非零值。

      在許多情況下,執行個體中的每個叢集都應有相同數量的節點,但也有例外。瞭解節點和複製功能。

    • STORAGE_TYPE: 叢集所使用的儲存類型。執行個體中的每一個叢集必須使用相同的儲存空間類型。接受 SSD 和 HDD 值。

  3. (選用) 查看預設應用程式設定檔中的複製設定,確認是否符合您的複製用途。您可能需要更新預設應用程式設定檔或建立自訂應用程式設定檔。

C++

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

namespace cbta = ::google::cloud::bigtable_admin;
using ::google::cloud::future;
using ::google::cloud::Location;
using ::google::cloud::Project;
using ::google::cloud::StatusOr;
[](cbta::BigtableInstanceAdminClient instance_admin,
   std::string const& project_id, std::string const& instance_id,
   std::string const& zone) {
  auto const project = Project(project_id);
  std::string project_name = project.FullName();
  std::string cluster_id = instance_id + "-c1";

  google::bigtable::admin::v2::Instance in;
  in.set_type(google::bigtable::admin::v2::Instance::PRODUCTION);
  in.set_display_name("Put description here");

  google::bigtable::admin::v2::Cluster cluster;
  cluster.set_location(Location(project, zone).FullName());
  cluster.set_serve_nodes(3);
  cluster.set_default_storage_type(google::bigtable::admin::v2::HDD);

  std::map<std::string, google::bigtable::admin::v2::Cluster> cluster_map = {
      {cluster_id, std::move(cluster)}};

  future<StatusOr<google::bigtable::admin::v2::Instance>> instance_future =
      instance_admin.CreateInstance(project_name, instance_id, std::move(in),
                                    std::move(cluster_map));
  // Show how to perform additional work while the long running operation
  // completes. The application could use future.then() instead.
  std::cout << "Waiting for instance creation to complete " << std::flush;
  instance_future.wait_for(std::chrono::seconds(1));
  std::cout << '.' << std::flush;
  auto instance = instance_future.get();
  if (!instance) throw std::move(instance).status();
  std::cout << "DONE, details=" << instance->DebugString() << "\n";
}

C#

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

// Creates a production instance with "<intanceId>-prod" instance ID,
// with cluster ID "ssd-cluster1", 3 nodes and location us-east1-b.
displayName += " Prod"; // Display name is for display purposes only. It doesn't have to equal instanceId and can be amended after instance is created.
string instanceId = Regex.Replace(displayName, @"[^A-Za-z0-9_\.~]+", "-").ToLower();

// Please refer to the link below for the full list of available locations:
// https://cloud.google.com/bigtable/docs/locations
string zone1 = "us-east1-b";

// The instance to create.
Instance myInstance = new Instance
{
    DisplayName = displayName,
    // You can choose DEVELOPMENT or PRODUCTION type here.
    // If not set, will default to PRODUCTION type.
    // Instance type can be upgraded from DEVELOPMENT to PRODUCTION but cannot be dowgraded after the instance is created.
    Type = Instance.Types.Type.Production,
    Labels = { { "prod-label", "prod-label" } }
};

// The first cluster to be created within the instance.
Cluster myCluster1 = new Cluster
{
    // You can choose SSD or HDD storage type here: StorageType.Ssd or StorageType.Hdd.
    // Cluster storage type can not be changed after the instance is created.
    // If not set will default to SSD type.
    DefaultStorageType = StorageType.Ssd,
    LocationAsLocationName = new LocationName(projectId, zone1),
    // Serve Nodes count can only be set if PRODUCTION type instance is being created.
    // Minimum count of 3 serve nodes must be specified.
    // Serve Nodes count can be increased and decreased after an instance is created.
    ServeNodes = 3
};

// Initialize request argument(s).
CreateInstanceRequest request = new CreateInstanceRequest
{
    ParentAsProjectName = new ProjectName(projectId),
    Instance = myInstance,
    InstanceId = instanceId,
    // Must specify at lease one cluster.
    // Only PRODUCTION type instance can be created with more than one cluster.
    // Currently all clusters must have the same storage type.
    // Clusters must be set to different locations.
    Clusters = { { "ssd-cluster1", myCluster1 } }
};

try
{
    // Make a request.
    Operation<Instance, CreateInstanceMetadata> createInstanceResponse =
        bigtableInstanceAdminClient.CreateInstance(request);
    Console.WriteLine("Waiting for operation to complete...");

    // Poll until the returned long-running operation is complete
    Operation<Instance, CreateInstanceMetadata> completedResponse =
        createInstanceResponse.PollUntilCompleted();
}
catch (Exception ex)
{
    Console.WriteLine($"Exception while creating {displayName} instance");
    Console.WriteLine(ex.Message);
}

Go

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

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

// Instance admin is a sample program demonstrating use of the Cloud Bigtable client
// library to perform basic instance admin operations.
package main

import (
	"context"
	"flag"
	"fmt"
	"io"
	"os"

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

func main() {
	projectID := "my-project-id" // The Google Cloud Platform project ID
	instanceID := "my-bigtable-instance"
	clusterID := "my-cluster"
	zone := "us-central1-b"

	// Allow overriding with flags
	flag.StringVar(&projectID, "project", projectID, "The Google Cloud Platform project ID.")
	flag.StringVar(&instanceID, "instance", instanceID, "The Google Cloud Bigtable instance ID to create.")
	flag.StringVar(&zone, "zone", zone, "The zone for the initial cluster.")
	flag.Parse()

	if err := createInstance(os.Stdout, projectID, instanceID, clusterID, zone); err != nil {
		fmt.Fprintf(os.Stderr, "Error creating instance: %v", err)
	}
}

func createInstance(w io.Writer, projectID, instanceID, clusterID, zone string) error {
	ctx := context.Background()

	instanceAdminClient, err := bigtable.NewInstanceAdminClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("bigtable.NewInstanceAdminClient: %w", err)
	}
	defer instanceAdminClient.Close()

	// These are placeholders. You must create these in your GCP Organization/Project first.
	// See [Creating and managing tags](https://docs.cloud.google.com/bigtable/docs/tags) for
	// more information on creating a tag.
	// tagKey := "tagKeys/12345"
	// tagValue := "tagValues/56789"

	instanceConf := &bigtable.InstanceConf{
		InstanceId:   instanceID,
		DisplayName:  instanceID,
		ClusterId:    clusterID,
		NumNodes:     1,
		InstanceType: bigtable.PRODUCTION,
		StorageType:  bigtable.SSD,
		Zone:         zone,
		// The 'Tags' field is optional. Uncomment the lines below (and the tagKey, tagValue lines above)
		// only if you want to create an instance with tags.
		// Ensure the tagKey and tagValue exist in your GCP project.
		// Tags: map[string]string{tagKey: tagValue},
	}

	fmt.Fprintf(w, "Creating instance %s with cluster %s in %s...\n", instanceID, clusterID, zone)

	if err := instanceAdminClient.CreateInstance(ctx, instanceConf); err != nil {
		return fmt.Errorf("CreateInstance: %w", err)
	}

	fmt.Fprintf(w, "Instance %s created successfully.\n", instanceID)
	return nil
}

Java

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

// Creates a Production Instance with the ID "ssd-instance",
// cluster id "ssd-cluster", 3 nodes and location "us-central1-f".
String parent = "projects/" + projectId;
Instance.Builder instanceObjBuilder =
    Instance.newBuilder()
        .setDisplayName(instanceId)
        .setType(Instance.Type.PRODUCTION)
        .putLabels("department", "accounting");

if (createWithTags) {
  System.out.println("Enabling tags for instance creation.");
  // These are placeholders. You must create these in your GCP Organization/Project first.
  String tagKey = "tagKeys/12345";
  String tagValue = "tagValues/6789";
  instanceObjBuilder.putTags(tagKey, tagValue);
}
Instance instanceObj = instanceObjBuilder.build();

Cluster clusterObj =
    Cluster.newBuilder()
        .setLocation("projects/" + projectId + "/locations/us-central1-f")
        .setServeNodes(3)
        .setDefaultStorageType(StorageType.SSD)
        .build();
CreateInstanceRequest request =
    CreateInstanceRequest.newBuilder()
        .setParent(parent)
        .setInstanceId(instanceId)
        .setInstance(instanceObj)
        .putClusters(clusterId, clusterObj)
        .build();
// Creates a production instance with the given request.
try {
  Instance instance = adminClient.createInstanceAsync(request).get();
  System.out.printf("PRODUCTION type instance %s created successfully%n", instance.getName());
} catch (Exception e) {
  System.err.println("Failed to create instance: " + e.getMessage());
  throw new RuntimeException(e);
}

Node.js

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

// Creates a Production Instance with the ID "ssd-instance"
// with cluster id "ssd-cluster", 3 nodes and location us-central1-f
const {BigtableInstanceAdminClient} = require('@google-cloud/bigtable').v2;
const instanceAdminClient = new BigtableInstanceAdminClient();
const projectId = await instanceAdminClient.getProjectId();

const instanceOptions = {
  parent: `projects/${projectId}`,
  instanceId: instanceID,
  instance: {
    displayName: instanceID,
    labels: {'prod-label': 'prod-label'},
    type: 'PRODUCTION',
  },
  clusters: {
    [clusterID]: {
      location: `projects/${projectId}/locations/us-central1-f`,
      serveNodes: 3,
      defaultStorageType: 'SSD',
    },
  },
};

// Create production instance with given options
const [prodInstance, operation] =
  await instanceAdminClient.createInstance(instanceOptions);
await operation.promise();
console.log(`Created Instance: ${prodInstance.name}`);

PHP

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

use Exception;
use Google\ApiCore\ApiException;
use Google\Cloud\Bigtable\Admin\V2\Client\BigtableInstanceAdminClient;
use Google\Cloud\Bigtable\Admin\V2\Cluster;
use Google\Cloud\Bigtable\Admin\V2\CreateInstanceRequest;
use Google\Cloud\Bigtable\Admin\V2\GetInstanceRequest;
use Google\Cloud\Bigtable\Admin\V2\Instance;
use Google\Cloud\Bigtable\Admin\V2\Instance\Type as InstanceType;
use Google\Cloud\Bigtable\Admin\V2\StorageType;

/**
 * Create a production Bigtable instance
 *
 * @param string $projectId The Google Cloud project ID
 * @param string $instanceId The ID of the Bigtable instance to be generated
 * @param string $clusterId The ID of the cluster to be generated
 * @param string $locationId The Bigtable region ID where you want your instance to reside
 */
function create_production_instance(
    string $projectId,
    string $instanceId,
    string $clusterId,
    string $locationId = 'us-east1-b'
): void {
    $instanceAdminClient = new BigtableInstanceAdminClient();

    $projectName = $instanceAdminClient->projectName($projectId);
    $instanceName = $instanceAdminClient->instanceName($projectId, $instanceId);

    $serveNodes = 3;
    $storageType = StorageType::SSD;
    $production = InstanceType::PRODUCTION;
    $labels = ['prod-label' => 'prod-label'];

    $instance = new Instance();
    $instance->setDisplayName($instanceId);

    $instance->setLabels($labels);
    $instance->setType($production);

    $cluster = new Cluster();
    $cluster->setDefaultStorageType($storageType);
    $locationName = $instanceAdminClient->locationName($projectId, $locationId);
    $cluster->setLocation($locationName);
    $cluster->setServeNodes($serveNodes);
    $clusters = [
        $clusterId => $cluster
    ];
    try {
        $getInstanceRequest = (new GetInstanceRequest())
            ->setName($instanceName);
        $instanceAdminClient->getInstance($getInstanceRequest);
        printf('Instance %s already exists.' . PHP_EOL, $instanceId);
        throw new Exception(sprintf('Instance %s already exists.' . PHP_EOL, $instanceId));
    } catch (ApiException $e) {
        if ($e->getStatus() === 'NOT_FOUND') {
            printf('Creating an Instance: %s' . PHP_EOL, $instanceId);
            $createInstanceRequest = (new CreateInstanceRequest())
                ->setParent($projectName)
                ->setInstanceId($instanceId)
                ->setInstance($instance)
                ->setClusters($clusters);
            $operationResponse = $instanceAdminClient->createInstance($createInstanceRequest);
            $operationResponse->pollUntilComplete();
            if (!$operationResponse->operationSucceeded()) {
                print('Error: ' . $operationResponse->getError()->getMessage());
            } else {
                printf('Instance %s created.', $instanceId);
            }
        } else {
            throw $e;
        }
    }
}

Python

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

cluster = instance.cluster(
    cluster_id,
    location_id=location_id,
    serve_nodes=serve_nodes,
    default_storage_type=storage_type,
)
if not instance.exists():
    print("\nCreating an instance")
    # Create instance with given options
    operation = instance.create(clusters=[cluster])
    # Ensure the operation completes.
    operation.result(timeout=480)
    print("\nCreated instance: {}".format(instance_id))

小茹

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

# instance_id      = "my-instance"
# cluster_id       = "my-cluster"
# cluster_location = "us-east1-b"
puts "Creating a PRODUCTION Instance"
job = bigtable.create_instance(
  instance_id,
  display_name: "Sample production instance",
  labels:       { "env": "production" },
  type:         :PRODUCTION # Optional as default type is :PRODUCTION
) do |clusters|
  clusters.add cluster_id, cluster_location, nodes: 3, storage_type: :SSD
end

job.wait_until_done!
instance = job.instance
puts "Created Instance: #{instance.instance_id}"

後續步驟