Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DynamoDB increment a key/value

if I was to have a DynamoDB table with a UserID as a key and a number as a value can I increment that number/value in a single operation? or do I need to read it out, increment and write it back in?

thx

like image 1000
Adam Avatar asked Dec 29 '12 00:12

Adam


People also ask

Can we update primary key in DynamoDB?

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.

Can you update partition key in DynamoDB?

Is it possible to change partition key in DynamoDB? No. Once the table is setup, you cannot modify its Key Schema. You can only provision a new table, move data there, and then remove the first table.

How do I update a DynamoDB item?

To update an existing item in an Amazon DynamoDB table, you use the UpdateItem operation. You must provide the key of the item that you want to update. You must also provide an update expression, indicating the attributes that you want to modify and the values that you want to assign to them.

What is atomic counter in DynamoDB?

You can use the UpdateItem operation to implement an atomic counter—a numeric attribute that is incremented, unconditionally, without interfering with other write requests. (All write requests are applied in the order in which they were received.) With an atomic counter, the updates are not idempotent.


2 Answers

DynamoDB supports the concept of atomic counters. You would simply call update_item with action: "ADD" to automatically increment the value for an item.

like image 128
Mike Brant Avatar answered Oct 24 '22 14:10

Mike Brant


As others have stated, you can increment with one operation, however "action: ADD" is now deprecated. The current way to achieve this is with UpdateExpression. I am also assuming the OP meant that there was a numeric [attribute] whose value needs incrementing. I am calling the attribute loginCount:

dynamoDB.updateItem({
  TableName: "Users",
  Key: { "UserId": { S: "c6af9ac6-7b61" } },
  ExpressionAttributeValues: { ":inc": {N: "1"} },
  UpdateExpression: "ADD loginCount :inc"
})
like image 36
gmoon Avatar answered Oct 24 '22 16:10

gmoon