הגדר איסוף אשפה

מדיניות איסוף האשפה ב-Bigtable מאפשרת לכם לשלוט בעלויות האחסון ולהסיר נתונים לא רלוונטיים מתאים באופן אוטומטי. אפשר להציג, להגדיר ולעדכן את המדיניות הזו באמצעות מסוף Google Cloud ,‏ cbt CLI או ספריות לקוח של Cloud Bigtable. לפני שמתחילים, חשוב לעיין בסקירה כללית של איסוף אשפה.

הצגת מדיניות איסוף האשפה הנוכחית

אפשר להשתמש במסוף Google Cloud או ב-CLI של cbt כדי לראות את מדיניות איסוף האשפה של משפחת עמודות.

המסוף

כדי לראות את מדיניות איסוף האשפה הנוכחית של קבוצת עמודות:

  1. במסוף Google Cloud , פותחים את רשימת מופעי Bigtable.

    פתיחת רשימת המופעים

  2. לוחצים על המופע שרוצים לראות את הטבלאות שלו.

  3. בחלונית הימנית, לוחצים על טבלאות.

    בדף Tables (טבלאות) מוצגת רשימה של טבלאות במופע.

  4. לוחצים על עריכה בשורה של הטבלה.

  5. לצד קבוצת העמודות שרוצים להציג, לוחצים על פתיחה.

  6. כשמסיימים לצפות במדיניות איסוף הגרבג' (Garbage Collection), לוחצים על ביטול כדי לצאת.

cbt

אפשר לחפש את כללי איסוף הגרבג' הנוכחיים של טבלה מסוימת באמצעות הפקודה הבאה. צריך להחליף את TABLE_ID במזהה טבלה תקין:

cbt ls TABLE_ID

הגדרת מדיניות Garbage Collection

אפשר להגדיר מדיניות של איסוף נתונים מיותרים באמצעות מסוף Google Cloud ,‏ cbt CLI או ספריות הלקוח של Cloud Bigtable.

איסוף אשפה לפי גיל

בקטע הבא מוסבר איך להגדיר את הגיל המקסימלי של נתונים במשפחת עמודות.

המסוף

כדי להגדיר מועד תפוגה לתאים בקבוצת עמודות:

  1. במסוף Google Cloud , פותחים את רשימת מופעי Bigtable.

    פתיחת רשימת המופעים

  2. לוחצים על המופע שרוצים לראות את הטבלאות שלו.

  3. בחלונית הימנית, לוחצים על טבלאות.

    בדף Tables (טבלאות) מוצגת רשימה של טבלאות במופע.

  4. לוחצים על עריכה.

  5. לצד קבוצת העמודות שרוצים לערוך, לוחצים על פתיחה.

  6. בוחרים באפשרות מדיניות לפי גיל.

  7. מזינים את הגיל בשדה גיל מקסימלי ובוחרים את יחידת הזמן בתפריט הנפתח יחידה.

    לדוגמה, כדי לשמור את הנתונים של קבוצת עמודות למשך 30 דקות, מזינים 30 ובוחרים באפשרות minutes (דקות).

  8. לוחצים על Save.

cbt

בדוגמה הזו נוצרת משפחת עמודות בשם cf1, ואז מוגדר הגיל המקסימלי של הנתונים במשפחת העמודות לחמישה ימים. הפקודה הזו אומרת ל-Bigtable להסיר את כל הנתונים עם חותמות זמן מלפני יותר מחמישה ימים בכל העמודות במשפחת העמודות הזו.

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

המשך

מידע על התקנת ספריית הלקוח של Bigtable ושימוש בה מופיע במאמר ספריות הלקוח של Bigtable.

כדי לבצע אימות ב-Bigtable, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

// 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.
GcRule maxAgeRule = GcRuleBuilder.maxAge(Duration.ofDays(5));

// Creates column family with given GC rule.
try {
  String tableName =
      "projects/" + projectId + "/instances/" + instanceId + "/tables/" + tableId;
  ModifyColumnFamiliesRequest request =
      ModifyColumnFamiliesRequest.newBuilder()
          .setName(tableName)
          .addModifications(
              ModifyColumnFamiliesRequest.Modification.newBuilder()
                  .setId(COLUMN_FAMILY_1)
                  .setCreate(ColumnFamily.newBuilder().setGcRule(maxAgeRule)))
          .build();
  adminClient.modifyColumnFamilies(request);
  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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

// 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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

// 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 = GcRuleBuilder.rule({
  maxAge: {
    // Value must be atleast 1 millisecond
    seconds: 60 * 60 * 24 * 5,
    nanos: 0,
  },
});
let [family] = await adminClient.modifyColumnFamilies({
  name: table.name,
  modifications: [
    {
      id: 'cf1',
      create: {
        gcRule: maxAgeRule,
      },
    },
  ],
});
console.log(`Created column family ${family.name}`);

PHP

מידע על התקנת ספריית הלקוח של Bigtable ושימוש בה מופיע במאמר ספריות הלקוח של Bigtable.

כדי לבצע אימות ב-Bigtable, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

איסוף אשפה בהתבסס על מספר הגרסאות

בקטע הבא מוסבר איך ליצור קבוצת עמודות עם מדיניות איסוף נתונים שקובעת את מספר הגרסאות של הנתונים או מספר התאים שצריך לשמור.

המסוף

כדי להגדיר את מספר התאים או הגרסאות שיישארו בקבוצת עמודות:

  1. במסוף Google Cloud , פותחים את רשימת מופעי Bigtable.

    פתיחת רשימת המופעים

  2. לוחצים על המופע שרוצים לראות את הטבלאות שלו.

  3. בחלונית הימנית, לוחצים על טבלאות.

    בדף Tables (טבלאות) מוצגת רשימה של טבלאות במופע.

  4. לוחצים על עריכה בשורה של הטבלה.

  5. לצד קבוצת העמודות שרוצים לערוך, לוחצים על פתיחה.

  6. בוחרים באפשרות מדיניות מבוססת-גרסה.

  7. מזינים את מספר התאים שרוצים לשמור בכל עמודה במשפחת העמודות.

  8. לוחצים על Save.

cbt

בדוגמה הזו נוצרת משפחת עמודות בשם cf2, ואז נקבע מספר הגרסאות שיישארו במשפחת העמודות כשתיים. הפקודה הזו אומרת ל-Bigtable להסיר את כל התאים מלבד שני התאים האחרונים בכל העמודות במשפחת העמודות הזו.

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

בדוגמה הזו מוגדרת מדיניות להסרת כל התאים מלבד התא החדש ביותר.

cbt setgcpolicy your-table cf2 maxversions=1

המשך

מידע על התקנת ספריית הלקוח של Bigtable ושימוש בה מופיע במאמר ספריות הלקוח של Bigtable.

כדי לבצע אימות ב-Bigtable, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

// 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.
GcRule versionRule = GcRuleBuilder.maxVersions(2);

// Creates column family with given GC rule.
try {
  String tableName =
      "projects/" + projectId + "/instances/" + instanceId + "/tables/" + tableId;
  ModifyColumnFamiliesRequest request =
      ModifyColumnFamiliesRequest.newBuilder()
          .setName(tableName)
          .addModifications(
              ModifyColumnFamiliesRequest.Modification.newBuilder()
                  .setId(COLUMN_FAMILY_2)
                  .setCreate(ColumnFamily.newBuilder().setGcRule(versionRule)))
          .build();
  adminClient.modifyColumnFamilies(request);
  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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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