DynamoDB updates the counter (or inserts a key)

I have a function that creates pairs (some_key, some_value)that I want to add to my DynamoDB. If the key element is some_keyalready present, I want to add some_valueto the attributes value. Otherwise, I want to create such an element. Following the example of the docs , it seems like the function if_not_existsshould do what I want. I'm having syntax problems because my code returns an error:

>>>> table.update_item(
        Key={
            'key': my_key
        },
        UpdateExpression="set my_value = if_not_exist(my_value + :inc, :inc)",

        ExpressionAttributeValues={
            ':inc': my_increment,
        },
        ReturnValues="UPDATED_NEW"
    )

ClientError: An error occurred (ValidationException) when calling the UpdateItem operation: 
Invalid UpdateExpression: Syntax error; token: "+", near: "coocc + :val"
+4
source share
2 answers

You can do it as follows:

table.update_item(
    Key={
        'key': my_key
    },
    UpdateExpression="SET my_value = if_not_exists(my_value, :start) + :inc",

    ExpressionAttributeValues={
        ':inc': my_increment,
        ':start': 0,
    },
    ReturnValues="UPDATED_NEW"
)

update_item Will create a new item or update existing ones.

UpdateExpression , my_value my_value + :inc.

my_value , :start .

+3

ADD. docs:

ADD - , . , ADD

, boto3.client(), :

client.update_item(
    TableName='MyTable',
    Key={'myhash': {'S': 'myvalue'}},
    UpdateExpression="ADD #counter :increment",
    ExpressionAttributeNames={'#counter': 'counter'},
    ExpressionAttributeValues={':increment': {'N': '1'}}
) 

counter, , , .

+9

Source: https://habr.com/ru/post/1627058/


All Articles