Home > Software design >  Dynamodb update multiple items in one transaction
Dynamodb update multiple items in one transaction

Time:12-12

In my dynamodb table, I have a scenario where when I add a new item to my table, I need to also increment a counter for another entry in my table.

For instance, when USER#1 follows USER#2, I would like to increment followers count for USER#2.

HashKey RangeKey counter
USER1 USER2
USER3 USER2
USER2 USER2 2

I do not want to use auto-increment as I want to control how the increment happens.

Naturally, everything works as expected if I make two update calls to dynamodb. One to create the relationship between users and another to update the count for the other user.

The question is, if it is a good approach to make two such calls or would a transactWrite be a better alternative.

If so how could I make an increment using transactwrite api.

I can add items using the following approach. But I am not sure how I can increment

"TransactItems": [
            {
                "Put": {
                    "TableName": "Table",
                    "Item": {
                        "hashKey": {"S":"USER1"}, 
                        "rangeKey": {"S":"USER2"}
                    }
                }
            },
            {
                "Update": {
                    "TableName": "TABLE",
                    "Key": {
                        "hashKey": {"S":"USER2"}, 
                        "rangeKey": {"S":"USER2"}
                    },
                    "ConditionExpression": "#cefe0 = :cefe0",
                    "ExpressionAttributeNames": {"#cefe0":"counter"},
                    "ExpressionAttributeValues": ?? how do I increment here
                }
            }
        ]

CodePudding user response:

Transactions would defintely be the best way to approach it, you can increment using SET in the UpdateExpression:

"TransactItems": [
        {
            "Put": {
                "TableName": "Table",
                "Item": {
                    "hashKey": {"S":"USER1"}, 
                    "rangeKey": {"S":"USER2"}
                }
            }
        },
        {
            "Update": {
                "TableName": "TABLE",
                "Key": {
                    "hashKey": {"S":"USER2"}, 
                    "rangeKey": {"S":"USER2"}
                },
                "UpdateExpression": "SET #cefe0 = #cefe0   :cefe0",
                "ExpressionAttributeNames": {"#cefe0":"counter"},
                "ExpressionAttributeValues": {"cefe0": {"N": "1"}}
            }
        }
    ]
  • Related