本文介紹如何通過 Java SDK 批量讀取Table Store中的資料,支援查詢多個表的資料。
注意事項
單次批量讀取操作最多支援讀取 100 行資料。
前提條件
方法說明
public BatchGetRowResponse batchGetRow(BatchGetRowRequest batchGetRowRequest) throws TableStoreException, ClientException範例程式碼
以下範例程式碼用於讀取 test_table 表中主索引值為 row1 和 row2 的兩行資料。
public static void batchGetRowExample(SyncClient client) {
// 構造查詢條件
MultiRowQueryCriteria multiRowQueryCriteria = new MultiRowQueryCriteria("test_table");
// 添加第 1 行主鍵資訊
PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
primaryKeyBuilder.addPrimaryKeyColumn("id", PrimaryKeyValue.fromString("row1"));
multiRowQueryCriteria.addRow(primaryKeyBuilder.build());
// 添加第 2 行主鍵資訊
primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
primaryKeyBuilder.addPrimaryKeyColumn("id", PrimaryKeyValue.fromString("row2"));
multiRowQueryCriteria.addRow(primaryKeyBuilder.build());
// 設定查詢版本
multiRowQueryCriteria.setMaxVersions(1);
// 調用 batchGetRow 方法進行批量資料查詢
BatchGetRowRequest batchGetRowRequest = new BatchGetRowRequest();
batchGetRowRequest.addMultiRowQueryCriteria(multiRowQueryCriteria);
BatchGetRowResponse batchGetRowResponse = client.batchGetRow(batchGetRowRequest);
// 返回結果處理
System.out.println("* RequestId: " + batchGetRowResponse.getRequestId());
System.out.println("* Is all succeeded: " + batchGetRowResponse.isAllSucceed());
// 列印讀取成功的行
System.out.println("* Succeeded Rows: ");
for(BatchGetRowResponse.RowResult rowResult:batchGetRowResponse.getSucceedRows())
System.out.println(rowResult.getRow());
// 列印讀取失敗的行
if(!batchGetRowResponse.isAllSucceed()) {
System.out.println("* Failed Rows: ");
for(BatchGetRowResponse.RowResult rowResult:batchGetRowResponse.getFailedRows())
System.out.println(rowResult.getTableName() + " | " + batchGetRowRequest.getPrimaryKey(rowResult.getTableName(), rowResult.getIndex()) + " | " + rowResult.getError());
}
}您可以在批量讀取資料時參考以下範例程式碼進行參數設定。
讀取多張表的資料。批量讀取支援一次讀取多張表的資料,您需要為每張表指定一個MultiRowQueryCriteria。
// 構造第 2 個表的查詢條件 MultiRowQueryCriteria multiRowQueryCriteria1 = new MultiRowQueryCriteria("orders_small"); // 添加第 1 行主鍵資訊 primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder(); primaryKeyBuilder.addPrimaryKeyColumn("order_id", PrimaryKeyValue.fromString("90fb478c-1360-11f0-a34d-00163e30a2a9")); multiRowQueryCriteria1.addRow(primaryKeyBuilder.build()); // 設定查詢版本 multiRowQueryCriteria1.setMaxVersions(1); // Request 添加 MultiRowQueryCriteria batchGetRowRequest.addMultiRowQueryCriteria(multiRowQueryCriteria1);設定讀取的資料版本範圍,結果只返回版本範圍內的資料。
// 設定查詢的資料版本範圍為目前時間往前一天 multiRowQueryCriteria.setTimeRange(new TimeRange(System.currentTimeMillis() - 86400*1000, System.currentTimeMillis()));指定讀取的屬性列。
multiRowQueryCriteria.addColumnsToGet("col1");