2

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);

}
user3587180
  • 1,317
  • 11
  • 23
  • Try performing a Scan Query first. Check with a simple if condition whether the length of your returned object is 1 or more, it means that this item already exists. If not, proceed on inserting that item. – Kazi Apr 18 '22 at 08:46

1 Answers1

0

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?

Philip Pittle
  • 11,821
  • 8
  • 59
  • 123