0

I want to update items by incrementing columns with dynamic values and create a new record if it does exist.

Sample item:

{
key: 123,
attribute1: 1,
attribute2: 3,
expirationTime: 1 day from insert time
}

I want to update attribute1, and attribute2 with specific values. This can be achieved using below code

AttributeValue idAttributeValue = AttributeValue.builder().s("1234").build();
        Key key = Key.builder().partitionValue(idAttributeValue).build();

        // define the attribute value to add to the existing or new field
        AttributeValue countAttributeValue = AttributeValue.builder().n("5").build();

        // define the update expression to add values to an existing field or create a new field
        String updateExpression = "SET #c = if_not_exists(#c, :zero) + :count";
        Map<String, String> nameMap = ImmutableMap.of(
                "#c", "count"
        );
        Map<String, AttributeValue> valueMap = ImmutableMap.of(
                ":zero", AttributeValue.builder().n("0").build(),
                ":count", countAttributeValue
        );

        // create an UpdateItemRequest to update or create the item with the update expression
        UpdateItemRequest request = UpdateItemRequest.builder()
                .tableName("your-table-name")
                .key(key)
                .updateExpression(updateExpression)
                .expressionAttributeNames(nameMap)
                .expressionAttributeValues(valueMap)
                .build();

        // execute the UpdateItemRequest
        UpdateItemResponse response = client.updateItem(request);

But if the item doesn't exist I also want to create a new item and set expiration_time. I don't want to do a getOperation every time and check if the item exists or not and based on that do an insert or update operation. How can the above code be changed to insert a new record with expiration time if it doesn't exist and update values? If the record exists the expiration time shouldn't be modified during the update operation.

Mike Reddington
  • 192
  • 2
  • 15
  • https://stackoverflow.com/questions/32777374/is-it-possible-to-do-a-conditional-put-or-update-in-dynamodb Would this help? – qkhanhpro Mar 11 '23 at 05:03

0 Answers0