Mettre à jour une règle de récupération de mémoire

Mettre à jour une règle de récupération de mémoire de famille de colonnes.

En savoir plus

Pour obtenir une documentation détaillée incluant cet exemple de code, consultez les articles suivants :

Exemple de code

C++

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la page Bibliothèques clientes Bigtable.

Pour vous authentifier auprès de Bigtable, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

namespace cbt = ::google::cloud::bigtable;
namespace cbta = ::google::cloud::bigtable_admin;
using ::google::bigtable::admin::v2::ModifyColumnFamiliesRequest;
using ::google::cloud::StatusOr;
[](cbta::BigtableTableAdminClient admin, std::string const& project_id,
   std::string const& instance_id, std::string const& table_id,
   std::string const& family_name) {
  std::string table_name = cbt::TableName(project_id, instance_id, table_id);

  ModifyColumnFamiliesRequest::Modification mod;
  mod.set_id(family_name);
  mod.mutable_update()->mutable_gc_rule()->set_max_num_versions(1);

  StatusOr<google::bigtable::admin::v2::Table> schema =
      admin.ModifyColumnFamilies(table_name, {std::move(mod)});

  if (!schema) throw std::move(schema).status();
  std::cout << "Schema modified to: " << schema->DebugString() << "\n";
}

C#

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la page Bibliothèques clientes Bigtable.

Pour vous authentifier auprès de Bigtable, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

// Update the column family metadata to update the GC rule.
// Initialize request argument(s).
// Updated column family GC rule.
GcRule maxVersionsRule = new GcRule { MaxNumVersions = 1 };

// Column family to create
ColumnFamily columnFamily = new ColumnFamily { GcRule = maxVersionsRule };

TableName tableName = new TableName(projectId, instanceId, tableId);

// Modification to update column family
ModifyColumnFamiliesRequest.Types.Modification modification = new ModifyColumnFamiliesRequest.Types.Modification
{
    Update = columnFamily,
    Id = "cf1"
};

ModifyColumnFamiliesRequest request = new ModifyColumnFamiliesRequest
{
    TableName = tableName,
    Modifications = { modification }
};
try
{
    // Make the request
    Table response = bigtableTableAdminClient.ModifyColumnFamilies(request);
    Console.WriteLine("Updated column family");
}
catch (Exception ex)
{
    Console.WriteLine($"Error updating column family {ex.Message}");
}

Go

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la page Bibliothèques clientes Bigtable.

Pour vous authentifier auprès de Bigtable, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

import (
	"context"
	"fmt"
	"io"

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

func updateGCRule(w io.Writer, projectID, instanceID string, tableName string) error {
	// projectID := "my-project-id"
	// instanceID := "my-instance-id"
	// tableName := "my-table-name"

	ctx := context.Background()

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

	columnFamilyName := "cf1"
	// Update the column family cf1 to update the GC rule.
	policy := bigtable.MaxVersionsPolicy(1)
	if err := adminClient.SetGCPolicy(ctx, tableName, columnFamilyName, policy); err != nil {
		return fmt.Errorf("SetGCPolicy(%s): %w", policy, err)
	}

	fmt.Fprintf(w, "Updated column family %s GC rule with policy: %v\n", columnFamilyName, policy)
	return nil
}

Java

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la page Bibliothèques clientes Bigtable.

Pour vous authentifier auprès de Bigtable, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

// Updates the column family metadata to update the GC rule.
// Updates a column family GC rule.
VersionRule versionRule = GCRULES.maxVersions(1);
try {
  // ModifyColumnFamiliesRequest can be used both for adding and modifying families, here it is
  // being used to modify a family
  // Updates column family with given GC rule.
  ModifyColumnFamiliesRequest updateRequest =
      ModifyColumnFamiliesRequest.of(tableId).updateFamily(COLUMN_FAMILY_1, versionRule);
  adminClient.modifyFamilies(updateRequest);
  System.out.printf("Column family %s GC rule updated%n", COLUMN_FAMILY_1);
} catch (NotFoundException e) {
  System.err.println("Failed to modify a non-existent column family: " + e.getMessage());
}

Node.js

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la page Bibliothèques clientes Bigtable.

Pour vous authentifier auprès de Bigtable, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

// Update the column family metadata to update the GC rule

// Create a reference to the column family
family = table.family('cf1');

// Update a column family GC rule
const updatedMetadata = {
  rule: {
    versions: 1,
  },
};

const [apiResponse] = await family.setMetadata(updatedMetadata);
console.log(`Updated GC rule: ${JSON.stringify(apiResponse)}`);

PHP

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la page Bibliothèques clientes Bigtable.

Pour vous authentifier auprès de Bigtable, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

use Google\ApiCore\ApiException;
use Google\Cloud\Bigtable\Admin\V2\Client\BigtableTableAdminClient;
use Google\Cloud\Bigtable\Admin\V2\ColumnFamily;
use Google\Cloud\Bigtable\Admin\V2\GcRule;
use Google\Cloud\Bigtable\Admin\V2\ModifyColumnFamiliesRequest;
use Google\Cloud\Bigtable\Admin\V2\ModifyColumnFamiliesRequest\Modification;

/**
 * Update the GC Rule for an existing column family in the table
 *
 * @param string $projectId The Google Cloud project ID
 * @param string $instanceId The ID of the Bigtable instance
 * @param string $tableId The ID of the table where the rule needs to be updated
 * @param string $familyId The ID of the column family
 */
function update_gc_rule(
    string $projectId,
    string $instanceId,
    string $tableId,
    string $familyId = 'cf3'
): void {
    $tableAdminClient = new BigtableTableAdminClient();
    $tableName = $tableAdminClient->tableName($projectId, $instanceId, $tableId);
    $columnFamily1 = new ColumnFamily();

    printf('Updating column family %s GC rule...' . PHP_EOL, $familyId);
    $columnFamily1->setGcRule((new GcRule())->setMaxNumVersions(1));
    // Update the column family with ID $familyId to update the GC rule
    $columnModification = new Modification();
    $columnModification->setId($familyId);
    $columnModification->setUpdate($columnFamily1);

    try {
        $modifyColumnFamiliesRequest = (new ModifyColumnFamiliesRequest())
            ->setName($tableName)
            ->setModifications([$columnModification]);
        $tableAdminClient->modifyColumnFamilies($modifyColumnFamiliesRequest);
    } catch (ApiException $e) {
        if ($e->getStatus() === 'NOT_FOUND') {
            printf('Column family %s does not exist.' . PHP_EOL, $familyId);
            return;
        }
        throw $e;
    }

    printf('Print column family %s GC rule after update...' . PHP_EOL, $familyId);
    printf('Column Family: ' . $familyId . PHP_EOL);
    printf('%s' . PHP_EOL, $columnFamily1->serializeToJsonString());
}

Python

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la page Bibliothèques clientes Bigtable.

Pour vous authentifier auprès de Bigtable, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

print("Updating column family cf1 GC rule...")
# Update the column family cf1 to update the GC rule
column_family1 = table.column_family("cf1", column_family.MaxVersionsGCRule(1))
column_family1.update()
print("Updated column family cf1 GC rule\n")

Ruby

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la page Bibliothèques clientes Bigtable.

Pour vous authentifier auprès de Bigtable, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

gc_rule = Google::Cloud::Bigtable::GcRule.max_versions 1
column_families = table.column_families do |cfs|
  cfs.update "cf1", gc_rule: gc_rule
end
p column_families["cf1"]

Étapes suivantes

Pour rechercher et filtrer des exemples de code pour d'autres produits Google Cloud, consultez l'exemple de navigateur Google Cloud.