Search code examples
amazon-dynamodbdynamodb-queries

dynamoDB conditional write only when there are N or less items in a map


We are storing a map in DynamoDB (not my design choice). So, basically a key can contain a list of values. Something like map[string][]someStruct.

We can only append a value to a given key if there are only N or less values for a given key. For example, if "key1" already has 3 values, I cannot append another value, but if it has less than 3 values, I can append one more value.

I looked at Conditional Writes, but couldn't find a conditional expression that would help with this. Any help is greatly appreciated. Thanks!


Solution

  • You would need to store the number of records in the list along side the list, perhaps something like this would work:

      {
        "key1": {
          "list": [1,2,3,4],
          "listLength": 4
        }
      }
    

    You'll need to make sure that the list and listLength are kept in sync.

    Alternatively you can get the item, check the length and then update with a condition to make sure it hasn't been updated between you get and update operation.