简体   繁体   中英

DynamoDB: Update atomic counter and add other info if new item

I have a db with only one hash key, and two numeric values: counter and some_value .

I want to update the atomic counter counter . I know that boto /DyamoDb will take care for me of the creation of the element if not already present in the db.

Since I am creating the element, I'd like to use the same write operation to also put some_value in the db. Is it possible at all to modify the update_item code in that respect?

table.update_item(
            Key={
                'my_key': some_string
            },
            UpdateExpression="SET counter = if_not_exists(counter , :start) + :inc",
            ExpressionAttributeValues={
                ':inc': 1,
                ':start' : 0
            },
            ReturnValues="UPDATED_NEW"
        )

Yes , you can also update some_item along with your counter. In fact, you can update multiple items. Below is the tried and tested code for updating multiple values.

    table.update_item(
    Key={
        'my_key': some_string
    },
    UpdateExpression="SET #counter = if_not_exists(#counter, :start) + :inc, #some_value = if_not_exists(#some_value, :start) - :inc",
    ExpressionAttributeNames={'#counter': 'counter', '#some_value': 'some_value'},
    ExpressionAttributeValues={
        ':inc': 1,
        ':start': 0
    },
    ReturnValues="UPDATED_NEW"
)

PS: Always define your expression attribute names rather than directly using it in the expression to avoid conflicts and subsequent errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM