Create a cluster

Create a cluster in the current project, given an instance ID.

Code sample

C#

To learn how to install and use the client library for Bigtable, see Bigtable client libraries.

// Create an additional cluster with cluster id "ssd-cluster2" with 3 nodes and location us-east1-d.
// Additional cluster can only be created in PRODUCTION type instance.
// Additional cluster must have same storage type as existing cluster.
// Please read about routing_policy for more information on mutli cluster instances.
// https://cloud.google.com/bigtable/docs/reference/admin/rpc/google.bigtable.admin.v2#google.bigtable.admin.v2.AppProfile.MultiClusterRoutingUseAny
// Cluster to be created within the instance.
Cluster myCluster2 = new Cluster
{
    DefaultStorageType = StorageType.Ssd,
    LocationAsLocationName = new LocationName(projectId, zone2),
    ServeNodes = 3
};
// Initialize request argument(s).
CreateClusterRequest request = new CreateClusterRequest
{
    ParentAsInstanceName = new InstanceName(projectId, instanceId),
    ClusterId = "ssd-cluster2",
    Cluster = myCluster2
};
try
{
    // Make the request
    Console.WriteLine("Waiting for operation to complete...");
    Operation<Cluster, CreateClusterMetadata> response = bigtableInstanceAdminClient.CreateCluster(request);
    // Poll until the returned long-running operation is complete
    Operation<Cluster, CreateClusterMetadata> completedResponse = response.PollUntilCompleted();

}
catch (Exception ex)
{
    Console.WriteLine($"Exception creating additional cluster {request.ClusterId} in instance {instanceId}");
    Console.WriteLine(ex.Message);
}

C++

To learn how to install and use the client library for Bigtable, see Bigtable client libraries.

namespace cbt = ::google::cloud::bigtable;
using ::google::cloud::future;
using ::google::cloud::StatusOr;
[](cbt::InstanceAdmin instance_admin, std::string const& instance_id,
   std::string const& cluster_id, std::string const& zone) {
  auto cluster_config = cbt::ClusterConfig(zone, 3, cbt::ClusterConfig::HDD);
  future<StatusOr<google::bigtable::admin::v2::Cluster>> cluster_future =
      instance_admin.CreateCluster(cluster_config, instance_id, cluster_id);

  // Applications can wait asynchronously, in this example we just block.
  auto cluster = cluster_future.get();
  if (!cluster) throw std::runtime_error(cluster.status().message());
  std::cout << "Successfully created cluster " << cluster->name() << "\n";
}

Java

To learn how to install and use the client library for Bigtable, see Bigtable client libraries.

try {
  adminClient.createCluster(
      CreateClusterRequest.of(instanceId, CLUSTER)
          .setZone("us-central1-c")
          .setServeNodes(3)
          .setStorageType(StorageType.SSD));
  System.out.printf("Cluster: %s created successfully%n", CLUSTER);
} catch (AlreadyExistsException e) {
  System.err.println("Failed to add cluster, already exists: " + e.getMessage());
}

Node.js

To learn how to install and use the client library for Bigtable, see Bigtable client libraries.

const clusterOptions = {
  location: 'us-central1-c',
  nodes: 3,
  storage: 'ssd',
};

const [cluster] = await instance.createCluster(clusterID, clusterOptions);
console.log(`Cluster created: ${cluster.id}`);

PHP

To learn how to install and use the client library for Bigtable, see Bigtable client libraries.

use Google\Cloud\Bigtable\Admin\V2\BigtableInstanceAdminClient;
use Google\Cloud\Bigtable\Admin\V2\Cluster;
use Google\Cloud\Bigtable\Admin\V2\StorageType;
use Google\ApiCore\ApiException;

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

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

    printf("Adding Cluster to Instance %s" . PHP_EOL, $instanceId);
    try {
        $instanceAdminClient->getInstance($instanceName);
    } catch (ApiException $e) {
        if ($e->getStatus() === 'NOT_FOUND') {
            printf("Instance %s does not exists." . PHP_EOL, $instanceId);
            return;
        } else {
            throw $e;
        }
    }
    printf("Listing Clusters:" . PHP_EOL);

    $storage_type = StorageType::SSD;
    $serve_nodes = 3;

    $clustersBefore = $instanceAdminClient->listClusters($instanceName)->getClusters();
    $clusters = $clustersBefore->getIterator();
    foreach ($clusters as $cluster) {
        print($cluster->getName() . PHP_EOL);
    }

    $cluster = new Cluster();
    $cluster->setServeNodes($serve_nodes);
    $cluster->setDefaultStorageType($storage_type);
    $cluster->setLocation(
        $instanceAdminClient->locationName(
            $projectId,
            $locationId
        )
    );
    try {
        $instanceAdminClient->getCluster($clusterName);
        printf("Cluster %s already exists, aborting...", $clusterId);
    } catch (ApiException $e) {
        if ($e->getStatus() === 'NOT_FOUND') {
            $operationResponse = $instanceAdminClient->createCluster($instanceName, $clusterId, $cluster);

            $operationResponse->pollUntilComplete();
            if ($operationResponse->operationSucceeded()) {
                $result = $operationResponse->getResult();
                printf("Cluster created: %s", $clusterId);
            } else {
                $error = $operationResponse->getError();
                printf("Cluster not created: %s", $error);
            }
        } else {
            throw $e;
        }
    }
}

Python

To learn how to install and use the client library for Bigtable, see Bigtable client libraries.

print("\nListing clusters...")
for cluster in instance.list_clusters()[0]:
    print(cluster.cluster_id)
cluster = instance.cluster(
    cluster_id,
    location_id=location_id,
    serve_nodes=serve_nodes,
    default_storage_type=storage_type,
)
if cluster.exists():
    print("\nCluster not created, as {} already exists.".format(cluster_id))
else:
    operation = cluster.create()
    # Ensure the operation completes.
    operation.result(timeout=60)
    print("\nCluster created: {}".format(cluster_id))

Ruby

To learn how to install and use the client library for Bigtable, see Bigtable client libraries.

# cluster_id       = "my-cluster"
# cluster_location = "us-east1-b"
job = instance.create_cluster(
  cluster_id,
  cluster_location,
  nodes:        3,
  storage_type: :SSD
)

job.wait_until_done!
cluster = job.cluster

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.