設定非分區鍵的主鍵列為自增列後,在寫入資料時,無需為自增列設定具體值,Tablestore會自動產生自增列的值。該值在分區鍵層級唯一且嚴格遞增。

前提條件

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