가비지 컬렉션 구성

이 페이지에서는 Bigtable에서 가비지 컬렉션 정책을 보고, 설정하고, 업데이트하는 방법을 보여줍니다. 이 페이지를 읽기 전에 가비지 컬렉션에 대한 내용을 숙지해야 합니다.

cbt CLI를 사용하기 전에 .cbtrc 파일을 만드는 단계를 포함하여 설정 안내를 따르세요.

현재 가비지 컬렉션 정책 보기

Google Cloud 콘솔 또는 cbt CLI를 사용하여 column family의 가비지 컬렉션 정책을 볼 수 있습니다.

콘솔

column family의 현재 가비지 컬렉션 정책을 보려면 다음 안내를 따르세요.

  1. Google Cloud 콘솔에서 Bigtable 인스턴스 목록을 엽니다.

    인스턴스 목록 열기

  2. 테이블을 보려는 인스턴스를 클릭합니다.

  3. 왼쪽 창에서 테이블을 클릭합니다.

    테이블 페이지에는 인스턴스의 테이블 목록이 표시됩니다.

  4. 테이블 행에서 수정을 클릭합니다.

  5. 보려는 column family 옆에 있는 열기를 클릭합니다.

  6. 가비지 컬렉션 정책 보기를 마치면 취소를 클릭하여 종료합니다.

cbt

다음 명령어를 실행하고 TABLE_ID를 유효한 테이블 ID로 대체하여 특정 테이블의 현재 가비지 컬렉션 정책을 찾을 수 있습니다.

cbt ls TABLE_ID

가비지 컬렉션 정책 설정

Google Cloud 콘솔, cbt CLI 또는 Cloud Bigtable 클라이언트 라이브러리를 사용하여 가비지 컬렉션 정책을 설정할 수 있습니다.

기간에 따른 가비지 컬렉션

다음 섹션에서는 column family 내 데이터의 최대 기간을 설정하는 방법을 보여줍니다.

콘솔

column family의 셀에 만료 시간을 설정하려면 다음 안내를 따르세요.

  1. Google Cloud 콘솔에서 Bigtable 인스턴스 목록을 엽니다.

    인스턴스 목록 열기

  2. 테이블을 보려는 인스턴스를 클릭합니다.

  3. 왼쪽 창에서 테이블을 클릭합니다.

    테이블 페이지에는 인스턴스의 테이블 목록이 표시됩니다.

  4. 수정을 클릭합니다.

  5. 수정할 column family 옆에 있는 열기를 클릭합니다.

  6. 기간 기반 정책을 선택합니다.

  7. 최대 기간 필드에 숫자를 입력하고 단위 드롭다운을 사용하여 시간 단위를 선택하여 기간을 입력합니다.

    예를 들어 30분 동안 column family의 데이터를 보관하려면 30을 입력하고 을 선택합니다.

  8. 저장을 클릭합니다.

cbt

이 예시에서는 cf1이라는 column family를 만들고 column family 내 데이터의 최대 기간을 5일로 설정합니다. 이는 이 column family의 모든 열에서 5일보다 오래된 타임스탬프가 있는 모든 데이터를 삭제하도록 Bigtable에 지시합니다.

cbt createfamily your-table cf1
cbt setgcpolicy your-table cf1 maxage=5d

Go

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"
	"time"

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

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

	// Set a garbage collection policy of 5 days.
	maxAge := time.Hour * 24 * 5
	policy := bigtable.MaxAgePolicy(maxAge)
	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

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

// Creates a column family with GC policy : maximum age
// where age = current time minus cell timestamp

// Defines the GC rule to retain data with max age of 5 days.
DurationRule maxAgeRule = GCRULES.maxAge(5, TimeUnit.DAYS);

// 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_1, maxAgeRule);
  adminClient.modifyFamilies(columnFamiliesRequest);
  System.out.println("Created column family: " + COLUMN_FAMILY_1);
} catch (AlreadyExistsException e) {
  System.err.println(
      "Failed to create column family with rule, already exists: " + e.getMessage());
}

Python

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    print("Creating column family cf1 with with MaxAge GC Rule...")
    # Create a column family with GC policy : maximum age
    # where age = current time minus cell timestamp

    # Define the GC rule to retain data with max age of 5 days
    max_age_rule = column_family.MaxAgeGCRule(datetime.timedelta(days=5))

    column_family1 = table.column_family("cf1", max_age_rule)
    column_family1.create()
    print("Created column family cf1 with MaxAge GC Rule.")

C#

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

// Create a column family with GC policy : maximum age
// where age = current time minus cell timestamp
// Initialize request argument(s).
// Define the GC rule to retain data with max age of 5 days
GcRule MaxAgeRule = new GcRule { MaxAge = Duration.FromTimeSpan(TimeSpan.FromDays(5.0)) };

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

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

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

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

C++

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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);
  mod.mutable_create()->mutable_gc_rule()->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";
}

Node.js

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

// Create a column family with GC policy : maximum age
// where age = current time minus cell timestamp

// Define the GC rule to retain data with max age of 5 days
const maxAgeRule = {
  rule: {
    age: {
      // Value must be atleast 1 millisecond
      seconds: 60 * 60 * 24 * 5,
      nanos: 0,
    },
  },
};

let [family] = await table.createFamily('cf1', maxAgeRule);
console.log(`Created column family ${family.id}`);

PHP

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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;
use Google\Protobuf\Duration;

/**
 * Create a new column family with a max age 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_max_age(
    string $projectId,
    string $instanceId,
    string $tableId
): void {
    $tableAdminClient = new BigtableTableAdminClient();

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

    print('Creating column family cf1 with MaxAge GC Rule...' . PHP_EOL);
    // Create a column family with GC policy : maximum age
    // where age = current time minus cell timestamp

    $columnFamily1 = new ColumnFamily();
    $duration = new Duration();
    $duration->setSeconds(3600 * 24 * 5);
    $MaxAgeRule = (new GcRule())->setMaxAge($duration);
    $columnFamily1->setGcRule($MaxAgeRule);

    $columnModification = new Modification();
    $columnModification->setId('cf1');
    $columnModification->setCreate($columnFamily1);
    $modifyColumnFamiliesRequest = (new ModifyColumnFamiliesRequest())
        ->setName($tableName)
        ->setModifications([$columnModification]);
    $tableAdminClient->modifyColumnFamilies($modifyColumnFamiliesRequest);
    print('Created column family cf1 with MaxAge GC Rule.' . PHP_EOL);
}

Ruby

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

# Create a column family with GC policy : maximum age
# where age = current time minus cell timestamp
# NOTE: Age value must be atleast 1 millisecond
max_age_rule = Google::Cloud::Bigtable::GcRule.max_age 60 * 60 * 24 * 5
column_families = table.column_families do |cfs|
  cfs.add "cf1", gc_rule: max_age_rule
end
family = column_families["cf1"]

버전 수에 따른 가비지 컬렉션

다음 섹션은 유지할 데이터의 버전 수 또는 셀 수를 명시하는 가비지 컬렉션 정책에 따라 column family를 만드는 방법을 보여줍니다.

콘솔

column family에 보관할 셀 또는 버전의 수를 설정하려면 다음 안내를 따르세요.

  1. Google Cloud 콘솔에서 Bigtable 인스턴스 목록을 엽니다.

    인스턴스 목록 열기

  2. 테이블을 보려는 인스턴스를 클릭합니다.

  3. 왼쪽 창에서 테이블을 클릭합니다.

    테이블 페이지에는 인스턴스의 테이블 목록이 표시됩니다.

  4. 테이블 행에서 수정을 클릭합니다.

  5. 수정할 column family 옆에 있는 열기를 클릭합니다.

  6. 버전 기반 정책을 선택합니다.

  7. column family의 열마다 보관할 셀 수를 입력합니다.

  8. 저장을 클릭합니다.

cbt

이 예시에서는 cf2라는 column family를 만들고 column family에 유지할 버전 수를 2로 설정합니다. 이는 이 column family의 모든 열에서 최근 셀 2개를 제외한 나머지를 삭제하도록 Bigtable에 지시합니다.

cbt createfamily your-table cf2
cbt setgcpolicy your-table cf2 maxversions=2

이 예시에서는 최근 셀을 제외한 모든 셀을 삭제하도록 정책을 설정합니다.

cbt setgcpolicy your-table cf2 maxversions=1

Go

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

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

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

	// Set a garbage collection policy of 2 versions.
	policy := bigtable.MaxVersionsPolicy(2)
	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

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

// Creates a column family with GC policy : most recent N versions
// where 1 = most recent version

// Defines the GC policy to retain only the most recent 2 versions.
VersionRule versionRule = GCRULES.maxVersions(2);

// 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_2, versionRule);
  adminClient.modifyFamilies(columnFamiliesRequest);
  System.out.println("Created column family: " + COLUMN_FAMILY_2);
} catch (AlreadyExistsException e) {
  System.err.println(
      "Failed to create column family with rule, already exists: " + e.getMessage());
}

Python

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    print("Creating column family cf2 with max versions GC rule...")
    # Create a column family with GC policy : most recent N versions
    # where 1 = most recent version

    # Define the GC policy to retain only the most recent 2 versions
    max_versions_rule = column_family.MaxVersionsGCRule(2)

    column_family2 = table.column_family("cf2", max_versions_rule)
    column_family2.create()
    print("Created column family cf2 with Max Versions GC Rule.")

C#

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

// Create a column family with GC policy : most recent N versions
// where 1 = most recent version
// Initialize request argument(s).
// Define the GC policy to retain only the most recent 2 versions
GcRule maxVersionsRule = new GcRule { MaxNumVersions = 2 };

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

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

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

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

C++

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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_create()->mutable_gc_rule()->set_max_num_versions(2);

  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";
}

Node.js

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

// Create a column family with GC policy : most recent N versions
// where 1 = most recent version

// Define the GC policy to retain only the most recent 2 versions
const maxVersionsRule = {
  rule: {
    versions: 2,
  },
};

// Create a column family with given GC rule
[family] = await table.createFamily('cf2', maxVersionsRule);
console.log(`Created column family ${family.id}`);

PHP

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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;

/**
 * Create a new column family with a max versions 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_max_versions(
    string $projectId,
    string $instanceId,
    string $tableId
): void {
    $tableAdminClient = new BigtableTableAdminClient();

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

    print('Creating column family cf2 with max versions GC rule...' . PHP_EOL);
    $columnFamily2 = new ColumnFamily();
    $maxVersionRule = (new GcRule())->setMaxNumVersions(2);
    $columnFamily2->setGCRule($maxVersionRule);

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

    print('Created column family cf2 with Max Versions GC Rule.' . PHP_EOL);
}

Ruby

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

# Create a column family with GC policy : most recent N versions
# where 1 = most recent version
max_versions_rule = Google::Cloud::Bigtable::GcRule.max_versions 2
column_families = table.column_families do |cfs|
  cfs.add "cf2", gc_rule: max_versions_rule
end
family = column_families["cf2"]

여러 기준에 따른 가비지 컬렉션

다음 섹션에서는 교차 가비지 컬렉션 정책에 따라 column family를 만드는 방법을 보여줍니다.

콘솔

column family의 셀에 교차 가비지 컬렉션 정책을 설정하려면 다음 안내를 따르세요.

  1. Google Cloud 콘솔에서 Bigtable 인스턴스 목록을 엽니다.

    인스턴스 목록 열기

  2. 테이블을 보려는 인스턴스를 클릭합니다.

  3. 왼쪽 창에서 테이블을 클릭합니다.

    테이블 페이지에는 인스턴스의 테이블 목록이 표시됩니다.

  4. 테이블 행에서 수정을 클릭합니다.

  5. 수정할 column family 옆에 있는 열기를 클릭합니다.

  6. 커스텀 정책을 선택합니다.

  7. 텍스트 영역에 가비지 컬렉션 규칙을 입력하고 maxage, maxversions 또는 둘 다 값을 설정합니다. 사용 가능한 연령 단위는 ms, s, m, h, d가 있으며 이는 밀리초, 초, 분, 시간, 일을 나타냅니다.

    예를 들어 5일보다 오래된 셀, 그리고 가장 최근 셀 두 개보다 오래된 셀을 삭제하려면 다음을 입력합니다. 셀을 삭제하려면 조건 기준 두 가지 모두를 충족해야 합니다.

    maxage=5d and maxversions=2
    
  8. 저장을 클릭합니다.

cbt

이 예시에서는 cf4라는 column family를 만들고, 5일이 지났으며 column family의 모든 열에 대한 가장 최근 셀 두 개보다 오래된 셀을 삭제하는 가비지 컬렉션 정책을 설정합니다. 셀을 삭제하려면 조건 기준 두 가지 모두를 충족해야 합니다.

cbt createfamily your-table cf4
cbt setgcpolicy your-table cf4 maxage=5d and maxversions=2

이 예시에서는 최근 셀을 제외하고 14일이 지난 모든 셀을 삭제하는 정책을 설정합니다.

cbt setgcpolicy your-table cf4 maxage=14d and maxversion=1

Go

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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

Python

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    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.")

C#

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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

C++

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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";
}

Node.js

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

// 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

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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

Ruby

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

# 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"]

다음 섹션에서는 통합 가비지 컬렉션 정책이 포함된 column family를 만드는 방법을 보여줍니다.

콘솔

column family의 셀에 통합 가비지 컬렉션 정책을 설정하는 방법은 다음과 같습니다.

  1. Google Cloud 콘솔에서 Bigtable 인스턴스 목록을 엽니다.

    인스턴스 목록 열기

  2. 테이블을 보려는 인스턴스를 클릭합니다.

  3. 왼쪽 창에서 테이블을 클릭합니다.

    테이블 페이지에는 인스턴스의 테이블 목록이 표시됩니다.

  4. 테이블 행에서 수정을 클릭합니다.

  5. 수정할 column family 옆에 있는 열기를 클릭합니다.

  6. 커스텀 정책을 선택합니다.

  7. 텍스트 영역에 가비지 컬렉션 규칙을 입력하고 maxage, maxversions 또는 둘 다 값을 설정합니다. 사용 가능한 연령 단위는 ms, s, m, h, d가 있으며 이는 밀리초, 초, 분, 시간, 일을 나타냅니다.

    예를 들어 5일이 지난 셀 또는 가장 최근의 2개 셀보다 오래된 셀을 삭제하려면 다음을 입력합니다. 셀을 삭제하려면 조건 기준 두 가지 중 하나를 충족해야 합니다.

    maxage=5d or maxversions=2
    
  8. 저장을 클릭합니다.

cbt

이 예시에서는 cf3라는 column family를 만든 다음 5일이 지났거나 또는 가장 최근의 2개 셀보다 오래된 셀을 삭제하는 가비지 컬렉션 정책을 설정합니다. 셀을 삭제하려면 둘 중 한 가지 조건을 충족해야 합니다.

cbt createfamily your-table cf3
cbt setgcpolicy your-table cf3 maxage=5d or maxversions=2

이 예시에서 만드는 정책은 최근 셀 값을 제외한 모든 셀 값을 삭제하는데, 1초보다 오래되었다면 최근 셀이라도 삭제합니다.

cbt setgcpolicy your-table cf3 maxversions=1 or maxage=1s

Go

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"
	"time"

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

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

	// Define a GC rule to drop cells older than 5 days or not the most recent version
	maxAge := time.Hour * 24 * 5
	maxAgePolicy := bigtable.MaxAgePolicy(maxAge)
	policy := bigtable.UnionPolicy(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

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

// Creates a column family with GC policy to drop data that matches at least one condition.

// Defines a list of GC rules to drop cells older than 5 days OR not the most recent
// version.
UnionRule unionRule =
    GCRULES.union().rule(GCRULES.maxAge(5, TimeUnit.DAYS)).rule(GCRULES.maxVersions(1));

// 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_3, unionRule);
  adminClient.modifyFamilies(columnFamiliesRequest);
  System.out.println("Created column family: " + COLUMN_FAMILY_3);
} catch (AlreadyExistsException e) {
  System.err.println(
      "Failed to create column family with rule, already exists: " + e.getMessage());
}

Python

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    print("Creating column family cf3 with union GC rule...")
    # Create a column family with GC policy to drop data that matches
    # at least one condition.
    # Define a GC rule to drop cells older than 5 days or not the
    # most recent version
    union_rule = column_family.GCRuleUnion(
        [
            column_family.MaxAgeGCRule(datetime.timedelta(days=5)),
            column_family.MaxVersionsGCRule(2),
        ]
    )

    column_family3 = table.column_family("cf3", union_rule)
    column_family3.create()
    print("Created column family cf3 with Union GC rule")

C#

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

// Create a column family with GC policy to drop data that matches at least one condition.
// Initialize request argument(s).
// Define a GC rule to drop cells older than 5 days or not the most recent version.
GcRule.Types.Union unionRule = new GcRule.Types.Union
{
    Rules =
    {
        new GcRule { MaxNumVersions = 1 },
        new GcRule { MaxAge = Duration.FromTimeSpan(TimeSpan.FromDays(5)) }
    }
};
GcRule gcRule = new GcRule { Union = unionRule };

// 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 = "cf3"
};

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

C++

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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_union = *mod.mutable_create()->mutable_gc_rule()->mutable_union_();
  gc_union.add_rules()->set_max_num_versions(1);
  gc_union.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";
}

Node.js

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

// Create a column family with GC policy to drop data that matches at least one condition.

// Define a GC rule to drop cells older than 5 days or not the most recent version
const unionRule = {
  rule: {
    versions: 1,
    age: {
      seconds: 60 * 60 * 24 * 5,
      nanos: 0,
    },
    union: true,
  },
};

[family] = await table.createFamily('cf3', unionRule);
console.log(`Created column family ${family.id}`);

PHP

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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\Union as GcRuleUnion;
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 a union 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_union(
    string $projectId,
    string $instanceId,
    string $tableId
): void {
    $tableAdminClient = new BigtableTableAdminClient();

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

    print('Creating column family cf3 with union GC rule...' . PHP_EOL);
    // Create a column family with GC policy to drop data that matches
    // at least one condition.
    // Define a GC rule to drop cells older than 5 days or not the
    // most recent version

    $columnFamily3 = new ColumnFamily();

    $ruleUnion = new GcRuleUnion();
    $ruleUnionArray = [
        (new GcRule())->setMaxNumVersions(2),
        (new GcRule())->setMaxAge((new Duration())->setSeconds(3600 * 24 * 5))
    ];
    $ruleUnion->setRules($ruleUnionArray);
    $union = new GcRule();
    $union->setUnion($ruleUnion);

    $columnFamily3->setGCRule($union);

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

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

Ruby

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

# 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
union_gc_rule = Google::Cloud::Bigtable::GcRule.union max_age_rule, max_versions_rule
column_families = table.column_families do |cfs|
  cfs.add "cf3", gc_rule: union_gc_rule
end
family = column_families["cf3"]

다음 섹션에서는 중첩 가비지 컬렉션 정책이 포함된 column family를 만드는 방법을 보여줍니다. 중첩 가비지 컬렉션 정책은 통합 규칙과 교차 규칙의 조합으로 구성됩니다.

콘솔

column family의 셀에 중첩된 가비지 컬렉션 정책을 설정하려면 다음 안내를 따르세요.

  1. Google Cloud 콘솔에서 Bigtable 인스턴스 목록을 엽니다.

    인스턴스 목록 열기

  2. 테이블을 보려는 인스턴스를 클릭합니다.

  3. 왼쪽 창에서 테이블을 클릭합니다.

    테이블 페이지에는 인스턴스의 테이블 목록이 표시됩니다.

  4. 테이블 행에서 수정을 클릭합니다.

  5. 수정할 column family 옆에 있는 열기를 클릭합니다.

  6. 커스텀 정책을 선택합니다.

  7. 텍스트 영역에 가비지 컬렉션 규칙을 입력하고 maxage, maxversions 또는 둘 다 값을 설정합니다. 사용 가능한 연령 단위는 ms, s, m, h, d가 있으며 이는 밀리초, 초, 분, 시간, 일을 나타냅니다.

    예를 들어 1분이 지난 최근 셀 2개를 유지하거나 1분이 지나지 않은 최근 셀 10개를 유지하려면 다음을 입력합니다.

    (maxage=1m and maxversions=2) or maxversions=10
    
  8. 저장을 클릭합니다.

cbt

이 예시에서는 cf5라는 column family를 만들고 다음 조건 중 하나를 충족하는 column family의 셀을 삭제하는 가비지 컬렉션 정책을 설정합니다.

  • 최근 10개 셀보다 오래됨
  • 1분보다 오래되었으며 최근 2개 셀보다 오래됨

즉, 이 정책은 1분이 지난 최근 셀 2개를 유지하거나 1분이 지나지 않은 최근 셀 10개를 유지합니다.

cbt createfamily your-table cf5
cbt setgcpolicy your-table cf5 "(maxage=1m and maxversions=2) or
maxversions=10"

Go

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"
	"time"

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

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

	// Create a nested GC rule:
	// Drop cells that are either older than the 10 recent versions
	// OR
	// Drop cells that are older than a month AND older than the 2 recent versions
	maxAge := time.Hour * 24 * 5
	maxAgePolicy := bigtable.MaxAgePolicy(maxAge)
	policy := bigtable.UnionPolicy(
		bigtable.MaxVersionsPolicy(10),
		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

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

// Creates a nested GC rule:
// Drop cells that are either older than the 10 recent versions
// OR
// Drop cells that are older than a month AND older than the 2 recent versions
VersionRule versionRule1 = GCRULES.maxVersions(10);
VersionRule versionRule2 = GCRULES.maxVersions(2);
DurationRule maxAgeRule = GCRULES.maxAge(30, TimeUnit.DAYS);
IntersectionRule intersectionRule = GCRULES.intersection().rule(maxAgeRule).rule(versionRule2);
UnionRule unionRule = GCRULES.union().rule(intersectionRule).rule(versionRule1);

// 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_5, unionRule);
  adminClient.modifyFamilies(columnFamiliesRequest);
  System.out.println("Created column family: " + COLUMN_FAMILY_5);
} catch (AlreadyExistsException e) {
  System.err.println(
      "Failed to create column family with rule, already exists: " + e.getMessage());
}

Python

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    print("Creating column family cf5 with a Nested GC rule...")
    # Create a column family with nested GC policies.
    # Create a nested GC rule:
    # Drop cells that are either older than the 10 recent versions
    # OR
    # Drop cells that are older than a month AND older than the
    # 2 recent versions
    rule1 = column_family.MaxVersionsGCRule(10)
    rule2 = column_family.GCRuleIntersection(
        [
            column_family.MaxAgeGCRule(datetime.timedelta(days=30)),
            column_family.MaxVersionsGCRule(2),
        ]
    )

    nested_rule = column_family.GCRuleUnion([rule1, rule2])

    column_family5 = table.column_family("cf5", nested_rule)
    column_family5.create()
    print("Created column family cf5 with a Nested GC rule.")

C#

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

// Create a nested GC rule:
// Drop cells that are either older than the 10 recent versions
// OR
// Drop cells that are older than 5 days AND older than the 2 recent versions.
// Initialize request argument(s).
GcRule.Types.Intersection intersectionRule = new GcRule.Types.Intersection
{
    Rules =
    {
        new GcRule { MaxNumVersions = 2 },
        new GcRule { MaxAge = Duration.FromTimeSpan(TimeSpan.FromDays(5)) }
    }
};

GcRule.Types.Union nestedRule = new GcRule.Types.Union
{
    Rules =
    {
        new GcRule { MaxNumVersions = 10 },
        new GcRule { Intersection = intersectionRule }
    }
};

GcRule gcRule = new GcRule { Union = nestedRule };

// 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 = "cf5"
};

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

C++

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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 = *mod.mutable_create()->mutable_gc_rule();
  auto& gc_1 = *gc.mutable_union_()->add_rules();
  auto& gc_2 = *gc.mutable_union_()->add_rules();
  auto& gc_2_1 = *gc_2.mutable_intersection()->add_rules();
  auto& gc_2_2 = *gc_2.mutable_intersection()->add_rules();

  gc_1.set_max_num_versions(10);
  gc_2_1.set_max_num_versions(1);
  gc_2_2.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";
}

Node.js

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

// Create a nested GC rule:
// Drop cells that are either older than the 10 recent versions
// OR
// Drop cells that are older than a month AND older than the 2 recent versions
const nestedRule = {
  union: true,
  versions: 10,
  rule: {
    versions: 2,
    age: {
      // one month
      seconds: 60 * 60 * 24 * 30,
      nanos: 0,
    },
  },
};

[family] = await table.createFamily('cf5', nestedRule);
console.log(`Created column family ${family.id}`);

PHP

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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\GcRule\Union as GcRuleUnion;
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 a nested 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_nested(
    string $projectId,
    string $instanceId,
    string $tableId
): void {
    $tableAdminClient = new BigtableTableAdminClient();

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

    print('Creating column family cf5 with a Nested GC rule...' . PHP_EOL);
    // Create a column family with nested GC policies.
    // Create a nested GC rule:
    // Drop cells that are either older than the 10 recent versions
    // OR
    // Drop cells that are older than a month AND older than the
    // 2 recent versions
    $columnFamily5 = new ColumnFamily();
    $rule1 = (new GcRule())->setMaxNumVersions(10);

    $rule2Intersection = new GcRuleIntersection();
    $rule2Duration1 = new Duration();
    $rule2Duration1->setSeconds(3600 * 24 * 30);
    $rule2Array = [
        (new GcRule())->setMaxAge($rule2Duration1),
        (new GcRule())->setMaxNumVersions(2)
    ];
    $rule2Intersection->setRules($rule2Array);
    $rule2 = new GcRule();
    $rule2->setIntersection($rule2Intersection);

    $nestedRule = new GcRuleUnion();
    $nestedRule->setRules([
        $rule1,
        $rule2
    ]);
    $nestedRule = (new GcRule())->setUnion($nestedRule);

    $columnFamily5->setGCRule($nestedRule);

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

    print('Created column family cf5 with a Nested GC rule.' . PHP_EOL);
}

Ruby

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

# Create a nested GC rule:
# Drop cells that are either older than the 10 recent versions
# OR
# Drop cells that are older than a month AND older than the 2 recent versions
max_versions_rule1 = Google::Cloud::Bigtable::GcRule.max_versions 10
max_age_rule = Google::Cloud::Bigtable::GcRule.max_age 60 * 60 * 24 * 5
max_versions_rule2 = Google::Cloud::Bigtable::GcRule.max_versions 2
intersection_gc_rule = Google::Cloud::Bigtable::GcRule.intersection max_age_rule, max_versions_rule2
nested_gc_rule = Google::Cloud::Bigtable::GcRule.union max_versions_rule1, intersection_gc_rule

가비지 컬렉션 정책 업데이트

다음 섹션에서는 기존 가비지 컬렉션 정책을 수정하는 방법을 보여줍니다.

복제를 사용하는 테이블에서 column family의 보관 기간을 늘리려면 클러스터가 동기화되지 않을 수 있다는 경고를 확인해야 합니다. 새 값은 현재 값에서 90일을 넘을 수 없습니다. 자세한 내용은 저장기간 기준 정책 변경을 참조하세요.

콘솔

column family의 가비지 컬렉션 정책을 업데이트하려면 다음 단계를 수행합니다.

  1. Google Cloud 콘솔에서 Bigtable 인스턴스 목록을 엽니다.

    인스턴스 목록 열기

  2. 테이블을 보려는 인스턴스를 클릭합니다.

  3. 왼쪽 창에서 테이블을 클릭합니다.

    테이블 페이지에는 인스턴스의 테이블 목록이 표시됩니다.

  4. 테이블 행에서 수정을 클릭합니다.

  5. 수정할 column family 옆에 있는 열기를 클릭합니다.

  6. 정책을 설정합니다.

  7. 저장을 클릭합니다.

cbt

cbt setgcpolicy your-table cf1 maxage=1d

복제된 테이블에서 maxage 값을 늘릴 경우 선택적 플래그 -- force를 사용해야 합니다. 새 값은 현재 값에서 90일을 넘을 수 없습니다.

Java

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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

Python

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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")

C#

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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

C++

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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";
}

Node.js

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

// 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

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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

Ruby

Bigtable용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Bigtable 클라이언트 라이브러리를 참조하세요.

Bigtable에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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"]

다음 단계