Search code examples
amazon-web-servicesamazon-dynamodbdynamodb-queries

DynamoDb Invalid ConditionExpression due to : present in expression


I want to do conditional putItem call into DynamoDb i.e. don't insert an entry in dynamoDb if the primaryKey(partitionKey + Sort Key already exists). My schema's key look like this:

PartitionKey: abc:def

SortKey:abc:123

To do a conditional I do something like this:


private static final String PK_DOES_NOT_EXIST_EXPR = "attribute_not_exists(%s)";

final String condition = String.format(PK_DOES_NOT_EXIST_EXPR,
            record.getPKey() + record.getSortKey);

        final PutItemEnhancedRequest putItemEnhancedRequest = PutItemEnhancedRequest
            .builder(Record.class)
            .conditionExpression(
                Expression.builder()
                .expression(condition)
                .build()
            )
            .item(newRecord)
            .build();

However I run into following error

Exception in thread "main" software.amazon.awssdk.services.dynamodb.model.DynamoDbException: Invalid ConditionExpression: Syntax error; token: ":123", near: "abc:123)" (Service: DynamoDb, Status Code: 400

I am assuming this is because of : present in my condition, because the same expression without : in the key succeeds. Is there a way to fix this?


Solution

  • Your condition should include the name of the partition key attribute, not its value. For example:

    attribute_not_exists(pk)
    

    Also, see Uniqueness for composite primary keys for an explanation of why you only need to indicate the partition key attribute name, not both the partition key and the sort key attribute names. So, the following, while not harmful, is unnecessary:

    attribute_not_exists(pk) AND attribute_not_exists(sk)