Add or remove an entry from a List type attribute in a DynamoDB table item

后端 未结 3 782
忘了有多久
忘了有多久 2020-12-04 02:14

I have a very simple class, with a string type primary key and List type attributes. I want to write an API for adding and removing an item from the attribute list, and savi

相关标签:
3条回答
  • 2020-12-04 02:21

    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

    0 讨论(0)
  • 2020-12-04 02:27

    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.

    0 讨论(0)
  • 2020-12-04 02:37

    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.

    0 讨论(0)
提交回复
热议问题