Add or remove an entry from a List type attribute

2020-02-14 02:20发布

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.

4条回答
戒情不戒烟
2楼-- · 2020-02-14 03:07

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 named active_user which contain the list of active users.

previous_list = "#a"
query = "SET %s = list_append(%s, :new_user)" % (previous_list, previous_list)
user_table.update_item(
    Key={
        # primary key
    },
    UpdateExpression=query,
    ExpressionAttributeNames={
        '#a': 'active_user',
    },
    ExpressionAttributeValues={
        ':new_user': new_user_model
    }
)

You can use REMOVE operator to remove or delete an element of the list. But you have to find the index of the element because REMOVE operator removes the given index of the list.

#user_index is the position of the target user in the list

query = "REMOVE active_user[%d]" % (user_index)
user_table.update_item(
    Key={
        # primary key
    },
    UpdateExpression=query
)

Here is REMOVE operator doc and SET operator doc.

查看更多
家丑人穷心不美
3楼-- · 2020-02-14 03:09

I just read the UpdateItem API thoroughly which talks about deleting set type attributes:

DELETE - Removes the attribute and its value, if no value is specified for DELETE. The data type of the specified value must match the existing value's data type.If a set of values is specified, then those values are subtracted from the old set. For example, if the attribute value was the set [a,b,c] and the DELETE action specifies [a,c], then the final attribute value is [b]. Specifying an empty set is an error.

查看更多
孤傲高冷的网名
4楼-- · 2020-02-14 03:10

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)

查看更多
欢心
5楼-- · 2020-02-14 03:15

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 an UpdateExpression

查看更多
登录 后发表回答