I have a very simple class, with a string type primary key and List type attributes. I want to write APIS for adding and removing an item from the attribute list and saving the changes back to DDB.
The simplest solution I can think of is: - Read the list (if it exists) - If it exists, remove or add that entry from the List type attribute - Put the modified object back
Is there a cleaner/simpler way to do this via DynamoDB java API? I spent quite some time looking it up, before I posted this question here.
You can use
SET
operator to add element in the attribute list. But for that you have to retrieve the existing list first then append new element in the list. Suppose you have a attribute namedactive_user
which contain the list of active users.You can use
REMOVE
operator to remove or delete an element of the list. But you have to find the index of the element becauseREMOVE
operator removes the given index of the list.Here is
REMOVE
operator doc andSET
operator doc.I just read the UpdateItem API thoroughly which talks about deleting set type attributes:
The DELETE action only supports Set data types as written in their documentation. The right answer could be find in this stackoverflow question
How to Remove from List Of Maps in DynamoDB (Must be Atomic)
The accepted answer is incorrect, the correct way of doing this is listed in the DynamoDB UpdateExpression documentation
You need to read the list then get the index of the item you're looking to remove then run
REMOVE list[index]
as anUpdateExpression