设置非分区键的主键列为自增列后,在写入数据时,无需为自增列设置具体值,表格存储会自动生成自增列的值。该值在分区键级别唯一且严格递增。

前提条件

已初始化Client。具体操作,请参见初始化

使用方法

  1. 创建表时,将非分区键的主键列设置为自增列。

    只有整型的主键列才能设置为自增列,系统自动生成的自增列值为64位的有符号长整型。

  2. 写入数据时,无需为自增列设置具体值,只需将自增列的值设置为占位符。

    如果需要获取写入数据后系统自动生成的自增列的值,将ReturnType设置为RT_PK,可以在数据写入成功后返回自增列的值。

    查询数据时,需要完整的主键值。通过设置PutRow、UpdateRow或者BatchWriteRow中的ReturnType为RT_PK可以获取完整的主键值。

    说明 如果要更新已存在的行,请先通过GetRange接口获取要更新的行主键信息,然后再进行数据更新。

示例

主键自增列功能主要涉及创建表(CreateTable)和写数据(PutRow、UpdateRow和BatchWriteRow)两类接口。

  1. 创建表

    创建表时,只需将自增的主键属性设置为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.')
  2. 写数据

    写入数据时,无需为自增列设置具体值,只需将自增列的值设置为占位符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)