DynamoDB - How to create a map and add an 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 that:

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

However, while doing the above, I am getting the error Two document paths overlap with each other

The only thing I'm going to do is do TWO updates, one to create any blank maps, and then another to set the attributes.

Is there a way to do this in one update?

Update

Another use case is to create maps that contain other maps. Currently, the only way to create the following is with 3 separate update requests to create maps if needed, and then another call to add attributes:

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

      

There must be a better way.

+3


source to share


1 answer


You can amortize the cost of making two separate calls to UpdateItem, 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've added many records to #A, then you only create #A once, and as the number of records in #A increases, the amortized time to create #A approaches zero. If you catch a ConditionalCheckFailedException, that is, when you create a map with a pre-existing #B number and call UpdateItem:

UpdateExpression: SET #A = :valueOfMapWithBInIt
ConditionExpression: attribute_not_exists(#A)

      

+1


source







All Articles