AWS Developer Tools Blog

Introducing DynamoDB Document API (Part 2)

In the previous blog, Introducing DynamoDB Document API (Part 1), we saw how to program against the DynamoDB Document API and produce code that is both easy to write and read.  But why is the API called the Document API, and how are JSON-style documents supported?

This perhaps can best be explained, well, with code! Using the same Game table from the previous blog, let’s start with a game object directly represented by a JSON document:

    {
        "Status" : "IN_PROGRESS",
        "GameId" : "abc",
        "Player1-Position" : 15,
        "Player2-Position" : 12
    }

First, we put this game to Amazon DynamoDB as a structured document:

AmazonDynamoDBClient client = new AmazonDynamoDBClient(...);
DynamoDB dynamodb = new DynamoDB(client);
Table table = dynamo.getTable("Game");
    
String json = "{"
                    + ""Status" : "IN_PROGRESS","
                    + ""GameId" : "abc","
                    + ""Player1-Position" : 15,"
                    + ""Player2-Position" : 12"
                    + "}"
                    ;
Item jsonItem = Item.fromJSON(json);
table.putItem(jsonItem);

Suppose we need to update the game, changing the status to “SUSPENDED”, and adding 1 to the first player’s position, but only if both players’ positions are less than 20 and if the current status is “IN_PROGRESS”:

UpdateItemOutcome outcome = table.updateItem(new UpdateItemSpec()
            .withReturnValues(ReturnValue.ALL_NEW)
            .withPrimaryKey("GameId", "abc")
            .withAttributeUpdate(
                new AttributeUpdate("Player1-Position").addNumeric(1), 
                new AttributeUpdate("Status").put("SUSPENDED"))
            .withExpected(
                new Expected("Player1-Position").lt(20),
                new Expected("Player2-Position").lt(20),
                new Expected("Status").eq("IN_PROGRESS"))
        );

Finally, let’s get back the updated document as JSON:


Item itemUpdated = outcome.getItem();
String jsonUpdated = itemUpdated.toJSONPretty();
System.out.println(jsonUpdated);

Here is the output in JSON:

    {
      "Status" : "SUSPENDED",
      "GameId" : "abc",
      "Player1-Position" : 16,
      "Player2-Position" : 12
    }

As you can see, saving JSON as a structured document in Amazon DynamoDB, or updating, retrieving and converting the document back into JSON is as easy as 1-2-3. :)  You can find more examples in the A-Z Document API quick-start folder at GitHub. Happy coding until next time!