Reputation: 99
I'm trying to add value to the attribute "dataname" which is type LIST in the dynamoDB table.
response = table.update_item(
Key={"name": xyz},
UpdateExpression="SET dataname = list_append(dataname, :i)"
ExpressionAttributeValues={
':i': [1200, readonly],
},
)
The above logic works only if the attribute "dataname" is already present in the item. If the attribute is not present it gives the following error: "The provided expression refers to an attribute that does not exist in the item".
Is there a way to add the attribute "dataname" if it does not exist in the item and then update the values ? I'm using Python language for this.
Upvotes: 3
Views: 3914
Reputation: 13197
I recently used an implementation like this:
import boto3
update_expression = "SET #dataname = list_append(if_not_exists(#dataname, :empty_list), :i)"
dynamodb = boto3.resource("dynamodb")
result_table = dynamodb.Table(TABLE_NAME)
result_table.update_item(
Key={
"name": "xyz",
},
UpdateExpression=update_expression,
ExpressionAttributeNames={
"#dataname": "dataname",
},
ExpressionAttributeValues={
":empty_list": [],
":i": [1200, readonly],
)
This is adapted from an implementation for NodeJS I found on stackoverflow by Nasreen Ustad) and translated to Python. (Looks like there is a sort of canonical answer for this without the complete implementation)
It basically works like this:
#dataname
attribute exists, if that's the case it is used, otherwise the value of :empty_list
will be used in its placeUpvotes: 1