主键列自增

本文介绍如何通过 Node.js SDK 为数据表设置主键列自增,以及如何为自增列写入数据并获取生成的自增值。

注意事项

自增列生成的自增值在分区键级别唯一且严格递增,但不保证连续。

前提条件

初始化Tablestore Client

设置主键列自增

您可以在创建数据表时将非分区主键列设置为自增列,对于已创建的数据表,无法设置自增列。

说明

只有整型的非分区主键列才能设置为自增列,一个数据表最多只能设置一个自增列,自增列生成的值为 64 位有符号长整型。

示例代码

以下示例代码创建了一个数据表 test_table,该表的主键包括分区键 id 和自增列 incr。

function createTableSample() {
    var createParams = {
        tableMeta: {
            tableName: 'test_table',
            primaryKey: [
                {
                    name: 'id',
                    type: 'STRING'
                },
                {
                    name: 'incr',
                    type: 'INTEGER',
                    option: 'AUTO_INCREMENT'
                },
            ]
        },
        tableOptions: {
            timeToLive: -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);
    });
}

写入数据

为自增列写入数据时,只需要将自增列的值设置为占位符。如果要获取生成的自增值用于数据查询和更新,还需要设置 returnType 的返回类型为 Primarykey。

示例代码

以下示例代码在 test_table 表中写入一行数据,同时获取并打印写入行数据的主键信息。

function putRowSample() {
    var putParams = {
        tableName: 'test_table',
        condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null),
        primaryKey: [
            { id: 'row1' },
            // 设置自增列为占位符
            { incr: TableStore.PK_AUTO_INCR }
        ],
        attributeColumns: [
            { 'col1': 'val1' }
        ],
        // 设置返回类型为 Primarykey,返回写入行数据的主键信息
        returnContent: { returnType: TableStore.ReturnType.Primarykey }
    };

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

        // RequestId 和 读写 CU 消耗
        console.log("RequestId: ", data.RequestId);
        console.log("Read CU Cost: ", data.consumed.capacityUnit.read);
        console.log("Write CU Cost: ", data.consumed.capacityUnit.write);

        // 获取返回的主键信息并打印,如果不设置返回类型为 Primarykey,默认不返回主键信息
        if (data.row.primaryKey) {
            console.log(JSON.stringify(data.row.primaryKey));
        }
    });
}