chack
chack

Reputation: 37

DynamoDB update_item: Increase values for existing items or use 1 for new item

I try to use updateitem as according to the wiki it works for updating existing & creating new items:

"Edits an existing item's attributes, or adds a new item to the table if it does not already exist."

I want to store:

I have following code:

table.update_item(
                Key={'item':"NEW"},
                UpdateExpression="SET opens = if_not_exists(opens + :var1, :var0), last_open = :var2, first_open = if_not_exists(first_open, :var3)",
                ExpressionAttributeValues={
                ':var0': "0",
                ':var1': "1",
                ':var2': '2020-04-01',
                ':var3': '1999-01-01'
                },
        ReturnValues="UPDATED_NEW"
                )

runs into error for new & existing items and says

An error occurred (ValidationException) when calling the UpdateItem operation: Invalid UpdateExpression: Syntax error; token: \"+\", near: \"opens + :var1\""

Following works for existing items but throws an error for new ones:

table.update_item(
            Key={'item':"NEW"},
            UpdateExpression="SET opens = opens + :var1, last_open = :var2, first_reachout = if_not_exists(first_open, :var3)",
            ExpressionAttributeValues={
            ':var1': "1",
            ':var2': '2020-04-01',
            ':var3': '1999-01-01'
            },
    ReturnValues="UPDATED_NEW"
            )

Error for only new ones:

"An error occurred (ValidationException) when calling the UpdateItem operation: The provided expression refers to an attribute that does not exist in the item"

I guess it means the contacts attribute, but including it into "if_not_exists" also does not work....

Upvotes: 0

Views: 519

Answers (1)

Nadav Har'El
Nadav Har'El

Reputation: 13731

You can find the documentation for the UpdateExpression syntax in https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html#Expressions.UpdateExpressions.SET. The relevant part for your question is the following:

value ::=
    operand
    | operand '+' operand
    | operand '-' operand

operand ::=
    path | function

Which means, the "+" can only be at the top level of the expression, it cannot be inside the function's parameters.

Luckily, there is an easy workaround for you. Instead of the if_not_exists(opens + :var1, :var0) which you tried, try" :var1 + if_not_exists(opens, :var0).

Upvotes: 2

Related Questions