3

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?

Adi
  • 387
  • 3
  • 6
  • 14

1 Answers1

3

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)
jarmod
  • 71,565
  • 16
  • 115
  • 122
  • Thanks, this wasn't very obvious to me. Specifying the key names fixed the issue. Replaced this with `attribute_not_exists(pk) AND attribute_not_exists(sk)` – Adi Feb 17 '23 at 23:42
  • Note, per the Alex DeBrie article I referenced, the `AND attribute_not_exists(sk)` part is extraneous, though not harmful. – jarmod Feb 18 '23 at 00:41