Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamodb: how to increment a value in map

I am trying to use dynamodb to maintain a map of names with their values

eg. {"scores": {"player-a": 10}}

I also wish to use increment operator to perform atomic increments. However, i could find very little documentation on how to use/update dynamodb maps. Here's the python code I have so far

 import boto3
 ddb = boto3.client('dynamodb')
 ddb.update_item(TableName='ledger', Key={'week': {'S': '06-12'}}, 
                 UpdateExpression='SET scores.player-a  = scores.player-a + :val', 
                 ExpressionAttributeValues={':val': {'N': '12'}})
like image 668
Kalyanaraman Santhanam Avatar asked Jul 02 '16 18:07

Kalyanaraman Santhanam


People also ask

Can we update data in DynamoDB?

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.

What is the use of add new attribute method in DynamoDB?

ADD - Causes DynamoDB to create an item with the supplied primary key and number (or set of numbers) for the attribute value. The only data types allowed are Number and Number Set.

Does Amazon DynamoDB support both increment and decrement atomic operations?

Does Amazon DynamoDB support both increment and decrement atomic operations? No, neither increment nor decrement operations.


1 Answers

DynamoDB update item uses ExpressionAttributeNames to prevent special characters in an attribute name from being misinterpreted in an expression.

Your update item consists of "player-a" as a key name which has "-" (hyphen) in it.

ddb.update_item(
    TableName='ledger',
    Key={
        'week': {
            'S': '06-12'
        }
    }, 
    UpdateExpression='SET scores.#s = scores.#s + :val",  
    ExpressionAttributeNames={
        "#s": "player-a"
    },  
    ExpressionAttributeValues={
        ':val': {
            'N': '12'
        }
    }
)
like image 79
omuthu Avatar answered Sep 29 '22 07:09

omuthu