How to only add item if it does not already exist in DynamoDB?

Viewed 319

I am trying to add an item to DynamoDB only if it doesn't exist already. I have tried the below code and doesn't look like the query filter is being applied for SaveAsync. I don't get an exception even when an item with the primary key (CommentId, CommentType) already exists.

public Task Add(Comment comment)
{
    var config = new DynamoDBOperationConfig();

    var partitionKeyCondition = new ScanCondition("CommentId", ScanOperator.NotEqual, 1);
    var rangeKeyCondition = new ScanCondition("CommentType", ScanOperator.NotEqual, "UserComment");

    config.QueryFilter.Add(partitionKeyCondition);
    config.QueryFilter.Add(rangeKeyCondition);


  return DynamoDBContext.SaveChangesAsync(comment, config);

}
1 Answers

You'll want to do a Conditional Put: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html#Expressions.ConditionExpressions.PreventingOverwrites

Here's a basic example:

var client = new AmazonDynamoDBClient();

Client.PutItem(new PutItemRequest
{
    Item = new Dictionary<string, AttributeValue>
    {
        {"Id", new AttributeValue("Item-unique-id")},
        {"Vale", new AttributeValue("Hello World")},
    },
    // cause put to fail if there is already an item with the same key
    ConditionExpression = "attribute_not_exists(Id)"
});

There's more details in this question: Is it possible to do a conditional put or update in DynamoDB?

Related