Amazon DynamoDB
Developer Guide (API Version 2012-08-10)
« PreviousNext »
View the PDF for this guide.Go to the AWS Discussion Forum for this product.Go to the Kindle Store to download this guide in Kindle format.Did this page help you?  Yes | No |  Tell us about it...

Working with Items Using the AWS SDK for Java Low-Level API

You can use AWS SDK for Java low-level API (protocol-level API) to perform typical create, read, update, and delete (CRUD) operations on an item in a table. The Java API for item operations maps to the underlying Amazon DynamoDB API. For more information, see Using the Amazon DynamoDB API.

The following are the common steps to perform data create, read, update, and delete (CRUD) operations using the Java low-level API.

  1. Create an instance of the AmazonDynamoDBClient class (the client).

  2. Provide the required operation specific information by creating a corresponding request object, for example, create a PutItemRequest object to upload an item and the GetItemRequest object to retrieve an existing item.

    You can use the request object to also provide any optional parameters supported by the operation.

  3. Execute the appropriate method provided by the client by passing in the request object that you created in the preceding step. The AmazonDynamoDBClient client provides putItem, getItem, updateItem, and deleteItem methods for the CRUD operations.

Putting an Item

The putItem method stores an item in a table. If the item exists, it replaces the entire item. Instead of replacing the entire item, if you want to update only specific attributes, you can use the updateItem method. For more information, see Updating an Item.

The following are the commons steps to upload an item using the low-level Java SDK API.

  1. Create an instance of the AmazonDynamoDBClient by providing your credentials.

  2. Create an instance of the PutItemRequest class by providing the name of the table to which you want to add the item and the item that you wish to upload.

  3. Execute the putItem method by providing the PutItemRequest object that you created in the preceding step.

The following Java code snippet demonstrates the preceding tasks. The snippet stores an item in the ProductCatalog table.

client = new AmazonDynamoDBClient(credentials);
String tableName = "ProductCatalog";

Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
item.put("Id", new AttributeValue().withN("104"));
item.put("Title", new AttributeValue().withS("Book 104 Title"));
item.put("ISBN", new AttributeValue().withS("111-1111111111"));
item.put("Price", new AttributeValue().withS("25.00"));
item.put("Authors", new AttributeValue()
    .withSS(Arrays.asList("Author1", "Author2")));

PutItemRequest putItemRequest = new PutItemRequest()
  .withTableName(tableName)
  .withItem(item);
PutItemResult result = client.putItem(putItemRequest);

In the preceding example, you upload a book item that has the Id, Title, ISBN, and Authors attributes. Note that the Authors attribute is a multi-valued string attribute.

Specifying Optional Parameters

Along with the required parameters, you can also specify optional parameters to the putItem method. For example, the following Java code snippet uses an optional parameter to specify a condition for uploading the item. If the condition you specify is not met, then the AWS Java SDK throws a ConditionalCheckFailedException. The code snippet specifies the following optional parameters in the PutItemRequest:

  • A list of ExpectedAttributeValue objects that define conditions for the request. The snippet defines the condition that the existing item that has the same primary key is replaced only if it has an ISBN attribute that equals a specific value.

  • One of the ReturnValue enumeration values that defines what type of data the putItem request returns.

Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
item.put("Id", new AttributeValue().withN("104"));
item.put("Title", new AttributeValue().withS("Book 104 Title"));
item.put("ISBN", new AttributeValue().withS("222-2222222222"));
item.put("Price", new AttributeValue().withS("20.00"));
item.put("Authors", new AttributeValue()
    .withSS(Arrays.asList("Author1", "Author2")));

// Optional parameters Expected and ReturnValue.
Map<String, ExpectedAttributeValue> expected = new HashMap<String, ExpectedAttributeValue>();
expected.put("ISBN", new ExpectedAttributeValue()
    .withValue( new AttributeValue().withS("111-1111111111")));
ReturnValue retVal = ReturnValue.ALL_OLD;

PutItemRequest putItemRequest = new PutItemRequest()
    .withTableName(tableName)
    .withItem(item)
    .withExpected(expected)
    .withReturnValues(retVal);
PutItemResult result = client.putItem(putItemRequest);

For more information about the parameters and the API, see PutItem.

Getting an Item

The getItem method retrieves an item. To retrieve multiple items, you can use the batchGetItem method.

The following are the commons steps that you follow to retrieve an item using the low-level Java SDK API.

  1. Create an instance of the AmazonDynamoDBClient by providing your credentials.

  2. Create an instance of the GetItemRequest class by providing the name of the table from which you want to retrieve an item and the primary key of the item that you want to retrieve.

  3. Execute the getItem method by providing the GetItemRequest object that you created in the preceding step.

The following Java code snippet demonstrates the preceding steps. The code snippet gets the item that has the specified hash primary key.

HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
key.put("Id", new AttributeValue().withN("101"));

GetItemRequest getItemRequest = new GetItemRequest()
    .withTableName(tableName)
    .withKey(key);

GetItemResult result = client.getItem(getItemRequest);
Map<String, AttributeValue> map = result.getItem();

Specifying Optional Parameters

Along with the required parameters, you can also specify optional parameters for the getItem method. For example, the following Java code snippet uses an optional method to retrieve only a specific list of attributes. The code example specifies the following optional parameters in the GetItemRequest:

  • A list of names that defines the attributes to retrieve.

  • A Boolean value that specifies whether to perform a strongly consistent read. To learn more about read consistency, see Data Read and Consistency Considerations.

List<String> attributesToGet = new ArrayList<String>(
    Arrays.asList("Id", "ISBN", "Title", "Authors"));
        
HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
key.put("Id", new AttributeValue().withN("201"));

GetItemRequest getItemRequest = new GetItemRequest()
    .withTableName(tableName)
    .withKey(key)
    .withAttributesToGet(attributesToGet)
    .withConsistentRead(true);

GetItemResult result = client.getItem(getItemRequest);
Map<String, AttributeValue> map = result.getItem();

For more information about the parameters and the API, see GetItem.

Batch Write: Putting and Deleting Multiple Items

Batch write refers to putting and deleting multiple items in a batch. The batchWriteItem method enables you to put and delete multiple items from one or more tables in a single API call. The following are the steps to put or delete multiple items using the low-level Java SDK API.

  1. Create an instance of the AmazonDynamoDBClient class by providing your credentials.

  2. Create an instance of the BatchWriteItemRequest class that describes all the put and delete operations.

  3. Execute the batchWriteItem method by providing the BatchWriteItemRequest object that you created in the preceding step.

  4. Process the response. You should check if there were any unprocessed request items returned in the response. This could happen if you reach the provisioned throughput limit or some other transient error. Also, Amazon DynamoDB limits the request size and the number of operations you can specify in a request. If you exceed these limits, Amazon DynamoDB rejects the request. For more information, see BatchWriteItem.

The following Java code snippet demonstrates the preceding steps. The example creates a BatchWriteItemRequest to perform the following write operations:

  • Put an item in the Forum table

  • Put and delete an item from Thread table

The code then executes the batchWriteItem to perform a batch operation.

// Create a map for the requests in the batch
Map<String, List<WriteRequest>> requestItems = new HashMap<String, List<WriteRequest>>();
        
// Create a PutRequest for a new Forum item
Map<String, AttributeValue> forumItem = new HashMap<String, AttributeValue>();
forumItem.put("Name", new AttributeValue().withS("Amazon ElastiCache"));
forumItem.put("Threads", new AttributeValue().withN("0"));

List<WriteRequest> forumList = new ArrayList<WriteRequest>();
forumList.add(new WriteRequest().withPutRequest(new PutRequest().withItem(forumItem)));
requestItems.put("Forum", forumList);
        
// Create a PutRequest for a new Thread item
Map<String, AttributeValue> threadItem = new HashMap<String, AttributeValue>();
threadItem.put("ForumName", new AttributeValue().withS("Amazon ElastiCache"));
threadItem.put("Subject", new AttributeValue().withS("ElastiCache Thread 1"));

List<WriteRequest> threadList = new ArrayList<WriteRequest>();
threadList.add(new WriteRequest().withPutRequest(new PutRequest().withItem(threadItem)));

// Create a DeleteRequest for a Thread item
HashMap<String, AttributeValue> threadDeleteKey = new HashMap<String, AttributeValue>();
threadDeleteKey.put("ForumName", new AttributeValue().withS("Some hash attribute value"));
threadDeleteKey.put("Subject", new AttributeValue().withS("Some range attribute value"));
    
threadList.add(new WriteRequest().withDeleteRequest(new DeleteRequest().withKey(threadDeleteKey)));
requestItems.put("Thread", threadList);

// Code for checking unprocessed items is omitted in this example
       
BatchWriteItemResult result;
BatchWriteItemRequest batchWriteItemRequest = new BatchWriteItemRequest();
                           
batchWriteItemRequest.withRequestItems(requestItems);
result = client.batchWriteItem(batchWriteItemRequest);

For a working example, see Example: Batch Write Operation Using the AWS SDK for Java Low-Level API.

Batch Get: Getting Multiple Items

The batchGetItem method enables you to retrieve multiple items from one or more tables. To retrieve a single item, you can use the getItem method.

The following are the commons steps that you follow to get multiple items using the low-level Java SDK API.

  1. Create an instance of the AmazonDynamoDBClient class by providing your credentials.

  2. Create an instance of the BatchGetItemRequest class that describes the table name, and a list of primary key values to retrieve. For the items that you are retrieving, you can optionally specify a list of attributes to retrieve.

  3. Execute the batchGetItem method by providing the BatchGetItemRequest object that you created in the preceding step.

The following Java code snippet demonstrates the preceding steps. The example retrieves two items from the Forum table and three items from the Thread table. The BatchGetItemRequest class has a withRequestItems method, which takes a HashMap of table names and primary keys to retrieve.

String table1Name = "Table1";
String table2Name = "Table2";
    	
HashMap<String, KeysAndAttributes> requestItems = new HashMap<String, KeysAndAttributes>();

ArrayList<Map<String, AttributeValue>> keys1 = new ArrayList<Map<String, AttributeValue>>();
    	
HashMap<String, AttributeValue> table1key1 = new HashMap<String, AttributeValue>();
table1key1.put("hashattribute", new AttributeValue().withS("Amazon S3"));
keys1.add(table1key1);
HashMap<String, AttributeValue> table1key2 = new HashMap<String, AttributeValue>();
table1key2.put("hashattribute", new AttributeValue().withS("Amazon DynamoDB"));
keys1.add(table1key2);
		
requestItems.put(table1Name, new KeysAndAttributes().withKeys(keys1));    	
    	
ArrayList<Map<String, AttributeValue>> keys2 = new ArrayList<Map<String, AttributeValue>>();

HashMap<String, AttributeValue> table2key1 = new HashMap<String, AttributeValue>();
table2key1.put("hashattribute", new AttributeValue().withS("Amazon DynamoDB"));
table2key1.put("rangeattribute", new AttributeValue().withS("DynamoDB Thread 1"));
keys2.add(table2key1);
HashMap<String, AttributeValue> table2key2 = new HashMap<String, AttributeValue>();
table2key2.put("hashattribute", new AttributeValue().withS("Amazon DynamoDB"));
table2key2.put("rangeattribute", new AttributeValue().withS("DynamoDB Thread 2"));
keys2.add(table2key2);
HashMap<String, AttributeValue> table2key3 = new HashMap<String, AttributeValue>();
table2key3.put("hashattribute", new AttributeValue().withS("Amazon S3"));
table2key3.put("rangeattribute", new AttributeValue().withS("S3 Thread 1"));
keys2.add(table2key3);

requestItems.put(table2Name, new KeysAndAttributes().withKeys(keys2));

BatchGetItemRequest batchGetItemRequest = new BatchGetItemRequest()
    .withRequestItems(requestItems);
    	
BatchGetItemResult result = client.batchGetItem(batchGetItemRequest);

List<Map<String,AttributeValue>> table1Results = result.getResponses().get(table1Name);
System.out.println("Items in table " + table1Name);
for (Map<String,AttributeValue> item : table1Results) {
    System.out.println(item);
}

List<Map<String,AttributeValue>> table2Results = result.getResponses().get(table2Name);
System.out.println("Items in table " + table2Name);
for (Map<String,AttributeValue> item : table2Results) {
    System.out.println(item);
}
          

Specifying Optional Parameters

Along with the required parameters, you can also specify optional parameters for the batchGetItem method. For example, you can optionally specify a list of attributes to retrieve as shown in the following Java code snippet. The code snippet retrieves two items from the Forum table. It specifies a list of attributes to retrieve by using the withAttributesToGet method.

HashMap<String, KeysAndAttributes> requestItems = new HashMap<String, KeysAndAttributes>();

ArrayList<Map<String, AttributeValue>> keys1 = new ArrayList<Map<String, AttributeValue>>();
    	
HashMap<String, AttributeValue> table1key1 = new HashMap<String, AttributeValue>();
table1key1.put("hashattribute", new AttributeValue().withS("Amazon S3"));
keys1.add(table1key1);
HashMap<String, AttributeValue> table1key2 = new HashMap<String, AttributeValue>();
table1key2.put("hashattribute", new AttributeValue().withS("Amazon DynamoDB"));
keys1.add(table1key2);
		
requestItems.put(table1Name, 
    new KeysAndAttributes()
        .withKeys(table1key1, table1key2)
        .withAttributesToGet("Threads"));

BatchGetItemRequest batchGetItemRequest = new BatchGetItemRequest()
    .withRequestItems(requestItems);

BatchGetItemResult result = client.batchGetItem(batchGetItemRequest);

For more information about the parameters and the API, see BatchGetItem.

Updating an Item

You can use the updateItem method to update existing attribute values, add new attributes to the existing collection, or delete attributes from the existing collection. You provide these updates by creating an UpdateItemRequest instance that describes the updates that you want to perform.

The updateItem method uses the following guidelines:

  • If an item does not exist, the updateItem function adds a new item using the primary key that is specified in the input.

  • If an item exists, the updateItems function applies the updates as follows:

    • Replaces the existing attribute values with the values in the update.

    • If the attribute you provide in the input does not exist, it adds a new attribute to the item.

    • If you use AttributeAction.ADD for the Action, you can add values to an existing set (string or number set), or mathematically add (use a positive number) or subtract (use a negative number) from the existing numeric attribute value.

Note

The putItem operation (Putting an Item) can also perform an update. For example, if you call putItem to upload an item and the primary key exists, the putItem operation replaces the entire item. Note that, if there are attributes in the existing item and those attributes are not specified in the input, the putItem operation deletes those attributes. However, the updateItem API only updates the specified input attributes so that any other existing attributes of that item remain unchanged.

The following are the commons steps that you follow to update an existing item using the low-level Java SDK API.

  1. Create an instance of the AmazonDynamoDBClient client by providing your security credentials.

  2. Create an UpdateItemRequest instance by providing all the updates that you wish to perform.

    To delete an existing attribute specify the attribute name with null value.

  3. Execute the updateItem method by providing the UpdateItemRequest object that you created in the preceding step.

The following Java code snippet demonstrates the preceding tasks. The snippet updates a book item in the ProductCatalog table. It adds a new author to the Authors multi-valued attribute and deletes the existing ISBN attribute. It also reduces the price by one.

Map<String, AttributeValueUpdate> updateItems = new HashMap<String, AttributeValueUpdate>();

HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
key.put("Id", new AttributeValue().withN("101"));

// Add two new authors to the list.
updateItems.put("Authors", 
  new AttributeValueUpdate()
    .withAction(AttributeAction.ADD)
    .withValue(new AttributeValue().withSS("AuthorYY", "AuthorZZ")));
 
// Reduce the price. To add or subtract a value,
// use ADD with a positive or negative number.
updateItems.put("Price", 
  new AttributeValueUpdate()
    .withAction(AttributeAction.ADD)
    .withValue(new AttributeValue().withN("-1")));
           
// Delete the ISBN attribute.
updateItems.put("ISBN", 
  new AttributeValueUpdate()
    .withAction(AttributeAction.DELETE));
            
UpdateItemRequest updateItemRequest = new UpdateItemRequest()
  .withTableName(tableName)
  .withKey(key).withReturnValues(ReturnValue.UPDATED_NEW)
  .withAttributeUpdates(updateItems);
            
UpdateItemResult result = client.updateItem(updateItemRequest);

Specifying Optional Parameters

Along with the required parameters, you can also specify optional parameters for the updateItem method including an expected value that an attribute must have if the update is to occur. If the condition you specify is not met, then the AWS Java SDK throws an ConditionalCheckFailedException. For example, the following Java code snippet conditionally updates a book item price to 25. It specifies the following optional parameters:

  • A hash table of keys and ExpectedAttributeValue objects that set a condition that the price should be updated only if the existing price is 20.00.

  • A ReturnValue enumeration value that specifies that the updateItem operation should return the updated item.

Map<String, AttributeValueUpdate> updateItems = new HashMap<String, AttributeValueUpdate>();
Map<String, ExpectedAttributeValue> expectedValues = new HashMap<String, ExpectedAttributeValue>();

HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
key.put("Id", new AttributeValue().withN("101"));

// Specify the desired price – 25.00.
updateItems.put("Price", 
        new AttributeValueUpdate()
            .withAction(AttributeAction.PUT)
            .withValue(new AttributeValue().withN("25.00")));

expectedValues.put("Price",
        new ExpectedAttributeValue()
            .withValue(new AttributeValue().withN("20.00")));

ReturnValue returnValue = ReturnValue.ALL_NEW;

UpdateItemRequest updateItemRequest = new UpdateItemRequest()
    .withTableName(tableName)
    .withKey(key)
    .withAttributeUpdates(updateItems)
    .withExpected(expectedValues)
    .withReturnValues(returnValues);

UpdateItemResult result = client.updateItem(updateItemRequest);

For more information about the parameters and the API, see http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html.

Deleting an Item

The deleteItem method deletes an item from a table.

The following are the commons steps that you follow to delete an item using the low-level Java SDK API.

  1. Create an instance of the AmazonDynamoDBClient client by providing your security credentials.

  2. Create a DeleteItemRequest instance by providing the name of the table from which you want to delete the item and the primary key of the item that you want to delete.

  3. Execute the deleteItem method by providing the DeleteItemRequest object that you created in the preceding step.

HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue> ();
key.put("Id", new AttributeValue().withN("101"));
      	
DeleteItemRequest deleteItemRequest = new DeleteItemRequest()
    .withTableName(tableName)
    .withKey(key);
      	
DeleteItemResult deleteItemResult = client.deleteItem(deleteItemRequest);

Specifying Optional Parameters

Along with the required parameters, you can also specify optional parameters for the DeleteItem method. For example, the following Java code snippet specifies the following optional parameters:

  • A hash table of keys and ExpectedAttributeValues objects that specify that the Book item in the ProductCatalog table be deleted only if the book is no longer in publication (the InPublication attribute value is false). Boolean values are stored as numeric 0 and 1.

  • A ReturnValue enumeration value to request that the DeleteItem method return the item that was deleted.

HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue> ();
key.put("Id", new AttributeValue().withN("103"));

Map<String, ExpectedAttributeValue> expectedValues = new HashMap<String, ExpectedAttributeValue>();
expectedValues.put("InPublication",
    new ExpectedAttributeValue()
        .withValue(new AttributeValue().withN("0"))); // Boolean stored as 0 or 1.

    DeleteItemRequest deleteItemRequest = new DeleteItemRequest()
        .withTableName(tableName)
        .withKey(key)
        .withExpected(expectedValues)
        .withReturnValues(ReturnValue.ALL_OLD);
 
        DeleteItemResult deleteItemResult = client.deleteItem(deleteItemRequest);

For more information about the parameters and the API, see DeleteItem.

Additional AWS SDK for Java APIs

The examples in this section use AWS SDK for Java low-level API. Additionally, the SDK provides Object Persistence Model API that enable you to map your client-side classes to your Amazon DynamoDB tables. For more information, see Using the AWS SDK for Java.