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:

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’

πŸ‘‹ Kindness is contagious

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

Okay