AWS DynamoDB
DynamoDB Document API
Update Map in DynamoDB
Update List in DynamoDB
DynamoDB Tutorial

How to update a Map or a List on AWS DynamoDB document API?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

AWS DynamoDB is a prominent NoSQL database that offers robust scalability and performance. It is widely used for applications requiring consistent single-digit millisecond response times across diverse scales. DynamoDB supports two data types for storing collections: Lists and Maps. Lists store an ordered collection of values, while Maps contain key-value pairs.

This article will explore updating a Map or a List using DynamoDB's Document API, providing technical explanations, examples, and related information.

DynamoDB Document API

The DynamoDB Document API is designed for seamless interaction with DynamoDB by abstracting the low-level operations into more intuitive document-level operations, allowing developers to work with JSON-like objects. Updating entries in a Map or a List involves using the API to precisely target and modify items without replacing entire collections.

Updating a Map

Maps in DynamoDB are akin to JSON objects, ideal for storing unordered collections of key-value pairs. Here’s how you can update a Map using the Document API:

Example

Assume we have an item with the partition key UserId and a map attribute Profile containing user information:

json
1{
2  "UserId": "12345",
3  "Profile": {
4    "Name": "John Doe",
5    "Email": "[email protected]",
6    "Address": {
7      "Street": "123 Main St",
8      "City": "Anytown",
9      "ZipCode": "12345"
10    }
11  }
12}

Updating a Map Item

To update the City in the Address attribute within the Profile map:

python
1import boto3
2from boto3.dynamodb.conditions import Key
3
4dynamodb = boto3.resource('dynamodb')
5table = dynamodb.Table('Users')
6
7response = table.update_item(
8    Key={
9        'UserId': '12345'
10    },
11    UpdateExpression='SET Profile.Address.City = :city',
12    ExpressionAttributeValues={
13        ':city': 'New City'
14    },
15    ReturnValues="UPDATED_NEW"
16)
17
18print(response)

Explanation

  • Key: Specify the primary key of the item to update.
  • UpdateExpression: Utilize a SET expression to define the update logic. Here, Profile.Address.City pinpoints the nested key's location.
  • ExpressionAttributeValues: Supply a dictionary of substitution tokens to use within the update expression.
  • ReturnValues: Choose "UPDATED_NEW" if you want to receive the modified attributes back in the response.

Updating a List

Lists store ordered values and are perfect for maintaining sequences like arrays. To update an element of a List at a specific index:

Example

Consider a user with a Favorites list attribute containing a collection of favorite items:

json
1{
2  "UserId": "67890",
3  "Favorites": ["Pizza", "Burger", "Salad"]
4}

Updating a List Item

To change the second item ("Burger") to "Sushi":

python
1response = table.update_item(
2    Key={
3        'UserId': '67890'
4    },
5    UpdateExpression='SET Favorites[1] = :new_item',
6    ExpressionAttributeValues={
7        ':new_item': 'Sushi'
8    },
9    ReturnValues="UPDATED_NEW"
10)
11
12print(response)

Explanation

  • UpdateExpression: The array syntax (Favorites[1]) allows direct access to the List element to be updated. Indexing is zero-based.
  • ExpressionAttributeValues: As before, this parameter provides new values for your update.

Summary Table

Below is a summary highlighting the crucial points of updating Maps and Lists in DynamoDB:

FeatureDescriptionExample
KeysIdentify the item to updateUserId = '12345'
UpdateExpressionSpecifies update logic using SETProfile.Address.City
ExpressionAttributeValuesSubstitution tokens for expressions:city = 'New City'
ReturnValuesControls data returned upon updateUPDATED_NEW
Map UpdateHandles nested attributesProfile.Address.City
List UpdateAllows specific index replacementFavorites[1]

Considerations and Best Practices

  • Concurrency Control: Use conditional expressions to prevent race conditions where two processes attempt updates simultaneously.
  • Error Handling: Implement exception handling to catch issues such as network failures or resource constraints.
  • Throughput Management: Monitor read/write units to optimize costs and performance using AWS CloudWatch.

Conclusion

Working with Maps and Lists in AWS DynamoDB's Document API is straightforward and efficient, enabling you to perform updates on nested or ordered collections without overhauling entire documents. By focusing on specific keys or indices, you maintain atomicity and performance, crucial for high-scale applications. Use the techniques and best practices outlined in this article to manage Lists and Maps effectively in DynamoDB.


Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design