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:

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay