DEV Community

Abhishek Gupta for AWS

Posted on • Edited on • Originally published at community.aws

5 1 1 1 1

[20 Days of DynamoDB] Day 1 - Conditional PutItem

For the next 20 days (don't ask me why I chose that number 😉), I will be publishing a DynamoDB quick tip per day with code snippets. The examples use the DynamoDB packages from AWS SDK for Go V2, but should be applicable to other languages as well.

Posted: 8/Jan/2024

The DynamoDB PutItem API overwrites the item in case an item with the same primary key already exists. To avoid (or work around) this behaviour, use PutItem with an additional condition.

Here is an example that uses the attribute_not_exists function:

    _, err := client.PutItem(context.Background(), &dynamodb.PutItemInput{
        TableName: aws.String(tableName),
        Item: map[string]types.AttributeValue{
            "email": &types.AttributeValueMemberS{Value: email},
        },
        ConditionExpression: aws.String("attribute_not_exists(email)"),
        ReturnConsumedCapacity:      types.ReturnConsumedCapacityTotal,
        ReturnValues:                types.ReturnValueAllOld,
        ReturnItemCollectionMetrics: types.ReturnItemCollectionMetricsSize,
    })

    if err != nil {
        if strings.Contains(err.Error(), "ConditionalCheckFailedException") {
            log.Println("failed pre-condition check")
            return
        } else {
            log.Fatal(err)
        }
    }
Enter fullscreen mode Exit fullscreen mode

With the PutItem operation, you can also:

  • Return the consumed Write Capacity Units (WCU)
  • Get the item attributes as they appeared before (in case they were updated during the operation)
  • Retrieve statistics about item collections, if any, that were modified during the operation

Recommended reading:

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay