設定非分區鍵的主鍵列為自增列後,在寫入資料時,無需為自增列設定具體值,Tablestore會自動產生自增列的值。該值在分區鍵層級唯一且嚴格遞增。

说明 從Java SDK 4.2.0版本開始支援主鍵列自增功能。

前提條件

已初始化Client。具體操作,請參見初始化

使用方法

  1. 建立表時,將非分區鍵的主鍵列設定為自增列。

    只有整型的主鍵列才能設定為自增列,系統自動產生的自增列值為64位的有符號長整型。

  2. 寫入資料時,無需為自增列設定具體值,只需將自增列的值設定為預留位置。

    如果需要擷取寫入資料後系統自動產生的自增列的值,將ReturnType設定為RT_PK,可以在資料寫入成功後返回自增列的值。

    查詢資料時,需要完整的主索引值。通過設定PutRow、UpdateRow或者BatchWriteRow中的ReturnType為RT_PK可以擷取完整的主索引值。

    说明 如果要更新已存在的行,請先通過GetRange介面擷取要更新的行主鍵資訊,然後再進行資料更新。

樣本

主鍵自增列功能主要涉及建立表(CreateTable)和寫資料(PutRow、UpdateRow和BatchWriteRow)兩類介面。

  1. 建立表

    建立表時,只需將自增的主鍵屬性設定為AUTO_INCREMENT。

    private static void createTable(SyncClient client) {
            TableMeta tableMeta = new TableMeta("table_name");
            //第一列為分區鍵。
            tableMeta.addPrimaryKeyColumn(new PrimaryKeySchema("PK_1", PrimaryKeyType.STRING));
            //第二列為自增列,類型為INTEGER,屬性為AUTO_INCREMENT。
            tableMeta.addPrimaryKeyColumn(new PrimaryKeySchema("PK_2", PrimaryKeyType.INTEGER, PrimaryKeyOption.AUTO_INCREMENT));
            int timeToLive = -1;  //資料永不到期。
            int maxVersions = 1;  //只儲存一個資料版本。
            TableOptions tableOptions = new TableOptions(timeToLive, maxVersions);
            CreateTableRequest request = new CreateTableRequest(tableMeta, tableOptions);
            client.createTable(request);
        }
  2. 寫資料

    寫入資料時,無需為自增列設定具體值,只需將自增列的值設定為預留位置AUTO_INCREMENT。

        private static void putRow(SyncClient client, String receive_id) {
            //構造主鍵。
            PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
            //第一列的值為md5(receive_id)前4位。
            primaryKeyBuilder.addPrimaryKeyColumn("PK_1", PrimaryKeyValue.fromString("Hangzhou"));
            //第二列是主鍵自增列,此處無需填入具體值,只需要一個預留位置AUTO_INCREMENT,Tablestore會自動產生此值。
            primaryKeyBuilder.addPrimaryKeyColumn("PK_2", PrimaryKeyValue.AUTO_INCREMENT);
            PrimaryKey primaryKey = primaryKeyBuilder.build();
            RowPutChange rowPutChange = new RowPutChange("table_name", primaryKey);
            //此處設定傳回型別為RT_PK,即在返回結果中包含PK列的值。如果不設定ReturnType,預設不返回。
            rowPutChange.setReturnType(ReturnType.RT_PK);
            //加入屬性列。
            rowPutChange.addColumn(new Column("content", ColumnValue.fromString("content")));
            //寫入資料到Tablestore。
            PutRowResponse response = client.putRow(new PutRowRequest(rowPutChange));
            //列印返回的PK列。
            Row returnRow = response.getRow();
            if (returnRow != null) {
                System.out.println("PrimaryKey:" + returnRow.getPrimaryKey().toString());
            }
            //列印消耗的CU。
            CapacityUnit  cu = response.getConsumedCapacity().getCapacityUnit();
            System.out.println("Read CapacityUnit:" + cu.getReadCapacityUnit());
            System.out.println("Write CapacityUnit:" + cu.getWriteCapacityUnit());
        }