設定非分區鍵的主鍵列為自增列後,在寫入資料時,無需為自增列設定具體值,Tablestore會自動產生自增列的值。該值在分區鍵層級唯一且嚴格遞增。
前提條件
已初始化Client。具體操作,請參見初始化。
使用方法
- 建立表時,將非分區鍵的主鍵列設定為自增列。
只有整型的主鍵列才能設定為自增列,系統自動產生的自增列值為64位的有符號長整型。
- 寫入資料時,無需為自增列設定具體值,只需將自增列的值設定為預留位置。
如果需要擷取寫入資料後系統自動產生的自增列的值,將ReturnType設定為RT_PK,可以在資料寫入成功後返回自增列的值。
查詢資料時,需要完整的主索引值。通過設定PutRow、UpdateRow或者BatchWriteRow中的ReturnType為RT_PK可以擷取完整的主索引值。
樣本
主鍵自增列功能主要涉及建立表(CreateTable)和寫資料(PutRow、UpdateRow和BatchWriteRow)兩類介面。
- 建立表
建立表時,只需將自增的主鍵屬性設定為PK_AUTO_INCR。
from tablestore import * table_name = 'OTSPkAutoIncrSimpleExample' def create_table(client): # 建立表,表中包括兩個主鍵:gid,INTEGER類型;uid,INTEGER類型,為自增列。 schema_of_primary_key = [('gid', 'INTEGER'), ('uid', 'INTEGER', PK_AUTO_INCR)] table_meta = TableMeta(table_name, schema_of_primary_key) table_options = TableOptions() reserved_throughput = ReservedThroughput(CapacityUnit(0, 0)) client.create_table(table_meta, table_options, reserved_throughput) print ('Table has been created.')
- 寫資料
寫入資料時,無需為自增列設定具體值,只需將自增列的值設定為預留位置PK_AUTO_INCR。
from tablestore import * table_name = 'OTSPkAutoIncrSimpleExample' def put_row(client): # 寫入主鍵:gid為1,uid為自增列。uid列必須設定,否則報錯。 primary_key = [('gid',1), ('uid', PK_AUTO_INCR)] attribute_columns = [('name','John'), ('mobile',13900006666), ('address','China'), ('age',20)] row = Row(primary_key, attribute_columns) # 寫入屬性列。 row.attribute_columns = [('name','John'), ('mobile',13900006666), ('address','China'), ('age',25)] consumed, return_row = client.put_row(table_name, row) print ('Write succeed, consume %s write cu.' % consumed.write) consumed, return_row = client.put_row(table_name, row, return_type = ReturnType.RT_PK) print ('Write succeed, consume %s write cu.' % consumed.write) print ('Primary key:%s' % return_row.primary_key)