全部產品
Search
文件中心

Tablestore:主鍵列自增

更新時間:Jul 23, 2026

Java SDK 可在建立資料表時將非分區主鍵列配置為自增列,並在寫入資料時擷取服務端產生的自增值。

前提條件

  • 安裝Tablestore Java SDK並初始化用戶端。

  • 使用 Tablestore Java SDK 4.2.0 或更高版本。

功能說明

主鍵列自增包含配置自增列、寫入預留位置和擷取自增值三個步驟。

說明

只能在建立資料表時將非分區主鍵列配置為自增列。自增列必須為整數類型,每張資料表最多配置一個自增列。服務端產生的自增值為 64 位元有符號整數。

自增值在同一分區鍵內唯一且嚴格遞增,但不保證連續。

設定主鍵列自增

建立資料表時,將非分區主鍵列的 option 設定為 PrimaryKeyOption.AUTO_INCREMENT

以下樣本建立 example_table 資料表。該表使用 id 作為分區鍵,使用 incr 作為自增主鍵列。

說明

建立資料表後,等待資料表載入完成再寫入資料。

String tableName = "example_table";

TableMeta tableMeta = new TableMeta(tableName);
tableMeta.addPrimaryKeyColumn(new PrimaryKeySchema("id", PrimaryKeyType.STRING));
tableMeta.addPrimaryKeyColumn(new PrimaryKeySchema(
        "incr", PrimaryKeyType.INTEGER, PrimaryKeyOption.AUTO_INCREMENT));

TableOptions tableOptions = new TableOptions(-1, 1);
CreateTableRequest request = new CreateTableRequest(tableMeta, tableOptions);
client.createTable(request);

寫入資料並擷取自增值

寫入資料時,將自增列值設定為 PrimaryKeyValue.AUTO_INCREMENT。需要擷取產生的自增值時,將傳回型別設定為 ReturnType.RT_PK;否則響應不返回主鍵資訊。

以下樣本向 example_table 寫入一行資料,並從響應中擷取 incr 列的自增值。

PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
primaryKeyBuilder.addPrimaryKeyColumn("id", PrimaryKeyValue.fromString("partition-a"));
primaryKeyBuilder.addPrimaryKeyColumn("incr", PrimaryKeyValue.AUTO_INCREMENT);
PrimaryKey primaryKey = primaryKeyBuilder.build();

RowPutChange rowPutChange = new RowPutChange("example_table", primaryKey);
rowPutChange.addColumn("payload", ColumnValue.fromString("example-value"));
rowPutChange.setReturnType(ReturnType.RT_PK);

PutRowResponse response = client.putRow(new PutRowRequest(rowPutChange));
long generatedValue = response.getRow().getPrimaryKey()
        .getPrimaryKeyColumn("incr").getValue().asLong();
System.out.println("Generated value: " + generatedValue);

參數說明

PrimaryKeySchema 參數

以下參數用於定義自增主鍵列。

名稱

類型

說明

name(必選)

String

自增主鍵列名稱。

type(必選)

PrimaryKeyType

自增主鍵列的資料類型,必須設定為 INTEGER

option(必選)

PrimaryKeyOption

主鍵列配置,必須設定為 AUTO_INCREMENT

RowPutChange 參數

以下參數控制自增列寫入和返回結果。

名稱

類型

說明

primaryKey(必選)

PrimaryKey

寫入行的主鍵。主鍵列的名稱、順序和類型必須與資料表的主鍵結構一致;自增列值必須設定為 PrimaryKeyValue.AUTO_INCREMENT

returnType(可選)

ReturnType

傳回型別,預設為 RT_NONE,不返回主鍵資訊。設定為 RT_PK 時,響應返回包含自增值的完整主鍵。

傳回值

PutRowResponse 中與主鍵列自增直接相關的返回欄位如下。

欄位

類型

說明

row

Row

通過 getRow() 擷取寫入行的主鍵資訊。僅當 returnType 設定為 RT_PK 時返回,其中包含服務端產生的自增值。