DEV Community

Abhishek Gupta for AWS

Posted on • Originally published at community.aws

6 1 1 1

[20 Days of DynamoDB] Day 5 - Avoid overwrites when using DynamoDB UpdateItem API

Posted: 12/Jan/2024

The UpdateItem API creates a new item or modifies an existing item's attributes. If you want to avoid overwriting an existing attribute, make sure to use the SET operation with if_not_exists function.

Here is an example that sets the category of an item only if the item does not already have a category attribute:

    resp, err := client.UpdateItem(context.Background(), &dynamodb.UpdateItemInput{
        TableName: aws.String(tableName),
        Key: map[string]types.AttributeValue{
            "email": &types.AttributeValueMemberS{Value: email},
        },
        UpdateExpression: aws.String("SET category = if_not_exists(category, :category)"),
        ExpressionAttributeValues: map[string]types.AttributeValue{
            ":category": &types.AttributeValueMemberS{
                Value: category,
            },
        },
    })
Enter fullscreen mode Exit fullscreen mode

Note that if_not_exists function can only be used in the SET action of an update expression.

Recommended reading - DynamoDB documentation

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay