Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java DynamoDB -- Only insert if key not already present (without mapper)

I only want to insert this row if the key is not present. I don't want to override the row if the key already exists.

My syntax is this:

new PutItemRequest().withTableName(myTableName).withItem(myItem).withConditionExpression(?)

As per the AWS docs, I'd use something like attribute ATTRIBUTE_NOT_EXISTS. I could also use ComparisonOperator.NULL, etc. That's as far as I can understand.

Syntax tips? Some explanation of this withConditionExpression mechanism?

like image 530
Jeremy Avatar asked Sep 21 '15 23:09

Jeremy


2 Answers

The doc says ConditionExpression replaces the legacy ConditionalOperator(.NULL). You can go both routes but you're supposed to use .withConditionExpression(...) rather then the operand route.

There is also https://java.awsblog.com/post/TxBG87QOQZRZJF/DynamoDB-XSpec-API for more complex expressions.

But in your case it should work by writing

.withConditionExpression("attribute_not_exists(thingId)")

assuming your hash key property is named thingId. That approach is also documented here: http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html

To prevent a new item from replacing an existing item, use a conditional expression that contains the attribute_not_exists function with the name of the attribute being used as the HASH key for the table. Since every record must contain that attribute, the attribute_not_exists function will only succeed if no matching item exists.

like image 101
zapl Avatar answered Oct 11 '22 09:10

zapl


We can define Dynamo Db primary Key as combination of (partition key and sort key) . based on this assumption ,this code would throw away duplicate records .

PrimaryKey primaryKey = new PrimaryKey();
primaryKey.addComponent("Partition_Key", partitionId);
primaryKey.addComponent("Sort_Key",sortId);

    Item item = new Item().withPrimaryKey(primaryKey).withString("username", userName).withLong("time", time);

    try {

        PutItemSpec putItemSpec = new PutItemSpec().withItem(item).withConditionExpression("attribute_not_exists(Sort_Key)");
        table.putItem(putItemSpec);

    } catch(ConditionalCheckFailedException ex) {
         logger.error("Record already exists in Dynamo DB Table ");

    }
like image 40
Sindhu Avatar answered Oct 11 '22 10:10

Sindhu