全部產品
Search
文件中心

Tablestore:主鍵列自增

更新時間:Apr 30, 2026

使用 Tablestore SDK for Node.js 為資料表配置自增主鍵列,向自增列寫入資料,並擷取系統產生的自增值。

前提條件

開始前,確保已完成用戶端初始化。詳情請參見初始化Tablestore Client

瞭解自增列行為

自增列在同一分區鍵下產生的值唯一且單調遞增,但不保證連續。

建立含自增主鍵列的資料表

建表時,將某個非分區鍵的主鍵列的 option 設為 AUTO_INCREMENT,即可將其聲明為自增列。該列必須為 INTEGER 類型。一個資料表最多隻能設定一個自增列,且無法為已有資料表添加自增列。

說明

自增列產生的值為 64 位元有符號長整型。只有非分區鍵列支援 AUTO_INCREMENT 選項。

樣本

以下樣本建立資料表 test_table,包含兩個主鍵列:id(分區鍵,STRING 類型)和 incr(自增列,INTEGER 類型)。

function createTableSample() {
    var createParams = {
        tableMeta: {
            tableName: 'test_table',
            primaryKey: [
                {
                    name: 'id',
                    type: 'STRING'       // 分區鍵——每次寫入時由調用方提供
                },
                {
                    name: 'incr',
                    type: 'INTEGER',
                    option: 'AUTO_INCREMENT'  // 自增列——Tablestore 自動產生該值
                },
            ]
        },
        tableOptions: {
            timeToLive: -1,   // -1 表示資料永不到期
            maxVersions: 1
        },
        reservedThroughput: {
            capacityUnit: {
                read: 0,
                write: 0
            }
        },
    };

    client.createTable(createParams, function (err, data) {
        if (err) {
            console.error('error:', err);
            return;
        }
        console.log('success:', data);
    });
}

寫入資料

寫入資料行時,將自增列的值設為 TableStore.PK_AUTO_INCR——這是一個預留位置,Tablestore 會用系統產生的值替換它。如需擷取產生的自增值(例如用於後續查詢或更新),在 returnContent 中將 returnType 設為 TableStore.ReturnType.Primarykey

樣本

以下樣本向 test_table 寫入一行資料,並列印系統產生的主鍵資訊。

function putRowSample() {
    var putParams = {
        tableName: 'test_table',
        condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null),
        primaryKey: [
            { id: 'row1' },
            // 使用 PK_AUTO_INCR 作為預留位置,Tablestore 會將其替換為自動產生的值
            { incr: TableStore.PK_AUTO_INCR }
        ],
        attributeColumns: [
            { 'col1': 'val1' }
        ],
        // 返回完整主鍵,以便後續查詢中使用產生的 incr 值
        returnContent: { returnType: TableStore.ReturnType.Primarykey }
    };

    client.putRow(putParams, function (err, data) {
        if (err) {
            console.error('error:', err);
            return;
        }

        // 請求中繼資料及消耗的讀寫 CU
        console.log("RequestId: ", data.RequestId);
        console.log("Read CU Cost: ", data.consumed.capacityUnit.read);
        console.log("Write CU Cost: ", data.consumed.capacityUnit.write);

        // 列印產生的主鍵資訊(含自增值)
        // 僅在 returnType 設為 Primarykey 時返回
        if (data.row.primaryKey) {
            console.log(JSON.stringify(data.row.primaryKey));
        }
    });
}