简体   繁体   中英

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.

如今,似乎ValueMap.withJSON(String)方法存在

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM