This topic describes how to read a single row of data from a Tablestore table by using Tablestore SDK for Java.
Usage notes
When you read data from a data table, you must provide the complete primary key, including the value of the auto-increment primary key column.
Prerequisites
A client is initialized. For more information, see Initialize a Tablestore client.
Method description
public GetRowResponse getRow(GetRowRequest getRowRequest) throws TableStoreException, ClientExceptionSample code
The following sample code reads a single row of data with the primary key value of row1.
public static void getRowExample(SyncClient client) {
// Construct the primary key.
PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
primaryKeyBuilder.addPrimaryKeyColumn("id", PrimaryKeyValue.fromString("row1"));
PrimaryKey primaryKey = primaryKeyBuilder.build();
// Construct the row data to read.
SingleRowQueryCriteria singleRowQueryCriteria = new SingleRowQueryCriteria("test_table", primaryKey);
singleRowQueryCriteria.setMaxVersions(1);
// Call the getRow method to read the row data.
GetRowRequest getRowRequest = new GetRowRequest(singleRowQueryCriteria);
GetRowResponse getRowResponse = client.getRow(getRowRequest);
// Return the result.
System.out.println("RequestId: " + getRowResponse.getRequestId());
System.out.println("Read CU Cost: " + getRowResponse.getConsumedCapacity().getCapacityUnit().getReadCapacityUnit());
System.out.println("Write CU Cost: " + getRowResponse.getConsumedCapacity().getCapacityUnit().getWriteCapacityUnit());
System.out.println("Row Data: \n" + getRowResponse.getRow());
}Specify the version range of data to read. Only data within the version range is returned.
// Set the version range of data to read to one day before the current time. singleRowQueryCriteria.setTimeRange(new TimeRange(System.currentTimeMillis() - 86400*1000, System.currentTimeMillis()));Specify the attribute columns to read.
singleRowQueryCriteria.addColumnsToGet("col2");