本文介紹如何通過 Java SDK 讀取Table Store資料表的單行資料。
注意事項
讀取資料時需要提供包含自增主鍵列值在內的完整主索引值。
前提條件
方法說明
public GetRowResponse getRow(GetRowRequest getRowRequest) throws TableStoreException, ClientException範例程式碼
以下範例程式碼讀取了主索引值為 row1 的單行資料。
public static void getRowExample(SyncClient client) {
// 構造主鍵
PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
primaryKeyBuilder.addPrimaryKeyColumn("id", PrimaryKeyValue.fromString("row1"));
PrimaryKey primaryKey = primaryKeyBuilder.build();
// 構造讀取的行資料
SingleRowQueryCriteria singleRowQueryCriteria = new SingleRowQueryCriteria("test_table", primaryKey);
singleRowQueryCriteria.setMaxVersions(1);
// 調用 getRow 方法讀取行資料
GetRowRequest getRowRequest = new GetRowRequest(singleRowQueryCriteria);
GetRowResponse getRowResponse = client.getRow(getRowRequest);
// 返回結果處理
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());
}設定讀取的資料版本範圍,結果只返回版本範圍內的資料。
// 設定查詢的資料版本範圍為目前時間往前一天 singleRowQueryCriteria.setTimeRange(new TimeRange(System.currentTimeMillis() - 86400*1000, System.currentTimeMillis()));指定讀取的屬性列。
singleRowQueryCriteria.addColumnsToGet("col2");