全部產品
Search
文件中心

Tablestore:主鍵列自增

更新時間:May 15, 2025

本文介紹如何通過 Java SDK 為資料表設定主鍵列自增,以及如何為自增列寫入資料並擷取產生的自增值。

注意事項

  • Table Store Java SDK 從 4.2.0 版本開始支援主鍵列自增。

  • 自增列產生的自增值在分區鍵層級唯一且嚴格遞增,但不保證連續。

前提條件

初始化Tablestore Client

設定主鍵列自增

您可以在建立資料表時將非分區主鍵列設定為自增列,對於已建立的資料表,無法設定自增列。

說明

只有整型的主鍵列才能設定為自增列,一個資料表最多隻能設定一個自增列,自增列產生的值為 64 位元有符號長整型。

範例程式碼

以下範例程式碼建立了一個資料表 test_table,該表的主鍵包括分區鍵 id 和自增列 incr。

public static void createTableTest(SyncClient client) {
    TableMeta tableMeta = new TableMeta("test_table");
    tableMeta.addPrimaryKeyColumn(new PrimaryKeySchema("id", PrimaryKeyType.STRING));
    tableMeta.addPrimaryKeyColumn(new PrimaryKeySchema("incr", PrimaryKeyType.INTEGER, PrimaryKeyOption.AUTO_INCREMENT));

    TableOptions tableOptions = new TableOptions();
    tableOptions.setMaxVersions(1);
    tableOptions.setTimeToLive(-1);

    CreateTableRequest createTableRequest = new CreateTableRequest(tableMeta, tableOptions);
    client.createTable(createTableRequest);
}

寫入資料

為自增列寫入資料時,只需要將自增列的值設定為預留位置。如果要擷取產生的自增值用於資料查詢和更新,還需要設定 rowPutChange 的傳回型別為 RT_PK。

範例程式碼

以下範例程式碼在 test_table 表中寫入一行資料,同時擷取並列印寫入行資料的主鍵資訊。

public static void putRowTest(SyncClient client) {
    // 構造主鍵
    PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
    primaryKeyBuilder.addPrimaryKeyColumn("id", PrimaryKeyValue.fromString("row1"));
    // 設定自增列為預留位置
    primaryKeyBuilder.addPrimaryKeyColumn("incr", PrimaryKeyValue.AUTO_INCREMENT);
    PrimaryKey primaryKey = primaryKeyBuilder.build();

    // 構造寫入行資料
    RowPutChange rowPutChange = new RowPutChange("test_table", primaryKey);
    rowPutChange.addColumn("col1", ColumnValue.fromString("val1"));
    // 設定傳回型別為 RT_PK,返回寫入行資料的主鍵資訊
    rowPutChange.setReturnType(ReturnType.RT_PK);

    // 調用 putRow 方法寫入行資料
    PutRowRequest putRowRequest = new PutRowRequest();
    putRowRequest.setRowChange(rowPutChange);
    PutRowResponse putRowResponse = client.putRow(putRowRequest);

    // RequestId 和 讀寫 CU 消耗
    System.out.println("RequestId: " + putRowResponse.getRequestId());
    System.out.println("Read CU Cost: " + putRowResponse.getConsumedCapacity().getCapacityUnit().getReadCapacityUnit());
    System.out.println("Write CU Cost: " + putRowResponse.getConsumedCapacity().getCapacityUnit().getWriteCapacityUnit());

    // 擷取返回的主鍵資訊並列印,如果不設定傳回型別為 RT_PK,預設不返回主鍵資訊
    Row row = putRowResponse.getRow();
    if(row != null)
        System.out.println(row.getPrimaryKey().toString());
}