Tablestore allows you to write data to data tables by writing a single row or multiple rows of data at the same time. You can write rows individually or write multiple rows of data at the same time based on your business requirements. This topic describes how to write data to Tablestore by using Tablestore SDK for Java.
Prerequisites
An OTSClient instance is initialized. For more information, see Initialize an OTSClient instance.
A data table is created in a Tablestore instance.
Write methods
Tablestore allows you to write a single row of data, update a single row of data, and write multiple rows of data at the same time by calling different operations. The following table describes the differences and applicable scenarios of the write methods.
Write method | Description | Scenario |
Call the PutRow operation to write a single row of data. | This method is suitable for scenarios in which you want to write a small amount of data. | |
Call the UpdateRow operation to update a single row of data. | This method is suitable for scenarios in which you want to update a small amount of data. | |
You can call the BatchWriteRow operation to write multiple rows of data to one or more tables at the same time. | This method is suitable for scenarios in which you want to write, delete, or update a large amount of data and scenarios in which you want to write, delete, and update data at the same time. |
Parameters
The following table describes the parameters that you can configure to write data to Tablestore.
Parameter | Description |
tableName | The name of the data table. |
primaryKey | The primary key information about the data table. The primary key information includes the name, type, and value of each primary key column. Important
|
column | The information about the attribute columns. The information about the attribute columns includes the name, value, type, and timestamp of each attribute column. The type and timestamp are optional.
Note
|
condition | The condition that must be met to write data. The condition can be a row existence condition or a condition based on column values. For more information, see Perform conditional updates. |
Write a single row of data
You can call the PutRow operation to write a single row of data. If the row exists, the PutRow operation deletes all versions of data in all columns from the existing row, and then writes new data.
In this example, pkValue
represents the primary key column value. Specify pkValue based on your business requirements. To write data to a data table, you must specify the complete primary key information and information about the attribute columns that you want to write. You can specify the condition that must be met to write data to the data table. For example, you can specify that data can be written to the data table only if the specified row does not exist.
The following sample code provides an example on how to use the data version number that is automatically generated by the system, specify a custom data version number, and specify a condition that must be met to write data to a data table:
Use the data version number automatically generated by the system
The following sample code provides an example on how to write a row that contains 10 attribute columns, each of which stores data of only one version. In this example, data version numbers are automatically generated by the system:
private static void putRow(SyncClient client, String pkValue) {
// Construct the primary key.
PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
primaryKeyBuilder.addPrimaryKeyColumn("your_primaryKey", PrimaryKeyValue.fromString(pkValue));
PrimaryKey primaryKey = primaryKeyBuilder.build();
// Specify the name of the data table.
RowPutChange rowPutChange = new RowPutChange("your_tableName", primaryKey);
// Add attribute columns.
for (int i = 0; i < 10; i++) {
rowPutChange.addColumn(new Column("Col" + i, ColumnValue.fromLong(i)));
}
client.putRow(new PutRowRequest(rowPutChange));
}
Specify a custom data version number
The following sample code provides an example on how to write a row that contains 10 attribute columns, each of which stores data of three versions. In this example, custom data version numbers are specified:
private static void putRow(SyncClient client, String pkValue) {
// Construct the primary key.
PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
primaryKeyBuilder.addPrimaryKeyColumn("your_primaryKey", PrimaryKeyValue.fromString(pkValue));
PrimaryKey primaryKey = primaryKeyBuilder.build();
// Specify the name of the data table.
RowPutChange rowPutChange = new RowPutChange("your_tableName", primaryKey);
// Add attribute columns.
long ts = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
rowPutChange.addColumn(new Column("Col" + i, ColumnValue.fromLong(j), ts + j));
}
}
client.putRow(new PutRowRequest(rowPutChange));
}
Specify a row existence condition
The following sample code provides an example on how to write a row that contains 10 attribute columns, each of which stores data of three versions, when the specified row does not exist. In this example, custom data version numbers are specified:
private static void putRow(SyncClient client, String pkValue) {
// Construct the primary key.
PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
primaryKeyBuilder.addPrimaryKeyColumn("your_primaryKey", PrimaryKeyValue.fromString(pkValue));
PrimaryKey primaryKey = primaryKeyBuilder.build();
// Specify the name of the data table.
RowPutChange rowPutChange = new RowPutChange("your_tableName", primaryKey);
// Specify a condition for the PutRow operation. In this example, data is written to the data table only when the specified row does not exist.
rowPutChange.setCondition(new Condition(RowExistenceExpectation.EXPECT_NOT_EXIST));
// Add attribute columns.
long ts = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
rowPutChange.addColumn(new Column("Col" + i, ColumnValue.fromLong(j), ts + j));
}
}
client.putRow(new PutRowRequest(rowPutChange));
}
Specify a column value condition and a row existence condition at the same time
The following sample code provides an example on how to write a row that contains 10 attribute columns, each of which stores data of three versions, when the specified row exists and the value of the Col0 column is greater than 100. In this example, custom data version numbers are specified:
private static void putRow(SyncClient client, String pkValue) {
// Construct the primary key.
PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
primaryKeyBuilder.addPrimaryKeyColumn("your_primaryKey", PrimaryKeyValue.fromString(pkValue));
PrimaryKey primaryKey = primaryKeyBuilder.build();
// Specify the name of the data table.
RowPutChange rowPutChange = new RowPutChange("your_tableName", primaryKey);
// Specify conditions for the PutRow operation. In this example, a row is written to the data table only when the row exists and the value of the Col0 column is greater than 100.
Condition condition = new Condition(RowExistenceExpectation.EXPECT_EXIST);
condition.setColumnCondition(new SingleColumnValueCondition("Col0",
SingleColumnValueCondition.CompareOperator.GREATER_THAN, ColumnValue.fromLong(100)));
rowPutChange.setCondition(condition);
// Add attribute columns.
long ts = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
rowPutChange.addColumn(new Column("Col" + i, ColumnValue.fromLong(j), ts + j));
}
}
client.putRow(new PutRowRequest(rowPutChange));
}
Update a single row of data
You can call the UpdateRow operation to update a single row of data. You can update the value of an attribute column, add and remove an attribute column, or delete a specific version of data from an attribute column. If the row does not exist, a new row is added.
If an UpdateRow operation only specifies columns that you want to delete from a row and the row does not exist, no row is added to the data table.
The following sample code provides an example on how to update specific columns, delete a specific version of data from the Col1 column, and delete the Col0 column when conditions that must be met to update the row are specified and when no conditions are specified:
Update a row of data without specifying conditions
The following sample code provides an example on how to update a row of data without specifying necessary conditions that must be met:
private static void updateRow(SyncClient client, String pkValue) {
// Construct the primary key.
PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
primaryKeyBuilder.addPrimaryKeyColumn("your_primaryKey", PrimaryKeyValue.fromString(pkValue));
PrimaryKey primaryKey = primaryKeyBuilder.build();
// Specify the name of the data table.
RowUpdateChange rowUpdateChange = new RowUpdateChange("your_tableName", primaryKey);
// Update specific columns.
for (int i = 0; i < 10; i++) {
rowUpdateChange.put(new Column("Col" + i, ColumnValue.fromLong(i)));
}
// Delete a specific version of data from a column.
rowUpdateChange.deleteColumn("Col1", 1465373223000L);
// Delete a column.
rowUpdateChange.deleteColumns("Col0");
client.updateRow(new UpdateRowRequest(rowUpdateChange));
}
Specify a row existence condition or a condition based on column values to update data
The following sample code provides an example on how to update a row of data only when the specified row exists and the value of the Col0 column is greater than 100:
private static void updateRow(SyncClient client, String pkValue) {
// Construct the primary key.
PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
primaryKeyBuilder.addPrimaryKeyColumn("your_primaryKey", PrimaryKeyValue.fromString(pkValue));
PrimaryKey primaryKey = primaryKeyBuilder.build();
// Specify the name of the data table.
RowUpdateChange rowUpdateChange = new RowUpdateChange("your_tableName", primaryKey);
// Specify the conditions for the UpdateRow operation. In this example, a row of data is updated only if the row exists and the value of the Col0 column is greater than 100.
Condition condition = new Condition(RowExistenceExpectation.EXPECT_EXIST);
condition.setColumnCondition(new SingleColumnValueCondition("Col0",
SingleColumnValueCondition.CompareOperator.GREATER_THAN, ColumnValue.fromLong(100)));
rowUpdateChange.setCondition(condition);
// Update specific columns.
for (int i = 0; i < 10; i++) {
rowUpdateChange.put(new Column("Col" + i, ColumnValue.fromLong(i)));
}
// Delete a specific version of data from a column.
rowUpdateChange.deleteColumn("Col1", 1465373223000L);
// Delete a column.
rowUpdateChange.deleteColumns("Col0");
client.updateRow(new UpdateRowRequest(rowUpdateChange));
}
Write multiple rows of data at the same time
You can call the BatchWriteRow operation to write multiple rows of data to one or more tables at the same time.
The BatchWriteRow operation consists of multiple PutRow, UpdateRow, and DeleteRow operations. When you call the BatchWriteRow operation, the process of constructing a suboperation is the same as the process of calling the PutRow, UpdateRow, or DeleteRow operation. When you call the BatchWriteRow operation, each PutRow, UpdateRow, or DeleteRow operation is separately performed and the response to each operation is separately returned by Tablestore.
If the server detects that invalid parameters exist in specific operations, the BatchWriteRow operation throws an exception that indicates invalid parameters. In this case, no operations in the request are performed.
When you call the BatchWriteRow operation to write multiple rows of data at the same time, some rows may fail to be written. If this happens, Tablestore returns BatchWriteRowResponse, which includes the indexes and error messages of the failed rows. We recommend that you check the return values. You can determine whether all rows are written to the data tables based on the
isAllSucceed
parameter in BatchWriteRowResponse.
The following sample code provides an example on how to send a request for the BatchWriteRow operation, which consists of two PutRow operations, one DeleteRow operation, and one UpdateRow operation:
private static void batchWriteRow(SyncClient client) {
BatchWriteRowRequest batchWriteRowRequest = new BatchWriteRowRequest();
// Construct the first rowPutChange.
PrimaryKeyBuilder pk1Builder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
pk1Builder.addPrimaryKeyColumn("your_primaryKey", PrimaryKeyValue.fromString("pkValue1"));
// Specify the name of the data table.
RowPutChange rowPutChange1 = new RowPutChange("your_tableName", pk1Builder.build());
// Add columns.
for (int i = 0; i < 10; i++) {
rowPutChange1.addColumn(new Column("Col" + i, ColumnValue.fromLong(i)));
}
// Add rowPutChange1 to the code of the batch operation.
batchWriteRowRequest.addRowChange(rowPutChange1);
// Construct the second rowPutChange.
PrimaryKeyBuilder pk2Builder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
pk2Builder.addPrimaryKeyColumn("your_primaryKey", PrimaryKeyValue.fromString("pkValue2"));
// Specify the name of the data table.
RowPutChange rowPutChange2 = new RowPutChange("your_tableName", pk2Builder.build());
// Add columns.
for (int i = 0; i < 10; i++) {
rowPutChange2.addColumn(new Column("Col" + i, ColumnValue.fromLong(i)));
}
// Add rowPutChange2 to the code of the batch operation.
batchWriteRowRequest.addRowChange(rowPutChange2);
// Construct rowUpdateChange.
PrimaryKeyBuilder pk3Builder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
pk3Builder.addPrimaryKeyColumn("your_primaryKey", PrimaryKeyValue.fromString("pkValue3"));
// Specify the name of the data table.
RowUpdateChange rowUpdateChange = new RowUpdateChange("your_tableName", pk3Builder.build());
// Add columns.
for (int i = 0; i < 10; i++) {
rowUpdateChange.put(new Column("Col" + i, ColumnValue.fromLong(i)));
}
// Delete a column.
rowUpdateChange.deleteColumns("Col0");
// Add rowUpdateChange to the code of the batch operation.
batchWriteRowRequest.addRowChange(rowUpdateChange);
// Construct rowDeleteChange.
PrimaryKeyBuilder pk4Builder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
pk4Builder.addPrimaryKeyColumn("your_primaryKey", PrimaryKeyValue.fromString("pkValue4"));
// Specify the name of the data table.
RowDeleteChange rowDeleteChange = new RowDeleteChange("your_tableName", pk4Builder.build());
// Add rowDeleteChange to the code of the batch operation.
batchWriteRowRequest.addRowChange(rowDeleteChange);
BatchWriteRowResponse response = client.batchWriteRow(batchWriteRowRequest);
System.out.println("Whether all operations are successful:" + response.isAllSucceed());
if (!response.isAllSucceed()) {
for (BatchWriteRowResponse.RowResult rowResult : response.getFailedRows()) {
System.out.println("Failed rows:" + batchWriteRowRequest.getRowChange(rowResult.getTableName(), rowResult.getIndex()).getPrimaryKey());
System.out.println("Cause of failures:" + rowResult.getError());
}
/**
* You can use the createRequestForRetry method to construct another request to retry the operations on failed rows. In this example, only the retry request is constructed.
* We recommend that you use the custom retry policy in Tablestore SDKs as the retry method. This feature allows you to retry failed rows after batch operations are performed. After you specify the retry policy, you do not need to add retry code to call the operation.
*/
BatchWriteRowRequest retryRequest = batchWriteRowRequest.createRequestForRetry(response.getFailedRows());
}
}
FAQ
References
For more information about the sample code that you can use to perform Tablestore data operations, visit the sample code on GitHub.
You can call the BatchWriteRow operation to write up to 200 rows of data at the same time. To concurrently write more than 200 rows of data, use TableStoreWriter. For more information, see Use TableStoreWriter to concurrently write data.
To collect real-time statistics about online applications, such as the number of page views (PVs) on various pages, you can use the atomic counter feature. For more information, see Use the atomic counter feature.
To perform atomic operations to write one or more rows of data, you can use the local transaction feature. For more information, see Use the local transaction feature.