问题描述:

I am trying to update an item in DynamoDb. The condition for update is that an input string (myValue in below example) should not be present in a string set (mySet). Here's the abstract code:

Map<String, Object> valueMap = new ValueMap().withStringSet(":val", "myValue");

String updateExpression = "add mySet :val ";

String conditionExpression = "not(contains(mySet, :val))";

UpdateItemSpec updateItemSpec =

new UpdateItemSpec().withReturnValues(ReturnValue.NONE)

.withPrimaryKey("HashKey", "h1")

.withUpdateExpression(updateExpression).withValueMap(valueMap)

.withConditionExpression(conditionExpression);

try {

myTable.updateItem(updateItemSpec);

} catch (ConditionalCheckFailedException ccfe) {

System.out.println("success");

}

The item already exists in the db. Now, no matter myValue exists in mySet or not, the condition expression always evaluates to true, thereby never leading to ConditionalCheckFailedException.

Is there something wrong with the way I am using the contains() function?

Ref: DynamoDb ConditionExpression Functions

网友答案:

The solution to this was:

Map<String, Object> valueMap =  new ValueMap()
    .withStringSet(":val", "myValue")
    .withString(":val2", "myValue");
String updateExpression = "add mySet :val ";
String conditionExpression = "not(contains(mySet, :val2))";
UpdateItemSpec updateItemSpec = new UpdateItemSpec().withReturnValues(ReturnValue.NONE)
    .withPrimaryKey("HashKey", "h1")
    .withUpdateExpression(updateExpression).withValueMap(valueMap)
    .withConditionExpression(conditionExpression);
try {
    myTable.updateItem(updateItemSpec);
} catch (ConditionalCheckFailedException ccfe) {
    System.out.println("success");
}

i.e. Using a String (:val2) and a StringSet (:val of the same myValue and then using :val2 in conditional expression and :val in update expression.

This is because update expression expects a StringSet to append to a set of string while the contains() function expects a String to check if it exists in a StringSet.

相关阅读:
Top