Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DynamoDB - How to create map and add attribute to it in one update

I want to create a new map if it doesn't exist and then add an attribute to that map. Something like this:

SET #A = if_not_exists(#A, :emptyMap), #A.#B = :somevalue

However doing the above gives me the error saying Two document paths overlap with each other

The only other thing I am thinking to do is do TWO updates, one to create any empty maps and then another to set attributes.

Is there a way to do it in a single update ?

Update

Another use case is creating maps that contain other maps. Currently the only way I can think of to create the following is 3 separate update calls to create the maps if necessary and then another update call to add attributes:

{
  Entities: { A: { B: {} } },
}

There must be a better way.

like image 857
pizzarob Avatar asked Mar 31 '17 01:03

pizzarob


People also ask

What is the difference between put and update in DynamoDB?

Main Difference Between DynamoDB UpdateItem & PutItemThe putItem function is used to replace an existing item or to create a new item. In contrast, the updateItem function is used to add, edit or delete attributes from an existing item.

Can we do batch update in DynamoDB?

A bulk (batch) update refers to updating multiple rows belonging to a single table. However, DynamoDB does not provide the support for this.

What is the use of add new attribute method in DynamoDB?

ADD - Causes DynamoDB to create an item with the supplied primary key and number (or set of numbers) for the attribute value. The only data types allowed are Number and Number Set.

Can we update data 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.


1 Answers

You can amortize the cost of doing two seperate UpdateItem calls, one to create #A, and the other to add #B to #A by adding #B to #A with a conditional update.

UpdateExpression: SET #A.#B = :valueOfB
ConditionExpression: attribute_exists(#A)

If you add many entries to #A, then you only create #A once, and as the number of entries in #A increases, the amortized time to create #A approaches zero. If you catch a ConditionalCheckFailedException, that is when you would create the map with #B already in it and call UpdateItem:

UpdateExpression: SET #A = :valueOfMapWithBInIt
ConditionExpression: attribute_not_exists(#A)
like image 53
Alexander Patrikalakis Avatar answered Oct 25 '22 01:10

Alexander Patrikalakis