Política de coleta de lixo de intersecção

Crie um grupo de colunas com uma política de coleta de lixo de intersecção (idade e versões).

Mais informações

Para ver a documentação detalhada que inclui este exemplo de código, consulte:

Exemplo de código

C++

Para saber como instalar e usar a biblioteca de cliente para o Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

Ver no GitHub (em inglês) Feedback
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);
  auto constexpr kSecondsPerDay =
      std::chrono::seconds(std::chrono::hours(24)).count();

  ModifyColumnFamiliesRequest::Modification mod;
  mod.set_id(family_name);
  auto& gc_int =
      *mod.mutable_create()->mutable_gc_rule()->mutable_intersection();
  gc_int.add_rules()->set_max_num_versions(1);
  gc_int.add_rules()->mutable_max_age()->set_seconds(5 * kSecondsPerDay);

  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#

Para saber como instalar e usar a biblioteca de cliente para o Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

Ver no GitHub (em inglês) Feedback
// Create a column family with GC policy to drop data that matches all conditions.
// Initialize request argument(s).
// GC rule: Drop cells older than 5 days AND older than the most recent 2 versions.
GcRule.Types.Intersection intersectionRule = new GcRule.Types.Intersection
{
    Rules =
    {
        new GcRule { MaxNumVersions = 2 },
        new GcRule { MaxAge = Duration.FromTimeSpan(TimeSpan.FromDays(5)) }
    }
};
GcRule gcRule = new GcRule { Intersection = intersectionRule };

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

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

// Modification to create column family
ModifyColumnFamiliesRequest.Types.Modification modification = new ModifyColumnFamiliesRequest.Types.Modification
{
    Create = columnFamily,
    Id = "cf4"
};

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

Go

Para saber como instalar e usar a biblioteca de cliente para o Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

Ver no GitHub (em inglês) Feedback
import (
	"context"
	"fmt"
	"io"
	"time"

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

func createFamilyGCIntersect(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 := "cf4"
	if err := adminClient.CreateColumnFamily(ctx, tableName, columnFamilyName); err != nil {
		return fmt.Errorf("CreateColumnFamily(%s): %w", columnFamilyName, err)
	}

	// GC rule: Drop cells older than 5 days AND older than the most recent 2 versions
	maxAge := time.Hour * 24 * 5
	maxAgePolicy := bigtable.MaxAgePolicy(maxAge)
	policy := bigtable.IntersectionPolicy(bigtable.MaxVersionsPolicy(2), maxAgePolicy)
	if err := adminClient.SetGCPolicy(ctx, tableName, columnFamilyName, policy); err != nil {
		return fmt.Errorf("SetGCPolicy(%s): %w", policy, err)
	}

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

Java

Para saber como instalar e usar a biblioteca de cliente para o Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

Ver no GitHub (em inglês) Feedback
// Creates a column family with GC policy to drop data that matches all conditions.

// Defines a GC rule to drop cells older than 5 days AND older than the most recent 2 versions.
DurationRule maxAgeRule = GCRULES.maxAge(5, TimeUnit.DAYS);
VersionRule versionRule = GCRULES.maxVersions(2);
IntersectionRule intersectionRule = GCRULES.intersection().rule(maxAgeRule).rule(versionRule);

// Creates column family with given GC rule.
try {
  // ModifyColumnFamiliesRequest can be used both for adding and modifying families, here it is
  // being used to add a family
  ModifyColumnFamiliesRequest columnFamiliesRequest =
      ModifyColumnFamiliesRequest.of(tableId).addFamily(COLUMN_FAMILY_4, intersectionRule);
  adminClient.modifyFamilies(columnFamiliesRequest);
  System.out.println("Created column family: " + COLUMN_FAMILY_4);
} catch (AlreadyExistsException e) {
  System.err.println(
      "Failed to create column family with rule, already exists: " + e.getMessage());
}

Node.js

Para saber como instalar e usar a biblioteca de cliente para o Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

Ver no GitHub (em inglês) Feedback
// Create a column family with GC policy to drop data that matches all conditions

// GC rule: Drop cells older than 5 days AND older than the most recent 2 versions
const intersectionRule = {
  rule: {
    versions: 2,
    age: {
      seconds: 60 * 60 * 24 * 5,
      nanos: 0,
    },
    intersection: true,
  },
};
[family] = await table.createFamily('cf4', intersectionRule);
console.log(`Created column family ${family.id}`);

PHP

Para saber como instalar e usar a biblioteca de cliente para o Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

Ver no GitHub (em inglês) Feedback
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\GcRule\Intersection as GcRuleIntersection;
use Google\Cloud\Bigtable\Admin\V2\ModifyColumnFamiliesRequest;
use Google\Cloud\Bigtable\Admin\V2\ModifyColumnFamiliesRequest\Modification;
use Google\Protobuf\Duration;

/**
 * Create a new column family with an intersection GC rule
 *
 * @param string $projectId The Google Cloud project ID
 * @param string $instanceId The ID of the Bigtable instance where the table resides
 * @param string $tableId The ID of the table in which the rule needs to be created
 */
function create_family_gc_intersection(
    string $projectId,
    string $instanceId,
    string $tableId
): void {
    $tableAdminClient = new BigtableTableAdminClient();

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

    print('Creating column family cf4 with Intersection GC rule...' . PHP_EOL);
    $columnFamily4 = new ColumnFamily();

    $intersectionRule = new GcRuleIntersection();
    $intersectionArray = [
        (new GcRule())->setMaxAge((new Duration())->setSeconds(3600 * 24 * 5)),
        (new GcRule())->setMaxNumVersions(2)
    ];
    $intersectionRule->setRules($intersectionArray);

    $intersection = new GcRule();
    $intersection->setIntersection($intersectionRule);

    $columnFamily4->setGCRule($intersection);

    $columnModification = new Modification();
    $columnModification->setId('cf4');
    $columnModification->setCreate($columnFamily4);
    $modifyColumnFamiliesRequest = (new ModifyColumnFamiliesRequest())
        ->setName($tableName)
        ->setModifications([$columnModification]);
    $tableAdminClient->modifyColumnFamilies($modifyColumnFamiliesRequest);

    print('Created column family cf4 with Union GC rule' . PHP_EOL);
}

Python

Para saber como instalar e usar a biblioteca de cliente para o Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

Ver no GitHub (em inglês) Feedback
    print("Creating column family cf4 with Intersection GC rule...")
    # Create a column family with GC policy to drop data that matches
    # all conditions
    # GC rule: Drop cells older than 5 days AND older than the most
    # recent 2 versions
    intersection_rule = column_family.GCRuleIntersection(
        [
            column_family.MaxAgeGCRule(datetime.timedelta(days=5)),
            column_family.MaxVersionsGCRule(2),
        ]
    )

    column_family4 = table.column_family("cf4", intersection_rule)
    column_family4.create()
    print("Created column family cf4 with Intersection GC rule.")

Ruby

Para saber como instalar e usar a biblioteca de cliente para o Bigtable, consulte Bibliotecas de cliente do Bigtable.

Para autenticar no Bigtable, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

Ver no GitHub (em inglês) Feedback
# Create a column family with GC policy to drop data that matches at least
# one condition
max_age_rule = Google::Cloud::Bigtable::GcRule.max_age 60 * 60 * 24 * 5
max_versions_rule = Google::Cloud::Bigtable::GcRule.max_versions 2
intersection_gc_rule = Google::Cloud::Bigtable::GcRule.intersection max_age_rule, max_versions_rule
column_families = table.column_families do |cfs|
  cfs.add "cf4", gc_rule: intersection_gc_rule
end
family = column_families["cf4"]

A seguir

Para pesquisar e filtrar amostras de código para outros produtos do Google Cloud, consulte o navegador de amostra do Google Cloud.