1

I need to constantly increment values for a map field value in DynamoDB. The map will contain keys with counters, and for each update I want to atomically increment the keys. The corner case is that for this operation it needs to do an upsert, meaning, if the record/property doesn't exist it should be created, otherwise updated (a.k.a. incremented).

The given Java code below shows what I'm trying to achieve:

DynamoDbClient client = DynamoDbClient.builder()
  .credentialsProvider(
    StaticCredentialsProvider.create(
      AwsBasicCredentials.create("test-key", "test-secret")))
  .region(Region.EU_CENTRAL_1)
  .endpointOverride(URI.create("http://localhost:4566"))
  .build();

client.transactWriteItems(TransactWriteItemsRequest.builder()
  .transactItems(TransactWriteItem.builder()
    .update(Update.builder()
      .tableName("my-table")
      .key(Map.of("id", AttributeValue.builder().s("123").build()))
      .updateExpression("""
        SET itemId  = if_not_exists(itemId, :itemId)
        ADD #val.#country :value
      """)
      .expressionAttributeNames(Map.of(
        "#val", "value",
        "#country", "Portugal" // in other invocations this might be a different country
      ))
      .expressionAttributeValues(Map.of(
        ":itemId", AttributeValue.builder().s("1234").build(),
        ":value", AttributeValue.builder().n("1").build()))
      .build())
    .build())
  .build());

Every time I run this operation I get the following error:

Exception in thread "main" software.amazon.awssdk.services.dynamodb.model.DynamoDbException: The document path provided in the update expression is invalid for update (Service: DynamoDb, Status Code: 400, Request ID: XXX)

Does somebody know how I could achieve this functionality?

João Pedro Schmitt
  • 1,046
  • 1
  • 11
  • 25
  • Can you share the item you're trying to update? My hunch is that `value.Portugal` isn't a map or something similar that would cause the Update Expression to fail for `ADD`. – Chris Anderson Feb 02 '23 at 15:55
  • Actually, in this example, I'm trying to create the record. I'm looking for an upsert operation, that creates the item if it doesn't exist, and in the other case updates it by ADDing elements to the map. – João Pedro Schmitt Feb 04 '23 at 12:48

0 Answers0