1

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.

Bharath Bharath
  • 59
  • 1
  • 10

1 Answers1

1

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:

  1. It checks if the #dataname attribute exists, if that's the case it is used, otherwise the value of :empty_list will be used in its place
  2. Then the new value(s) will be appended to the list.
Maurice
  • 11,482
  • 2
  • 25
  • 45
  • 1
    Thank you. This works exactly as i wanted. @Maurice – Bharath Bharath Feb 10 '21 at 17:30
  • Out of curiosity, suppose the attribute "dataname" is a MAP, is it still possible to do this ? Guess list_append won't work then. @Maurice – Bharath Bharath Feb 11 '21 at 05:34
  • I'd be surprised if list_appends works for map, you're probably right about that. [Here](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html#Expressions.UpdateExpressions.SET.AddingNestedMapAttributes) is an example of setting nested map attributes, you can probably use the `if_not_exists` technique there as well - just add an empty map and not an empty list ;-) – Maurice Feb 11 '21 at 07:45