全部產品
Search
文件中心

Tablestore:主鍵列自增

更新時間:Jun 26, 2025

本文介紹如何通過 Python SDK 為資料表設定主鍵列自增,以及如何為自增列寫入資料並擷取產生的自增值。

注意事項

  • Table Store Python SDK 從 4.0.0 版本開始支援主鍵列自增。

  • 自增列產生的自增值在分區鍵層級唯一且嚴格遞增,但不保證連續。

前提條件

初始化Tablestore Client

設定主鍵列自增

您可以在建立資料表時將非分區主鍵列設定為自增列,對於已建立的資料表,無法設定自增列。

說明

只有整型的非分區主鍵列才能設定為自增列,一個資料表最多隻能設定一個自增列,自增列產生的值為 64 位元有符號長整型。

範例程式碼

以下範例程式碼建立了一個資料表 test_table,該表的主鍵包括分區鍵 id 和自增列 incr。

schema_of_primary_key = [('id', 'STRING'), ('incr', 'INTEGER', PK_AUTO_INCR)]
table_meta = TableMeta('test_table', schema_of_primary_key)
table_options = TableOptions()
reserved_throughput = ReservedThroughput(CapacityUnit())
try:
    client.create_table(table_meta, table_options, reserved_throughput)
    print("Create table succeeded.")
except Exception as e:
    print("Create table failed. %s" % e)

寫入資料

為自增列寫入資料時,只需要將自增列的值設定為預留位置。如果要擷取產生的自增值用於資料查詢和更新,還需要設定 put_row 的傳回型別為 RT_PK。

範例程式碼

以下範例程式碼在 test_table 表中寫入一行資料,同時擷取並列印寫入行資料的主鍵資訊。

# 構造主鍵
primary_key = [('id', 'row1'), ('incr', PK_AUTO_INCR)]

# 構造寫入行資料
attribute_columns = [('col1', 'val1')]
row = Row(primary_key, attribute_columns)

try:
    # 調用 putRow 方法寫入行資料,並設定傳回型別為 RT_PK(返回寫入行資料的主鍵資訊)
    consumed, return_row = client.put_row('test_table', row, return_type=ReturnType.RT_PK)

    # 讀寫 CU 消耗
    print('Read CU Cost: %s' % consumed.read)
    print('Write CU Cost: %s' % consumed.write)

    # 擷取返回的主鍵資訊並列印,如果不設定傳回型別為 RT_PK,預設不返回主鍵資訊
    if return_row is not None:
        print('Primary key: %s' % return_row.primary_key)
except Exception as e:
    print("Write failed. %s" % e)