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.
CodePudding user response:
You should not use a list you need to use a String Set like defined as datatype here:
For adding values to a Set you need to use ADD UpdateOperation like described here
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