Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamodb batch put if item does not exist

DynamoDb does not support batch update, it supports batch put only.

But is it possible to batchPut only of item with key does not exist?

like image 480
Shushant Arora Avatar asked Jan 06 '18 19:01

Shushant Arora


People also ask

Does DynamoDB Update create if not exists?

UpdateItem behaves as an “UPSERT” operation. This means that if you try to update an item that doesn't exist, DynamoDB will automatically create it for you. Like with PutItem , you can add conditions to your UpdateItem API calls to modify this behavior, but there is no way to implement it service-side.

Does Amazon DynamoDB support conditional operations?

Yes, like all the other database management systems, DynamoDB also supports all the conditional operators, User can specify a condition that is satisfied for a put, update, or delete operation to work on an item.

What is conditional writes in DynamoDB?

Conditional writes can be idempotent if the conditional check is on the same attribute that is being updated. This means that DynamoDB performs a given write request only if certain attribute values in the item match what you expect them to be at the time of the request.

Does Batchwrite overwrite?

Chen's answer is correct; BatchWriteItem always overwrites.


1 Answers

In the batchWriteItem, there is the following note:

For example, you cannot specify conditions on individual put and delete requests, and BatchWriteItem does not return deleted items in the response.

Instead, I would recommend using putItem with a conditional expression. Towards the bottom of the putItem documentation there is the following note:

[...] 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 partition key for the table [...]

So make sure to add the following to ConditionExpression (using NodeJS syntax here)

const params = {
    Item: {
        userId: {
            S: "Beyonce",
        }
    },
    ConditionExpression: "attribute_not_exists(userId)"
};
like image 199
Daniel Apt Avatar answered Sep 18 '22 17:09

Daniel Apt