Faisal
Faisal

Reputation: 175

Update if value doesn't exist or check condition in DynamoDBMapper

I am working on a method that saves to DynamoDB. I want the method to save if the value doesn't exist in the table. If it does exist, I want to apply a conditional update. I am using DynamoDBMapper's save method.

The code I have at the moment does the conditional save successfully, but throws an exception if the column doesn't exist in the database.

Is there a way to come up with a conditional update expression that checks if the value doesn't exist or checks for the condition I need?

The code I have at the moment, which is in Java, looks like this:

DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression();
AttributeValue attributeValue = new AttributeValue(valueToSave);
ExpectedAttributeValue expectedAttributeValue = new ExpectedAttributeValue(attributeValue).withComparisonOperator(ComparisonOperator.LT);
Map<String, ExpectedAttributeValue> expected = new HashMap<>();
expected.put("key", expectedAttributeValue);
saveExpression.setExpected(expected);
dynamoDbMapper.save(objectToSave);

Thanks!

Upvotes: 3

Views: 2452

Answers (1)

chim
chim

Reputation: 8573

The ExpectedAttribute stuff is there for Legacy applications (https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html#DDB-PutItem-request-Expected).

It's recommended that you use the newer ConditionExpression instead.

This is one way i've done it, although the snippet below is converted from Scala code and untested.

Map attrVals = new HashMap() {{
  put(":revision", new AttributeValue().withN(revision.toString)));   
}};

PutItemRequest request = new PutItemRequest().withTableName(myTableName)
.withItem(myItem)
.withConditionExpression(attribute_not_exists(primaryKey) OR revision <= :revision)
.withExpressionAttributeValues(attrVals);

dynamoClient.putItem(request);

Upvotes: 2

Related Questions