How to update an item in dynamoDB using Java – DynamoDB UpdateItem

5 years ago Lalit Bhagtani 0

In this tutorial, we will learn about how to update an item in dynamoDB (UpdateItem) using java language.

DynamoDB

Amazon DynamoDB is a fully managed NoSQL database services offered by Amazon as part of its Amazon Web Service (AWS) portfolio. It provides fast and predictable performance with seamless scalability. DynamoDB is a key-value datastore, where each item (row) in a table is a key-value pair.

Project Setup

Create a simple maven project in your favorite IDE and add below mentioned dependency in your pom.xml file.

<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-java-sdk</artifactId>
  <version>1.11.524</version>
</dependency>

For latest version of aws library, check this page.

Table Schema

In this example, we will update an item in JOB table. Schema of this table is as follows:-

  1. CountryName (Partition Key) :- It represents name of the country for which job is posted. It is stored as String data type (ScalarAttributeType S).
  2. JobId (Sort Key) :- It represents unique id of the posted job. It is of Number datatype (ScalarAttributeType N).
  3. CompanyName :- It represents name of the company by which job is posted. It is of String datatype (ScalarAttributeType S).
  4. JobTitle :- As the name suggest, it represents tile of the job. It is of String datatype (ScalarAttributeType S).
  5. JobDescription :- It represents details job description. It is of String datatype (ScalarAttributeType S).

dynamodb updateitem

DynamoDB Connection

Create an object of AmazonDynamoDB ( com.amazonaws.services.dynamodbv2.AmazonDynamoDB ) class for sending a client request to dynamoDB. To get instance of this class, we will use AmazonDynamoDBClientBuilder builder class. It requires three important parameters :- 

  1. Region :- It is a region where dynamoDB table will be stored.
  2. ACCESS_KEY :- It is a access key for using dynamoDB. You can generate this key, using aws management console.
  3. SECRET_KEY :- It is a secret key of above mentioned access key.

Here is a code example :-

AmazonDynamoDB dynamoDB = AmazonDynamoDBClientBuilder.standard()
				.withRegion(Regions.AP_SOUTH_1)
				.withCredentials(new AWSStaticCredentialsProvider
                                                    (new BasicAWSCredentials("ACCESS_KEY","SECRET_KEY")))
				.build();

UpdateItem

Steps to create and send UpdateItemRequest to dynamoDB are as follows:-

  1. Instantiate UpdateItemRequest object, this object will send the client request to dynamoDB.
  2. Set name of the table whose item is to be updated. In our case JOB.
  3. Set return consumed capacity as TOTAL, this returns aggregate consumed capacity.
  4. Set return values as UPDATED_OLD, this returns old values of attributes that has been updated. Other possible values are ALL_OLDALL_NEWUPDATED_NEW, NONE }
  5. Create a map of primary key attributes and their values.
  6. Create a map of attributes and their values with the action ( PUT, ADD, DELETE ) that needs to be performed on item.
  7. Invoke the updateItem method on AmazonDynamoDB object by passing UpdateItemRequest object as an argument.

Example

import java.util.HashMap;
import java.util.Map;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.AttributeValueUpdate;
import com.amazonaws.services.dynamodbv2.model.ReturnConsumedCapacity;
import com.amazonaws.services.dynamodbv2.model.ReturnValue;
import com.amazonaws.services.dynamodbv2.model.UpdateItemRequest;
import com.amazonaws.services.dynamodbv2.model.UpdateItemResult;

public class UpdateItem {

	public static void main(String[] args) {

		/* Create DynamoDB Client Object */
		AmazonDynamoDB dynamoDB = AmazonDynamoDBClientBuilder.standard().withRegion(Regions.AP_SOUTH_1)
				.withCredentials(new AWSStaticCredentialsProvider(
						new BasicAWSCredentials("ACCESS_KEY","SECRET_KEY")))
				.build();

		/* Create an Object of UpdateItemRequest */
		UpdateItemRequest request = new UpdateItemRequest();

		/* Setting Table Name */
		request.setTableName("JOB");

		/* Setting Consumed Capacity */
		request.setReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL);

		/* To get old value of item's attributes before it is updated */
		request.setReturnValues(ReturnValue.UPDATED_OLD);
		
		/* Create a Map of Primary Key attributes */
		Map<String, AttributeValue> keysMap = new HashMap<>();
		keysMap.put("CountryId", new AttributeValue("18"));
		keysMap.put("JobId", (new AttributeValue()).withN("1"));		
		request.setKey(keysMap);

		/* Create a Map of attributes to be updated */
		Map<String, AttributeValueUpdate> map = new HashMap<>();
		map.put("CompanyName", new AttributeValueUpdate(new AttributeValue("Amazon"),"PUT"));
		map.put("JobTitle", new AttributeValueUpdate(new AttributeValue("Senior Software Engineer"),"PUT"));
		request.setAttributeUpdates(map);

		try {
			/* Send Update Item Request */
			UpdateItemResult result = dynamoDB.updateItem(request);

			System.out.println("Status : " + result.getSdkHttpMetadata().getHttpStatusCode());

			System.out.println("Consumed Capacity : " + result.getConsumedCapacity().getCapacityUnits());

			/* Printing Old Attributes Name and Values */
			if (result.getAttributes() != null) {
				result.getAttributes().entrySet().stream()
						.forEach(e -> System.out.println(e.getKey() + " " + e.getValue()));
			}

		} catch (AmazonServiceException e) {

			System.out.println(e.getErrorMessage());

		}

	}

}

Action

Action specifies how to perform the update operation on item with the specified primary key. Three different types of action that can be specified are PUT (default), DELETE, and ADD. The behavior of the action depends on whether the specified primary key already exists in the table or not.

If an item with the specified primary key is already present in the table :-

  1. PUT :- If the attribute does not exists for the item, then the attribute and its values are added to the item otherwise attribute value is replaced by the new value.
  2. DELETE :- If no value is specified, then the attribute and its value are removed from the item. The data type of the specified value must match the existing value’s data type. If the existing value and new value both are set of same data type like number sets or string sets, then new value and existing value are subtracted through set difference operation. Specifying an empty set is an error.
  3. ADD :- If the attribute does not already exist, then the attribute and its values are added to the item. If the attribute does exist, then the behavior of ADD depends on the data type of the attribute:
    1. Number :- If the existing value and new value both are number, then new value is added to the existing value. If new value is a negative number, then it is subtracted from the existing value. If existing value doesn’t exist then 0 is consider as the initial value.
    2. Set :- If the existing value and new value both are set of same data type like number sets or string sets, then new value and existing value are added through set union operation. is added to the existing value.

    This action is only valid for an existing attribute whose data type is number or is a set. Do not use ADD for any other data types.

If an item with the specified primary key does not exists in the table :-

  1. PUT :- It creates a new item with the specified primary key, and then adds the attribute.
  2. DELETE :- No operation is performed as there is no attribute to delete.
  3. ADD :- It creates an item with the specified primary key and number (or set of numbers) for the attribute value. The only data types allowed are number and number set, no other data types can be specified.

References :-

  1. UpdateItemRequest Java Docs
  2. UpdateItemResult Java Docs

That’s all for how to update an item in dynamoDB (UpdateItem) using java language. If you liked it, please share your thoughts in comments section and share it with others too.