主键列自增

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

注意事项

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

前提条件

初始化Tablestore Client

设置主键列自增

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

说明

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

示例代码

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

func CreateTableSample(client *tablestore.TableStoreClient) {
    tableMeta := new(tablestore.TableMeta)
    tableMeta.TableName = "test_table"
    tableMeta.AddPrimaryKeyColumn("id", tablestore.PrimaryKeyType_STRING)
    tableMeta.AddPrimaryKeyColumnOption("incr", tablestore.PrimaryKeyType_INTEGER, tablestore.AUTO_INCREMENT)

    tableOption := new(tablestore.TableOption)
    tableOption.MaxVersion = 1
    tableOption.TimeToAlive = -1

    reservedThroughput := new(tablestore.ReservedThroughput)

    createTableRequest := new(tablestore.CreateTableRequest)
    createTableRequest.TableMeta = tableMeta
    createTableRequest.TableOption = tableOption
    createTableRequest.ReservedThroughput = reservedThroughput
    _, err := client.CreateTable(createTableRequest)
    if err != nil {
        fmt.Println("Failed to create table with error:", err)
    } else {
        fmt.Println("Create table finished.")
    }
}

写入数据

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

示例代码

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

func PutRowSample(client *tablestore.TableStoreClient) {
    // 构造主键
    putPrimaryKey := new(tablestore.PrimaryKey)
    putPrimaryKey.AddPrimaryKeyColumn("id", "row1")
    // 设置自增列
    putPrimaryKey.AddPrimaryKeyColumnWithAutoIncrement("incr")

    // 构造写入行数据
    putRowChange := new(tablestore.PutRowChange)
    putRowChange.TableName = "test_table"
    putRowChange.PrimaryKey = putPrimaryKey
    putRowChange.AddColumn("col1", "val1")
    putRowChange.SetCondition(tablestore.RowExistenceExpectation_IGNORE)
    // 设置返回类型为 ReturnType_RT_PK,返回写入行数据的主键信息
    putRowChange.ReturnType = tablestore.ReturnType_RT_PK

    // 调用 putRow 方法写入行数据
    putRowRequest := new(tablestore.PutRowRequest)
    putRowRequest.PutRowChange = putRowChange
    response, err := client.PutRow(putRowRequest)
    if err != nil {
        fmt.Println("Failed to put row with error:", err)
    } else {
        // RequestId 和 读写 CU 消耗
        fmt.Printf("RequestId: %s \n", response.RequestId)
        fmt.Printf("Read CU Cost: %d \n", response.ConsumedCapacityUnit.Read)
        fmt.Printf("Write CU Cost: %d \n", response.ConsumedCapacityUnit.Write)

        // 获取返回的主键信息并打印,如果不设置返回类型为 ReturnType_RT_PK,默认不返回主键信息
        fmt.Println(response.PrimaryKey)
    }
}