I am trying to write a function that will insert data into my DynamoDB using boto3. I am trying to find the largest ID in the DB and increment it by one in order to give that to my inserted object making it the latest ID. I know that DynamoDB does not support auto-increment and that most would suggest using a UUID however that would require me to restructure my tables and I would like to avoid that if possible. Is there any way to find the largest number of an attribute so I could increment it manually for my insertion?
I have tried to use the describe_table function to get the item count however that only updates every 6 hours which does not work well for my use-case. I have also tried the following block of code, but I just found it online and it throws an error stating that the provided key element does not match the schema.
response = table.update_item(
Key={'pk': 'transaction_id'},
UpdateExpression="ADD #cnt :val",
ExpressionAttributeNames={'#cnt': 'count'},
ExpressionAttributeValues={':val': 1},
ReturnValues="UPDATED_NEW"
)
My guess is that you don't require much scale? For that reason I would suggest that you use a static partition key value, and what you use as partition key now should be the sort key.
Both of these blogs combined will provide you the solution to your question:
https://aws.amazon.com/blogs/database/effective-data-sorting-with-amazon-dynamodb/
https://aws.amazon.com/blogs/database/implement-auto-increment-with-amazon-dynamodb/
The alternative approach is to use transactions, every time you add an item you update a counter item to keep count of the current partition key value. Transactions will increase your write throughput consumption, instead of 1 WCU, you will increase it to 4 WCU as you need to write with transactions to two items.