刪除次數

本文說明如何刪除 Bigtable 資料表儲存的資料,並討論何時應使用每種方法,以及提供範例。閱讀本頁面之前,請先熟悉 Bigtable 總覽,並瞭解結構定義設計相關概念。

為確保一致性,本頁面的說明會提及用於各類型要求的 API 方法。不過,我們強烈建議您一律使用 Bigtable 用戶端程式庫存取 Bigtable API,而非使用 REST 或 RPC。

本頁面的範例使用範例資料,類似於您可能儲存在 Bigtable 中的資料。

如要瞭解每天可使用本頁面所述作業的次數,請參閱「配額與限制」。

Bigtable 如何刪除資料

傳送刪除要求後,系統會將儲存格標記為待刪除,且無法讀取。最多一週後,系統會在壓縮期間移除資料。壓縮是持續最佳化資料表的背景程序。刪除中繼資料可能會導致資料在您傳送刪除要求後的幾天內,佔用稍微多一點的空間 (每列幾 KB),直到下次壓縮為止。

即使叢集超出儲存空間上限,導致讀取和寫入作業遭到封鎖,您還是可以傳送刪除要求。

刪除特定範圍內的資料列

如要刪除儲存在連續資料列中的大量資料,請使用 dropRowRange。這項作業會刪除由開始和結束資料列或資料列鍵前置字串所識別的資料列範圍內的所有資料列。

刪除一系列資料列時,您提供的資料列鍵值會視為服務資料。如要瞭解服務資料的處理方式,請參閱Google Cloud 隱私權聲明

成功刪除資料並收到回應後,您就可以安全地將資料寫入相同列範圍。

dropRowRange 作業有下列限制:

  • 您無法從授權檢視畫面中捨棄列範圍。
  • 您無法以非同步方式呼叫 dropRowRange 方法。如果您在另一個要求進行中時,傳送 dropRowRange 要求至資料表,Bigtable 會傳回 UNAVAILABLE 錯誤,並顯示 A DropRowRange operation is already ongoing 訊息。如要解決這個錯誤,請再次傳送要求。
  • 使用複製功能時,請注意 Bigtable 可能需要較長時間才能完成作業,因為複製延遲和 CPU 使用量會增加。如要從使用複寫功能的執行個體刪除資料,請使用 Data API 讀取資料,然後刪除資料

下列程式碼範例說明如何捨棄以資料列鍵前置字元 phone#5c10102 開頭的資料列範圍:

Java

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

import com.google.cloud.bigtable.admin.v2.BigtableTableAdminClient;
import java.io.IOException;

public class DropRowRangeExample {
  public void dropRowRange(String projectId, String instanceId, String tableId) throws IOException {
    try (BigtableTableAdminClient tableAdminClient =
        BigtableTableAdminClient.create(projectId, instanceId)) {
      tableAdminClient.dropRowRange(tableId, "phone#4c410523");
    }
  }
}

Python

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

def drop_row_range(project_id, instance_id, table_id):
    from google.cloud.bigtable import Client

    client = Client(project=project_id, admin=True)
    instance = client.instance(instance_id)
    table = instance.table(table_id)
    row_key_prefix = "phone#4c410523"
    table.drop_by_prefix(row_key_prefix, timeout=200)

Node.js

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

await table.deleteRows('phone#5c10102');
await printRows();

使用 Data API 方法刪除資料

如要刪除少量不連續的資料,通常最好使用呼叫 Cloud Bigtable API (Data API) 的方法刪除資料。如果要求刪除的資料量為 MB,而非 GB,請使用這些方法。 如要刪除資料欄 (而非資料欄系列) 中的資料,只能使用 Data API。

資料 API 方法會使用下列三種變動類型之一呼叫 MutateRows

  • DeleteFromColumn
  • DeleteFromFamily
  • DeleteFromRow

使用 Data API 提出的刪除要求是不可分割的作業:要求成功時,所有資料都會遭到刪除;要求失敗時,則不會移除任何資料。

在大多數情況下,請避免使用 CheckAndMutate 方法刪除資料。如果需要強烈一致性,您或許可以採用這種做法,但請注意,這會耗用大量資源,且效能可能會受到影響。

如要使用 MutateRows 刪除資料,請傳送 readRows 要求,並使用篩選器判斷要刪除的內容,然後傳送刪除要求。如需可用篩選器清單,請參閱「篩選器」。

本節中的範例假設您已決定要刪除哪些資料。

從資料欄中刪除

下列程式碼範例示範如何刪除資料列中某個資料欄的所有儲存格:

Java

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

import com.google.cloud.bigtable.data.v2.BigtableDataClient;
import com.google.cloud.bigtable.data.v2.models.Mutation;
import com.google.cloud.bigtable.data.v2.models.RowMutation;
import com.google.cloud.bigtable.data.v2.models.TableId;
import java.io.IOException;

public class DeleteFromColumnExample {
  public void deleteFromColumnCells(String projectId, String instanceId, String tableId)
      throws IOException {
    try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {
      Mutation mutation = Mutation.create().deleteCells("cell_plan", "data_plan_01gb");
      dataClient.mutateRow(
          RowMutation.create(TableId.of(tableId), "phone#4c410523#20190501", mutation));
    }
  }
}

Python

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

def delete_from_column(project_id, instance_id, table_id):
    from google.cloud.bigtable import Client

    client = Client(project=project_id, admin=True)
    instance = client.instance(instance_id)
    table = instance.table(table_id)
    row = table.row("phone#4c410523#20190501")
    row.delete_cell(column_family_id="cell_plan", column="data_plan_01gb")
    row.commit()

Python asyncio

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

async def delete_from_column(project_id, instance_id, table_id):
    from google.cloud.bigtable.data import BigtableDataClientAsync
    from google.cloud.bigtable.data import DeleteRangeFromColumn

    client = BigtableDataClientAsync(project=project_id)
    table = client.get_table(instance_id, table_id)

    await table.mutate_row(
        "phone#4c410523#20190501",
        DeleteRangeFromColumn(family="cell_plan", qualifier=b"data_plan_01gb"),
    )

    await table.close()
    await client.close()

Node.js

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

await table.mutate({
  key: 'phone#4c410523#20190501',
  method: 'delete',
  data: {
    column: 'cell_plan:data_plan_05gb',
  },
});
await printRows();

從資料欄系列中刪除

以下程式碼範例示範如何刪除資料列中資料欄系列的儲存格:

Java

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

import com.google.cloud.bigtable.data.v2.BigtableDataClient;
import com.google.cloud.bigtable.data.v2.models.RowMutation;
import com.google.cloud.bigtable.data.v2.models.TableId;
import java.io.IOException;

public class DeleteFromColumnFamilyExample {
  public void deleteFromColumnFamily(String projectId, String instanceId, String tableId)
      throws IOException {
    try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {
      dataClient.mutateRow(
          RowMutation.create(TableId.of(tableId), "phone#5c10102#20190501")
              .deleteFamily("stats_summary"));
    }
  }
}

Python

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

def delete_from_column_family(project_id, instance_id, table_id):
    from google.cloud.bigtable import Client

    client = Client(project=project_id, admin=True)
    instance = client.instance(instance_id)
    table = instance.table(table_id)
    row = table.row("phone#4c410523#20190501")
    row.delete_cells(column_family_id="cell_plan", columns=row.ALL_COLUMNS)
    row.commit()

Python asyncio

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

async def delete_from_column_family(project_id, instance_id, table_id):
    from google.cloud.bigtable.data import BigtableDataClientAsync
    from google.cloud.bigtable.data import DeleteAllFromFamily

    client = BigtableDataClientAsync(project=project_id)
    table = client.get_table(instance_id, table_id)

    await table.mutate_row("phone#4c410523#20190501", DeleteAllFromFamily("cell_plan"))

    await table.close()
    await client.close()

Node.js

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

await table.mutate({
  key: 'phone#4c410523#20190501',
  method: 'delete',
  data: {
    column: 'cell_plan',
  },
});
await printRows();

從資料列中刪除

下列程式碼片段示範如何刪除資料列中的所有儲存格:

Java

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

import com.google.cloud.bigtable.data.v2.BigtableDataClient;
import com.google.cloud.bigtable.data.v2.models.Mutation;
import com.google.cloud.bigtable.data.v2.models.RowMutation;
import com.google.cloud.bigtable.data.v2.models.TableId;
import java.io.IOException;

public class DeleteFromRowExample {
  public void deleteFromRow(String projectId, String instanceId, String tableId)
      throws IOException {
    try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {
      Mutation mutation = Mutation.create().deleteRow();
      dataClient.mutateRow(
          RowMutation.create(TableId.of(tableId), "phone#4c410523#20190501", mutation));
    }
  }
}

Python

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

def delete_from_row(project_id, instance_id, table_id):
    from google.cloud.bigtable import Client

    client = Client(project=project_id, admin=True)
    instance = client.instance(instance_id)
    table = instance.table(table_id)
    row = table.row("phone#4c410523#20190501")
    row.delete()
    row.commit()

Python asyncio

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

async def delete_from_row(project_id, instance_id, table_id):
    from google.cloud.bigtable.data import BigtableDataClientAsync
    from google.cloud.bigtable.data import DeleteAllFromRow

    client = BigtableDataClientAsync(project=project_id)
    table = client.get_table(instance_id, table_id)

    await table.mutate_row("phone#4c410523#20190501", DeleteAllFromRow())

    await table.close()
    await client.close()

Node.js

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

const row = table.row('phone#4c410523#20190501');
await row.delete();
await printRows();

透過串流和批次刪除

如要刪除大量資料,通常最好採用串流和批次處理刪除要求。如果資料保留要求比垃圾收集政策允許的更精細,這項策略就非常實用。

如果應用程式是以 Java 編寫,向 Bigtable 傳送批次刪除作業時,可以啟用批次寫入流量控制。詳情請參閱「批次寫入流量控管」和「啟用批次寫入流量控管」。

下列程式碼範例會啟動資料串流 (讀取資料列)、批次處理資料,然後逐一處理批次資料,並刪除 cell_plan 資料欄系列中 data_plan_01gb1 資料欄的所有儲存格:

Go

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package deletes


import (
	"context"
	"fmt"
	"io"

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

// streamingAndBatching starts a stream of data (reading rows), batches them, and then goes through the batch and deletes all the cells in column
func streamingAndBatching(w io.Writer, projectID, instanceID string, tableName string) error {
	// projectID := "my-project-id"
	// instanceID := "my-instance-id"
	// tableName := "mobile-time-series"

	ctx := context.Background()
	client, err := bigtable.NewClient(ctx, projectID, instanceID)
	if err != nil {
		return fmt.Errorf("bigtable.NewClient: %w", err)
	}
	defer client.Close()
	tbl := client.Open(tableName)

	// Slices to hold the row keys and the corresponding mutations.
	var rowKeys []string
	var mutations []*bigtable.Mutation

	// Read all rows from the table.
	err = tbl.ReadRows(ctx, bigtable.InfiniteRange(""), func(row bigtable.Row) bool {
		// For each row, create a mutation to delete the specified cell.
		mut := bigtable.NewMutation()
		mut.DeleteCellsInColumn("cell_plan", "data_plan_01gb")

		// Append the row key and mutation to the slices.
		rowKeys = append(rowKeys, row.Key())
		mutations = append(mutations, mut)

		// Continue processing rows.
		return true
	})
	if err != nil {
		return fmt.Errorf("tbl.ReadRows: %w", err)
	}

	if len(mutations) == 0 {
		return nil
	}
	// If there are mutations to apply, apply them in a single bulk request.
	// ApplyBulk returns a slice of errors, one for each mutation.
	var errs []error
	if errs, err = tbl.ApplyBulk(ctx, rowKeys, mutations); err != nil {
		return fmt.Errorf("tbl.ApplyBulk: %w", err)
	}
	if errs != nil {
		// Log any individual errors that occurred during the bulk operation.
		var errorCount int
		for _, individualErr := range errs {
			if individualErr != nil {
				fmt.Fprintf(w, "Error applying mutation: %v\n", individualErr)
				errorCount++
			}
		}
		if errorCount > 0 {
			return fmt.Errorf("encountered %d error(s) out of %d mutations", errorCount, len(errs))
		}
	}

	fmt.Fprintf(w, "Successfully deleted cells from all rows")
	return nil
}

Java

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

import com.google.api.gax.batching.Batcher;
import com.google.api.gax.rpc.ServerStream;
import com.google.cloud.bigtable.data.v2.BigtableDataClient;
import com.google.cloud.bigtable.data.v2.models.Query;
import com.google.cloud.bigtable.data.v2.models.Row;
import com.google.cloud.bigtable.data.v2.models.RowMutationEntry;
import com.google.cloud.bigtable.data.v2.models.TableId;
import java.io.IOException;

public class BatchDeleteExample {
  public void batchDelete(String projectId, String instanceId, String tableId)
      throws InterruptedException, IOException {
    try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {
      try (Batcher<RowMutationEntry, Void> batcher =
          dataClient.newBulkMutationBatcher(TableId.of(tableId))) {
        ServerStream<Row> rows = dataClient.readRows(Query.create(TableId.of(tableId)));
        for (Row row : rows) {
          batcher.add(
              RowMutationEntry.create(row.getKey()).deleteCells("cell_plan", "data_plan_05gb"));
        }
        // Blocks until mutations are applied on all submitted row entries.
        batcher.flush();
      }
    }
  }
}

Python

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

def streaming_and_batching(project_id, instance_id, table_id):
    from google.cloud.bigtable import Client

    client = Client(project=project_id, admin=True)
    instance = client.instance(instance_id)
    table = instance.table(table_id)
    batcher = table.mutations_batcher(flush_count=2)
    rows = table.read_rows()
    for row in rows:
        row = table.row(row.row_key)
        row.delete_cell(column_family_id="cell_plan", column="data_plan_01gb")

    batcher.mutate_rows(rows)

Python asyncio

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

async def streaming_and_batching(project_id, instance_id, table_id):
    from google.cloud.bigtable.data import BigtableDataClientAsync
    from google.cloud.bigtable.data import DeleteRangeFromColumn
    from google.cloud.bigtable.data import RowMutationEntry
    from google.cloud.bigtable.data import ReadRowsQuery

    client = BigtableDataClientAsync(project=project_id)
    table = client.get_table(instance_id, table_id)

    async with table.mutations_batcher() as batcher:
        async for row in await table.read_rows_stream(ReadRowsQuery(limit=10)):
            await batcher.append(
                RowMutationEntry(
                    row.row_key,
                    DeleteRangeFromColumn(
                        family="cell_plan", qualifier=b"data_plan_01gb"
                    ),
                )
            )

    await table.close()
    await client.close()

Node.js

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

const rows = (await table.getRows({limit: 2}))[0];
const entries = rows.map(row => {
  return {
    key: row.id,
    method: 'delete',
    data: {
      column: 'cell_plan:data_plan_05gb',
    },
  };
});
await table.mutate(entries);
await printRows();

刪除授權檢視表中的資料

您可以將刪除要求傳送至授權檢視區塊,藉此刪除表格資料。你必須使用下列其中一種方式:

  • gcloud CLI
  • Java 適用的 Bigtable 用戶端

從授權檢視表刪除資料時,除了資料表 ID 之外,您還需要提供授權檢視表 ID。

您可以從授權檢視表刪除的資料,會受到授權檢視表定義的限制。您只能刪除授權檢視表中的資料。如果您嘗試刪除授權檢視定義以外的資料,或刪除受下列規則限制的資料,系統會傳回 PERMISSION_DENIED 錯誤:

  • 系統不支援使用 Admin API 中的 DropRowRange,從授權檢視畫面刪除一系列資料列。
  • 系統不支援從資料列中刪除。
  • 只要資料列位於授權檢視畫面中,系統就支援從資料欄中刪除資料。
  • 只有在指定資料欄系列已設定為允許授權檢視畫面中的所有資料欄限定詞前置字元 (qualifier_prefixes="") 時,才能從資料欄系列中刪除資料。

舉例來說,如果您嘗試從指定資料列刪除資料,但該資料列包含基礎資料表中不在授權檢視畫面中的資料欄,則要求會失敗。

後續步驟