Crear un clúster

Crea un clúster en el proyecto actual a partir de un ID de instancia.

Código de ejemplo

C++

Para saber cómo instalar y usar la biblioteca de cliente de Bigtable, consulta el artículo Bibliotecas de cliente de Bigtable.

Para autenticarte en Bigtable, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

namespace cbt = ::google::cloud::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& cluster_id, std::string const& zone) {
  auto const project = Project(project_id);
  std::string instance_name = cbt::InstanceName(project_id, instance_id);

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

  future<StatusOr<google::bigtable::admin::v2::Cluster>> cluster_future =
      instance_admin.CreateCluster(instance_name, cluster_id, std::move(c));

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

C#

Para saber cómo instalar y usar la biblioteca de cliente de Bigtable, consulta el artículo Bibliotecas de cliente de Bigtable.

Para autenticarte en Bigtable, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

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

Java

Para saber cómo instalar y usar la biblioteca de cliente de Bigtable, consulta el artículo Bibliotecas de cliente de Bigtable.

Para autenticarte en Bigtable, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

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

Para saber cómo instalar y usar la biblioteca de cliente de Bigtable, consulta el artículo Bibliotecas de cliente de Bigtable.

Para autenticarte en Bigtable, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

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

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

PHP

Para saber cómo instalar y usar la biblioteca de cliente de Bigtable, consulta el artículo Bibliotecas de cliente de Bigtable.

Para autenticarte en Bigtable, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

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\CreateClusterRequest;
use Google\Cloud\Bigtable\Admin\V2\GetClusterRequest;
use Google\Cloud\Bigtable\Admin\V2\GetInstanceRequest;
use Google\Cloud\Bigtable\Admin\V2\ListClustersRequest;
use Google\Cloud\Bigtable\Admin\V2\StorageType;

/**
 * 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 {
        $getInstanceRequest = (new GetInstanceRequest())
            ->setName($instanceName);
        $instanceAdminClient->getInstance($getInstanceRequest);
    } 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;
    $listClustersRequest = (new ListClustersRequest())
        ->setParent($instanceName);

    $clustersBefore = $instanceAdminClient->listClusters($listClustersRequest)->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 {
        $getClusterRequest = (new GetClusterRequest())
            ->setName($clusterName);
        $instanceAdminClient->getCluster($getClusterRequest);
        printf('Cluster %s already exists, aborting...', $clusterId);
    } catch (ApiException $e) {
        if ($e->getStatus() === 'NOT_FOUND') {
            $createClusterRequest = (new CreateClusterRequest())
                ->setParent($instanceName)
                ->setClusterId($clusterId)
                ->setCluster($cluster);
            $operationResponse = $instanceAdminClient->createCluster($createClusterRequest);

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

Python

Para saber cómo instalar y usar la biblioteca de cliente de Bigtable, consulta el artículo Bibliotecas de cliente de Bigtable.

Para autenticarte en Bigtable, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

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=480)
    print("\nCluster created: {}".format(cluster_id))

Ruby

Para saber cómo instalar y usar la biblioteca de cliente de Bigtable, consulta el artículo Bibliotecas de cliente de Bigtable.

Para autenticarte en Bigtable, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

# 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

Siguientes pasos

Para buscar y filtrar ejemplos de código de otros Google Cloud productos, consulta el Google Cloud navegador de ejemplos.