This topic describes how to update a single row of data in a Tablestore data table by using Tablestore SDK for Java. You can update attribute column values, add attribute columns, delete a specific version of an attribute column, or delete an entire attribute column.
Prerequisites
A client is initialized. For more information, see Initialize a Tablestore client.
Method
public UpdateRowResponse updateRow(UpdateRowRequest updateRowRequest) throws TableStoreException, ClientExceptionSample code
The following sample code provides an example on how to modify the row data with the primary key value of row1 in the test_table table. In this example, the value of the attribute column col1 is changed to changed_val1.
public static void updateRowExample(SyncClient client) {
// Construct the primary key.
PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
primaryKeyBuilder.addPrimaryKeyColumn("id", PrimaryKeyValue.fromString("row1"));
PrimaryKey primaryKey = primaryKeyBuilder.build();
// Construct the column value that you want to update.
RowUpdateChange rowUpdateChange = new RowUpdateChange("test_table", primaryKey);
rowUpdateChange.put("col1", ColumnValue.fromString("changed_val1"));
// Call the updateRow method to update the row data.
UpdateRowRequest updateRowRequest = new UpdateRowRequest(rowUpdateChange);
UpdateRowResponse updateRowResponse = client.updateRow(updateRowRequest);
// Return the result.
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());
}You can also refer to the sample code to perform the following row data operations.
Add an attribute column
rowUpdateChange.put("col2", ColumnValue.fromString("val2"));Specify the version number of data in an attribute column
rowUpdateChange.put("col2", ColumnValue.fromString("val2"), System.currentTimeMillis());Delete a specific version of data from an attribute column
rowUpdateChange.deleteColumn("col2", 1747893563831L);Delete an entire attribute column
rowUpdateChange.deleteColumns("col2");