DynamoDB get all items with partition key java

What you will learn here about AWS

  • DynamoDB get all items with partition key java

DynamoDB get all items with partition key java

Please follow the following steps to know how to get DynamoDB all items with partition key using java

1)First create a simple maven project

2)Add maven AWS spring boot dependency which is shown below
aws lambda spring boot dependency

	
	<dependency>
	    <groupId>com.amazonaws</groupId>
	    <artifactId>aws-java-sdk-dynamodb</artifactId>
	    <version>1.12.125</version>
	</dependency>
	  	
	<dependency>
	    <groupId>com.amazonaws</groupId>
	    <artifactId>aws-lambda-java-core</artifactId>
	    <version>1.1.0</version>
	</dependency>
	  	
	<dependency>
	    <groupId>com.amazonaws</groupId>
	    <artifactId>aws-lambda-java-events</artifactId>
	    <version>1.3.0</version>
	</dependency>	  	
	  	
	<dependency>
		<groupId>com.amazonaws</groupId>
		<artifactId>aws-java-sdk-bom</artifactId>
		<version>1.11.1000</version>
		<type>pom</type>
		<scope>import</scope>
	</dependency>

3)Now use following code to get DynamoDB all items with partition key
DynamoDB get all items with partition key java

import java.util.HashMap;
import java.util.Map;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ScanRequest;
import com.amazonaws.services.dynamodbv2.model.ScanResult;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

public class ViewItemWithPartitionKey implements RequestHandler<Object, Object> {
	
	private String DYNAMODB_TABLE_NAME="Test";

	 @Override
	public Object handleRequest(Object input, Context context) {
		 
		 String result = "";
		AmazonDynamoDBClientBuilder builder = AmazonDynamoDBClientBuilder.standard();
		
		Map<String, AttributeValue> expressionAttributeValues = new HashMap<String, AttributeValue>();
		expressionAttributeValues.put("firstName", new AttributeValue("John"));
		
		ScanRequest scanRequest = new ScanRequest()
				.withTableName(DYNAMODB_TABLE_NAME)
				.withFilterExpression("firstName = :firstName")
				.withExpressionAttributeValues(expressionAttributeValues);
		
		ScanResult scanResult = builder.build().scan(scanRequest);
		if(scanResult.getCount()>0) {
			result ="Record found"; 
		}else {
			result ="Record not found";
		}
		 
		 return result;
	}
}

You may also like...