fogwolf
fogwolf

Reputation: 941

Update JSON Document attribute in DynamoDB with Java SDK

I have a DynamoDB table with 2 attributes - a String for an ID and a JSON document. From my research I've found there is not a way to specify JSON as the type for Table.updateItem() in the Java SDK. For my update I want to overwrite the JSON document completely rather than go in an update specific attributes. I also want to do an updateItem rather than putItem (since it did seem like I could use putItem since I am just overwriting the document every time) because I will eventually have some other top-level attributes in my table that I do not want to overwrite or update every time I need to do an update - I want to be able to come in and just update the document attribute and update it completely.

I've gotten something that almost works for my CRUD operations but am wondering if there's a better way. For example I'm doing something like this:

public <T extends BaseEntity> void updateObject(T newEntity, UUID uuid) {
    try {
        TypeReference<HashMap<String, Object>> typeRef = 
            new TypeReference<HashMap<String, Object>>() {};
        HashMap<String, Object> dataMap = 
            mapper.readValue(mapper.writeValueAsString(newEntity), typeRef);

        UpdateItemSpec updateItemSpec = new UpdateItemSpec()
                .withPrimaryKey("Id", uuid.toString())
                .withAttributeUpdate(new AttributeUpdate("data").put(dataMap))
                .withReturnValues(ReturnValue.UPDATED_NEW);

        UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
    } catch (Exception e) {}
}

I really wish I could just do something like this instead:

UpdateItemSpec updateItemSpec = new UpdateItemSpec()
    .withPrimaryKey("Id", uuid.toString())
    .withUpdateExpression("set #da = :d")
    .withNameMap(new NameMap()
        .with("#da", "data"))
    .withValueMap(new ValueMap()
        .withJSON(":d", objectAsStr)) // withJSON() method sadly doesn't exist
    .withReturnValues(ReturnValue.UPDATED_NEW);

Any help or suggestions greatly appreciated. Thanks.

Upvotes: 1

Views: 1562

Answers (1)

Alexander Patrikalakis
Alexander Patrikalakis

Reputation: 5205

Today, it seems that ValueMap.withJSON(String) method exists.

Upvotes: 1

Related Questions