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

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

👋 Kindness is contagious

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

Okay