主键列自增

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

注意事项

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

前提条件

初始化Tablestore Client

设置主键列自增

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

说明

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

示例代码

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

public static void CreateSample(OTSClient client)
{
    try
    {
        PrimaryKeySchema primaryKeySchema = new PrimaryKeySchema
        {
            { "id", ColumnValueType.String },
            { "incr", ColumnValueType.Integer, PrimaryKeyOption.AUTO_INCREMENT}
        };
        TableMeta tableMeta = new TableMeta("test_table", primaryKeySchema);
        CapacityUnit reservedThroughput = new CapacityUnit(0, 0);

        CreateTableRequest request = new CreateTableRequest(tableMeta, reservedThroughput);
        client.CreateTable(request);
        Console.WriteLine("Create table succeeded.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Create table failed, exception:{ex.Message}");
    }
}

写入数据

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

示例代码

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

public static void PutRowSample(OTSClient client)
{
    try
    {
        // 构造主键
        PrimaryKey primaryKey = new PrimaryKey
        {
            { "id", new ColumnValue("row1") },
            { "incr",  ColumnValue.AUTO_INCREMENT }
        };

        // 构造写入行数据
        AttributeColumns attribute = new AttributeColumns
        {
            { "col1", new ColumnValue("val1") }
        };
        PutRowRequest request = new PutRowRequest("test_table", new Condition(RowExistenceExpectation.IGNORE), primaryKey, attribute);
        // 设置返回类型为 ReturnType.RT_PK,返回写入行数据的主键信息
        request.RowPutChange.ReturnType = ReturnType.RT_PK;

        // 调用 PutRow 方法写入行数据
        PutRowResponse response = client.PutRow(request);

        // RequestId 和 读写 CU 消耗
        Console.WriteLine("RequestId: " + response.RequestID);
        Console.WriteLine("Read CU Cost: " + response.ConsumedCapacityUnit.Read);
        Console.WriteLine("Write CU Cost: " + response.ConsumedCapacityUnit.Write);

        // 获取返回的主键信息并打印,如果不设置返回类型为 ReturnType.RT_PK,默认不返回主键信息
        Console.WriteLine(response.Row.PrimaryKey.ToString());
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Put Row failed, exception:{ex.Message}");
    }
}