This topic describes how to use the Tablestore Python SDK to add an auto-increment primary key column and write data when you create a table.

Note
  • If you set a primary key column in a table as an auto-increment column, you do not need to enter values in this column when writing data in a row. Tablestore automatically generates primary key values.
  • The values of the auto-increment column are unique and increase sequentially.
  • Only one primary key column can be set as the auto-increment column in each table.
  • Partition keys and attribute columns cannot be set as auto-increment columns.

Create a table

You can add an auto-increment primary key column when you create a table. Example:

from tablestore import *

table_name = 'OTSPkAutoIncrSimpleExample'

def create_table(client):
    # Create a table that includes the following two INTEGER type primary keys: gid and uid. Specify uid as the auto-increment column.
    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.')

Write data

Example:

from tablestore import *

table_name = 'OTSPkAutoIncrSimpleExample'

def put_row(client):
    # Write data to the primary keys: Set the values of gid to 1 and set uid as the auto-increment column. The uid column must be set as the auto-increment column. Otherwise, an error is returned.
    primary_key = [('gid',1), ('uid', PK_AUTO_INCR)]
    attribute_columns = [('name','John'), ('mobile',15100000000), ('address','China'), ('age',20)]
    row = Row(primary_key, attribute_columns)

    # Write data to attribute columns.
    row.attribute_columns = [('name','John'), ('mobile',15100000000), ('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)