全部產品
Search
文件中心

Tablestore:更新單行資料

更新時間:Jun 27, 2025

本文介紹如何通過 Java SDK 更新Table Store資料表中的單行資料,您可以更新屬性列的值、添加屬性列、刪除屬性列的某個版本或整個屬性列。

前提條件

初始化Tablestore Client

方法說明

public UpdateRowResponse updateRow(UpdateRowRequest updateRowRequest) throws TableStoreException, ClientException

UpdateRowRequest參數說明

  • rowChange(必選)RowUpdateChange:更新的行資料資訊,包含以下參數。

    名稱

    類型

    說明

    tableName(必選)

    String

    資料表名稱。

    primaryKey(必選)

    PrimaryKey

    主鍵資訊,包括主鍵列名稱和主索引值。

    • 主鍵列資料類型包括 STRING、INTEGER 和 BINARY。

    • 主鍵個數和類型必須與資料表的主鍵保持一致。

    columnsToUpdate(必選)

    List<Pair<Column, Type>>

    更新的屬性列資訊和操作類型。

    condition(可選)

    Condition

    寫入條件,詳情請參見條件更新

範例程式碼

以下範例程式碼用於修改 test_table 表中主索引值為 row1 的行資料,將屬性列 col1 的值修改為 changed_val1。

public static void updateRowExample(SyncClient client) {
    // 構造主鍵
    PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
    primaryKeyBuilder.addPrimaryKeyColumn("id", PrimaryKeyValue.fromString("row1"));
    PrimaryKey primaryKey = primaryKeyBuilder.build();

    // 構造更新行資料
    RowUpdateChange rowUpdateChange = new RowUpdateChange("test_table", primaryKey);
    rowUpdateChange.put("col1", ColumnValue.fromString("changed_val1"));

    // 調用 updateRow 方法更新行資料
    UpdateRowRequest updateRowRequest = new UpdateRowRequest(rowUpdateChange);
    UpdateRowResponse updateRowResponse = client.updateRow(updateRowRequest);

    // 返回結果處理
    System.out.println("RequestId: " + updateRowResponse.getRequestId());
    System.out.println("Read CU Cost: " + updateRowResponse.getConsumedCapacity().getCapacityUnit().getReadCapacityUnit());
    System.out.println("Write CU Cost: " + updateRowResponse.getConsumedCapacity().getCapacityUnit().getWriteCapacityUnit());
}

您也可以參照範例程式碼進行以下行資料操作。

  • 添加一個屬性列

    rowUpdateChange.put("col2", ColumnValue.fromString("val2"));
  • 設定屬性列資料版本號碼

    rowUpdateChange.put("col2", ColumnValue.fromString("val2"), System.currentTimeMillis());
  • 刪除屬性列指定版本的資料

    rowUpdateChange.deleteColumn("col2", 1747893563831L);
  • 刪除整個屬性列資料

    rowUpdateChange.deleteColumns("col2");

相關文檔