全部產品
Search
文件中心

Tablestore:主鍵列自增

更新時間:Jun 26, 2025

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