Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamodb update attribute based on another

Tags:

I want to update an item in Dynamodb such that I can set the value of one attribute based on the value of an existing attribute in that item. For example: I have table with the following item {"id": 1, "valueone": 30}.

I want to update this item such that I can add another attribute valuetwo whose value is twice that of valueone: {"id": 1, "valueone": 30, "valuetwo": 60}

Something like this, but not sure how to represent valueone in the ExpressionAttributeValues:

table.update_item(Key={'id': 1}, UpdateExpression="set vtwo = :two * :r", ExpressionAttributeValues={':r': valueone, ':two': 2},ReturnValues="ALL_NEW"))

I can control whether valuetwo is a new attribute in the item or already exists with a dummy value (say zero).

like image 315
user2703829 Avatar asked Feb 06 '17 22:02

user2703829


People also ask

Does 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.

Can you update a record in DynamoDB?

To update an existing item in an Amazon DynamoDB table, you use the UpdateItem operation. You must provide the key of the item that you want to update. You must also provide an update expression, indicating the attributes that you want to modify and the values that you want to assign to them.

Does DynamoDB putItem overwrite?

Conditional writes. By default, the DynamoDB write operations ( PutItem , UpdateItem , DeleteItem ) are unconditional: Each operation overwrites an existing item that has the specified primary key.

What is the relationship between an attribute item and table in Amazon DynamoDB?

In DynamoDB, tables, items, and attributes are the core components that you work with. A table is a collection of items, and each item is a collection of attributes. DynamoDB uses primary keys to uniquely identify each item in a table and secondary indexes to provide more querying flexibility.


1 Answers

Currently, DynamoDB doesn't support " * - Multiply (or) / - Division" arithmetic operators in UpdateExpression.

It supports only addition (+) and subtraction (-) operators.

Addition:-

UpdateExpression : "SET total_new_val = total_val + :value",

Subtraction:-

UpdateExpression : "SET total_new_val = total_val - :value",

Multiplication:-

UpdateExpression : "SET total_new_val = total_val * :value",    

Multiplication throws the below error:-

Unable to update item. Error JSON: {
  "message": "Invalid UpdateExpression: Syntax error; token: \"*\", near: \"tota
l_val * :value\"",
  "code": "ValidationException",
  "time": "2017-02-07T11:32:41.478Z",
  "requestId": "64f36024-7251-40af-98ee-e9cef854e94b",
  "statusCode": 400,
  "retryable": false,
  "retryDelay": 0
}
like image 133
notionquest Avatar answered Sep 21 '22 17:09

notionquest