全部產品
Search
文件中心

Tablestore:主鍵列自增

更新時間:Jun 20, 2025

本文介紹如何通過 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)
    }
}