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

前提條件

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

使用方法

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

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

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

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

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

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

樣本

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

  1. 建立表

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

    var TableStore = require('../index.js');
    var Long = TableStore.Long;
    var client = require('./client');
    
    var tableName = "autoIncTable";
    var pk1 = "stringPK";
    var pk2 = "autoIncPK";
    
    function createTableWithAutoIncrementPk() {
        var createParams = {
            tableMeta: {
                tableName: tableName,
                primaryKey: [
                    {
                        name: pk1,
                        type: 'STRING'
                    },
                    {
                        name: pk2,
                        type: 'INTEGER',
                        option: 'AUTO_INCREMENT'//自增列,指定option為AUTO_INCREMENT。
                    },
                ]
            },
            reservedThroughput: {
                capacityUnit: {
                    read: 0,
                    write: 0
                }
            },
            tableOptions: {
                timeToLive: -1,//資料的到期時間,單位秒,-1表示資料永不到期。假如設定到期時間為一年,即為365*24*3600。
                maxVersions: 1//儲存的最大版本數,設定為1表示每列上最多儲存一個版本(儲存最新的版本)。
            },
        };
    
        client.createTable(createParams, function (err, data) {
            if (err) {
                console.log('error:', err);
                return;
            }
            console.log('create table success');
        });
    }
  2. 寫資料

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

    var TableStore = require('../index.js');
    var Long = TableStore.Long;
    var client = require('./client');
    
    var tableName = "autoIncTable";
    var pk1 = "stringPK";
    var pk2 = "autoIncPK";
    
    function putRow() {
        var putParams = {
            tableName: tableName,
            condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null),
            primaryKey: [
                { stringPK: 'pk1' },
                { autoIncPK: TableStore.PK_AUTO_INCR }
            ],
            attributeColumns: [
                { 'col1': 'col1val' }
            ],
            returnContent: { returnType: TableStore.ReturnType.Primarykey }
        };
    
        client.putRow(putParams, function (err, data) {
            if (err) {
                console.log('error:', err);
                return;
            }
    
            console.log('put row success,autoIncrement pk value:' + JSON.stringify(data.row.primaryKey));
        });
    
    }