Crear tabla

Crea una tabla con una aplicación de “Hello World”.

Explora más

Para obtener documentación en la que se incluye esta muestra de código, consulta lo siguiente:

Muestra de código

C++

Si quieres obtener información sobre cómo instalar y usar la biblioteca cliente de Bigtable, consulta las bibliotecas cliente de Bigtable.

Para autenticarte en Bigtable, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

// Define the desired schema for the Table.
google::bigtable::admin::v2::Table t;
auto& families = *t.mutable_column_families();
families["family"].mutable_gc_rule()->set_max_num_versions(1);

// Create a table.
std::string instance_name = cbt::InstanceName(project_id, instance_id);
StatusOr<google::bigtable::admin::v2::Table> schema =
    table_admin.CreateTable(instance_name, table_id, std::move(t));

C#

Si quieres obtener información sobre cómo instalar y usar la biblioteca cliente de Bigtable, consulta las bibliotecas cliente de Bigtable.

Para autenticarte en Bigtable, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

// Create a table with a single column family.
Console.WriteLine($"Create new table: {tableId} with column family: {columnFamily}, instance: {instanceId}");

// Check whether a table with given TableName already exists.
if (!TableExist(bigtableTableAdminClient))
{
    bigtableTableAdminClient.CreateTable(
        new InstanceName(projectId, instanceId),
        tableId,
        new Table
        {
            Granularity = Table.Types.TimestampGranularity.Millis,
            ColumnFamilies =
            {
                {
                    columnFamily, new ColumnFamily
                    {
                        GcRule = new GcRule
                        {
                            MaxNumVersions = 1
                        }
                    }
                }
            }
        });
    // Confirm that table was created successfully.
    Console.WriteLine(TableExist(bigtableTableAdminClient)
        ? $"Table {tableId} created successfully\n"
        : $"There was a problem creating a table {tableId}");
}
else
{
    Console.WriteLine($"Table: {tableId} already exists");
}

Go

Si quieres obtener información sobre cómo instalar y usar la biblioteca cliente de Bigtable, consulta las bibliotecas cliente de Bigtable.

Para autenticarte en Bigtable, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

tables, err := adminClient.Tables(ctx)
if err != nil {
	log.Fatalf("Could not fetch table list: %v", err)
}

if !sliceContains(tables, tableName) {
	log.Printf("Creating table %s", tableName)
	if err := adminClient.CreateTable(ctx, tableName); err != nil {
		log.Fatalf("Could not create table %s: %v", tableName, err)
	}
}

tblInfo, err := adminClient.TableInfo(ctx, tableName)
if err != nil {
	log.Fatalf("Could not read info for table %s: %v", tableName, err)
}

if !sliceContains(tblInfo.Families, columnFamilyName) {
	if err := adminClient.CreateColumnFamily(ctx, tableName, columnFamilyName); err != nil {
		log.Fatalf("Could not create column family %s: %v", columnFamilyName, err)
	}
}

Java

Si quieres obtener información sobre cómo instalar y usar la biblioteca cliente de Bigtable, consulta las bibliotecas cliente de Bigtable.

Para autenticarte en Bigtable, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

// Checks if table exists, creates table if does not exist.
boolean exists = false;
try {
  adminClient.getTable(
      GetTableRequest.newBuilder()
          .setName("projects/" + projectId + "/instances/" + instanceId + "/tables/" + tableId)
          .setView(Table.View.NAME_ONLY)
          .build());
  exists = true;
} catch (NotFoundException e) {
  // ignore
}
if (!exists) {
  System.out.println("Creating table: " + tableId);
  String parent = "projects/" + projectId + "/instances/" + instanceId;
  CreateTableRequest request =
      CreateTableRequest.newBuilder()
          .setParent(parent)
          .setTableId(tableId)
          .setTable(
              Table.newBuilder()
                  .putColumnFamilies(COLUMN_FAMILY, ColumnFamily.getDefaultInstance())
                  .build())
          .build();
  adminClient.createTable(request);
  System.out.printf("Table %s created successfully%n", tableId);
}

PHP

Si quieres obtener información sobre cómo instalar y usar la biblioteca cliente de Bigtable, consulta las bibliotecas cliente de Bigtable.

Para autenticarte en Bigtable, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

$instanceName = $instanceAdminClient->instanceName($projectId, $instanceId);
$tableName = $tableAdminClient->tableName($projectId, $instanceId, $tableId);

// Check whether table exists in an instance.
// Create table if it does not exists.
$table = new Table();
printf('Creating a Table: %s' . PHP_EOL, $tableId);

try {
    $getTableRequest = (new GetTableRequest())
        ->setName($tableName)
        ->setView(View::NAME_ONLY);
    $tableAdminClient->getTable($getTableRequest);
    printf('Table %s already exists' . PHP_EOL, $tableId);
} catch (ApiException $e) {
    if ($e->getStatus() === 'NOT_FOUND') {
        printf('Creating the %s table' . PHP_EOL, $tableId);
        $createTableRequest = (new CreateTableRequest())
            ->setParent($instanceName)
            ->setTableId($tableId)
            ->setTable($table);

        $tableAdminClient->createtable($createTableRequest);
        $columnFamily = new ColumnFamily();
        $columnModification = new Modification();
        $columnModification->setId('cf1');
        $columnModification->setCreate($columnFamily);
        $modifyColumnFamiliesRequest = (new ModifyColumnFamiliesRequest())
            ->setName($tableName)
            ->setModifications([$columnModification]);
        $tableAdminClient->modifyColumnFamilies($modifyColumnFamiliesRequest);
        printf('Created table %s' . PHP_EOL, $tableId);
    } else {
        throw $e;
    }
}

Ruby

Si quieres obtener información sobre cómo instalar y usar la biblioteca cliente de Bigtable, consulta las bibliotecas cliente de Bigtable.

Para autenticarte en Bigtable, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

# This is the full resource name for the table. Use this name to make admin
# calls for the table, such as reading or deleting the resource.
table_name = table_client.table_path project: bigtable.project_id,
                                     instance: instance_id,
                                     table: table_id
begin
  # Attempt to get the table to see if it already exists
  table_client.get_table name: table_name
  puts "#{table_id} is already exists."
  exit 0
rescue Google::Cloud::NotFoundError
  # The table doesn't exist, so let's create it.
  # The following is the resource name for the table's instance.
  instance_name = table_client.instance_path project: bigtable.project_id,
                                             instance: instance_id
  # This is the configuration of the table's column families.
  table_config = {
    column_families: {
      column_family => {
        gc_rule: Google::Cloud::Bigtable::Admin::V2::GcRule.max_num_versions(1)
      }
    }
  }
  # Now call the API to create the table.
  table_client.create_table parent: instance_name,
                            table_id: table_id,
                            table: table_config
  puts "Table #{table_id} created."
end

¿Qué sigue?

Si quieres buscar y filtrar muestras de código para otros productos de Google Cloud , consulta el navegador de muestras deGoogle Cloud .