Nico Müller
Nico Müller

Reputation: 1874

Dynamodb Add or Update key in dict

I have a dynamodb table with the following structure:

'Items': [
   {'user_id': 'myuser',
    'owes_to': {
         'youruser': '10',
         'user3': '20'
       }
   }]

Is it possible in dynamodb to create a new user key in owes_to or if it already exists add to the value of that key?

In example in two calls:

  1. Add 'user4' with value 20, It doesnt exist so create the user4 key with value 20)
  2. Next time update user4 value 20 to 40, This time key already existed so add the 20 to the existing value

Upvotes: 1

Views: 1952

Answers (1)

FireNero
FireNero

Reputation: 170

It's possible, update expression will be similar to this:

update_request = {
    Key={'user_id': ':id'},
    UpdateExpression='SET owes_to.#user_name = if_not_exists(owes_to.#user_name, :default_val) + :val',
    ExpressionAttributeNames={
        '#user_name': <your_user_name>
    }
    ExpressionAttributeValues={
        ':id': 'myuser',
        ':val': <your_update_value>,
        ':default_val': 0
    }
}

Note the if_not_exists(owes_to.#user_name, :default_val) construction. It will take value of the user if it exists or take value specified in :default_val if it doesn't. More about adding and updating map values in official docs

Upvotes: 2

Related Questions