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

前提条件

已初始化Client。具体操作,请参见初始化

使用方法

  1. 创建表时,将非分区键的主键列设置为自增列。

    只有整型的主键列才能设置为自增列,系统自动生成的自增列值为64位的有符号整型。

  2. 写入数据时,无需为自增列设置具体值,只需将相应主键指定为自增主键。

    如果需要获取写入数据后系统自动生成的自增列的值,将ReturnType设置为RT_PK,可以在数据写入成功后返回自增列的值。

    查询数据时,需要完整的主键值。通过设置PutRow、UpdateRow或者BatchWriteRow中的ReturnType为RT_PK可以获取完整的主键值。

    说明 如果要更新已存在的行,请先通过GetRange接口获取要更新的行主键信息,然后再进行数据更新。

示例

主键自增列功能主要涉及创建表(CreateTable)和写数据(PutRow、UpdateRow和BatchWriteRow)两类接口。

  1. 创建表

    创建表时,只需将自增的主键属性设置为AUTO_INCREMENT。

    import (
        "fmt"
        "github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
    )
    
    func CreateTableKeyAutoIncrementSample(client *tablestore.TableStoreClient) {
        createtableRequest := new(tablestore.CreateTableRequest)
        //创建表,数据表中包括三个主键:pk1,String类型;pk2,INTEGER类型,为自增列;pk3,Binary类型。
        tableMeta := new(tablestore.TableMeta)
        tableMeta.TableName = "incrementsampletable"
        tableMeta.AddPrimaryKeyColumn("pk1", tablestore.PrimaryKeyType_STRING)
        tableMeta.AddPrimaryKeyColumnOption("pk2", tablestore.PrimaryKeyType_INTEGER, tablestore.AUTO_INCREMENT)
        tableMeta.AddPrimaryKeyColumn("pk3", tablestore.PrimaryKeyType_BINARY)
        tableOption := new(tablestore.TableOption)
        tableOption.TimeToAlive = -1
        tableOption.MaxVersion = 3
        reservedThroughput := new(tablestore.ReservedThroughput)
        reservedThroughput.Readcap = 0
        reservedThroughput.Writecap = 0
        createtableRequest.TableMeta = tableMeta
        createtableRequest.TableOption = tableOption
        createtableRequest.ReservedThroughput = reservedThroughput
    
        client.CreateTable(createtableRequest)
    }
  2. 写数据

    写入数据时,无需为自增列设置具体值,只需将相应主键指定为自增主键。

    import (
        "fmt"
        "github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
    )
    
    func PutRowWithKeyAutoIncrementSample(client *tablestore.TableStoreClient) {
        fmt.Println("begin to put row")
        putRowRequest := new(tablestore.PutRowRequest)
        putRowChange := new(tablestore.PutRowChange)
        putRowChange.TableName = "incrementsampletable"
        //设置主键,必须按照创建数据表时的顺序添加主键,并且需要指定pk2为自增主键。
        putPk := new(tablestore.PrimaryKey)
        putPk.AddPrimaryKeyColumn("pk1", "pk1value1")
        putPk.AddPrimaryKeyColumnWithAutoIncrement("pk2")
        putPk.AddPrimaryKeyColumn("pk3", []byte("pk3"))
        putRowChange.PrimaryKey = putPk
        putRowChange.AddColumn("col1", "col1data1")
        putRowChange.AddColumn("col2", int64(100))
        putRowChange.SetCondition(tablestore.RowExistenceExpectation_IGNORE)
        putRowRequest.PutRowChange = putRowChange
        _, err := client.PutRow(putRowRequest)
    
        if err != nil {
            fmt.Println("put row failed with error:", err)
        } else {
            fmt.Println("put row finished")
        }
    }