全部產品
Search
文件中心

Tablestore:讀取單行資料

更新時間:Jun 27, 2025

本文介紹如何通過 Java SDK 讀取Table Store資料表的單行資料。

注意事項

讀取資料時需要提供包含自增主鍵列值在內的完整主索引值。

前提條件

初始化 Tablestore Client

方法說明

public GetRowResponse getRow(GetRowRequest getRowRequest) throws TableStoreException, ClientException

GetRowRequest參數說明

  • rowQueryCriteria(必選)SingleRowQueryCriteria:讀取單行資料資訊,包含以下參數。

    名稱

    類型

    說明

    tableName(必選)

    String

    資料表名稱。

    primaryKey(必選)

    PrimaryKey

    主鍵資訊,包括主鍵列名稱和主索引值。

    • 主鍵列資料類型包括 STRING、INTEGER 和 BINARY。

    • 主鍵個數和類型必須與資料表的主鍵保持一致。

    maxVersions(可選)

    OptionalValue<Integer>

    最大版本數。

    • 必須設定最大版本數和版本範圍的其中一個。

    • 如果符合查詢條件的資料版本數量超過設定的最大版本數,按從新到舊的順序返回指定版本數量的資料。

    timeRange(可選)

    OptionalValue<TimeRange>

    資料版本範圍。

    • 必須設定最大版本數和版本範圍的其中一個。

    • Table Store資料表的每個屬性列可以有不同的資料版本,設定版本範圍後,僅返回版本範圍內的資料。

    columnsToGet(可選)

    Set<String>

    指定讀取的資料列,可以是主鍵列或屬性列。

    • 不設定columnsToGet時,返回整行資料。

    • 設定columnsToGet時,如果讀取的行資料不包含任何指定的資料列,將返回 null。

    filter(可選)

    OptionalValue<Filter>

    過濾條件,詳情請參見過濾器

    • 如果同時設定columnsToGet和filter,先按columnsToGet篩選合格資料行,再按filter條件過濾資料。

範例程式碼

以下範例程式碼讀取了主索引值為 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");

相關文檔