Search code examples
pythonpython-3.xaws-lambdaamazon-dynamodbboto3

For a DynamoDB item, how can i append a list which is a value of a key only if the element is not exists in that list?


I have an item in DynamoDB that has a key which has values as a list. I want to append that list with new elements, only if they are not already exists in that list. I don't want to duplicate any element in that list. Item's structure is like below:

{
 "username": "blabla",
 "my_list": ["element1","element2"]
}

I use boto3 library in Python and this is my code block for the update:

response = my_table.update_item(
    Key = {
        'username': "blabla"
    },
    UpdateExpression="SET my_list = list_append(my_list, :i)",
    ExpressionAttributeValues={
        ':i': ["element1"],
    },
    ReturnValues="UPDATED_NEW"
)

I tried to use if_not_exist() in UpdateExpression but always got syntax errors. How can i properly achieve this goal? Thank you.


Solution

  • You should not use a list you need to use a String Set like defined as datatype here:

    https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html

    For adding values to a Set you need to use ADD UpdateOperation like described here

    https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html#Expressions.UpdateExpressions.ADD

    According to this you can change your code like

    {
     "username": "blabla",
     "my_list": set(["element1","element2"])
    }
    
    # ---
    
    response = my_table.update_item(
        Key = {
            'username': "blabla"
        },
        UpdateExpression="ADD my_list :i",
        ExpressionAttributeValues={
            ':i': set(["element1"]),
        },
        ReturnValues="UPDATED_NEW"
    )
    

    This answer shows howto remove items from the set again

    https://stackoverflow.com/a/56861830/13055947