DynamoDB mapper update item only if HashKey RangeKey pair is in the table

Viewed 442

I want to design an update function for my DynamoDB table that only updates the record when the hash key and range key pair is in the DynamoDB table. If the item doesn't exist, I would like to throw a badRequestError. How can I use a DynamoDB expression to achieve this? Can I set both the expectedAttribute to true and set the conditional operator to AND?

1 Answers

If you are using DynamoDBMapper you could use DynamoDBSaveExpression

Something like:

Map<String, ExpectedAttributeValue> expected =
    Map.of("hashKeyAttrName", new ExpectedAttributeValue().withExists(true),
        "rangeKeyAttrName", new ExpectedAttributeValue().withExists(true));
DynamoDBSaveExpression expression = new DynamoDBSaveExpression();
expression.setExpected(expected);
dynamoDBMapper.save(item, expression);

If condition is not met save will trow a ConditionalCheckFailedException

Related