设置非分区键的主键列为自增列后,在写入数据时,无需为自增列设置具体值,表格存储会自动生成自增列的值。该值在分区键级别唯一且严格递增。

前提条件

已初始化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));
        });
    
    }