I am new to dynamodb. I want to auto increment id value when I use putitem
with dynamodb.
Is possible to do that?
DynamoDB does not support auto-incrementing IDs for items. They can be a performance bottleneck at scale, and most workloads are better off with UUIDs anyway. However, there are use cases where auto-incrementing integers are required.
You cannot update the primary key attributes using UpdateItem. Instead, delete the item and use PutItem to create a new item with new attributes. The UpdateItem operation includes an Action parameter, which defines how to perform the update. You can put, delete, or add attribute values.
DynamoDB supports two types of primary keys: Partition key: A simple primary key, composed of one attribute known as the partition key.
Primary key. When you create a table, in addition to the table name, you must specify the primary key of the table. The primary key uniquely identifies each item in the table, so that no two items can have the same key.
This is anti-pattern in DynamoDB which is build to scale across many partitions/shards/servers. DynamoDB does not support auto-increment primary keys due to scaling limitations and cannot be guaranteed across multiple servers.
Better option is to assemble primary key from multiple indices. Primary key can be up to 2048 bytes. There are few options:
Following code will auto-increment counter in DynamoDB and then you can use it as primary key.
var documentClient = new AWS.DynamoDB.DocumentClient(); var params = { TableName: 'sampletable', Key: { HashKey : 'counters' }, UpdateExpression: 'ADD #a :x', ExpressionAttributeNames: {'#a' : "counter_field"}, ExpressionAttributeValues: {':x' : 1}, ReturnValues: "UPDATED_NEW" // ensures you get value back }; documentClient.update(params, function(err, data) {}); // once you get new value, use it as your primary key
My personal favorite is using timestamp + random inspired by Instagram's Sharding ID generation at http://instagram-engineering.tumblr.com/post/10853187575/sharding-ids-at-instagram
Following function will generate id for a specific shard (provided as parameter). This way you can have unique key, which is assembled from timestamp, shard no. and some randomness (0-512).
var CUSTOMEPOCH = 1300000000000; // artificial epoch function generateRowId(shardId /* range 0-64 for shard/slot */) { var ts = new Date().getTime() - CUSTOMEPOCH; // limit to recent var randid = Math.floor(Math.random() * 512); ts = (ts * 64); // bit-shift << 6 ts = ts + shardId; return (ts * 512) + randid; } var newPrimaryHashKey = "obj_name:" + generateRowId(4); // output is: "obj_name:8055517407349240"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With