VOOZH about

URL: https://www.javacodegeeks.com/2016/07/__trashed-4.html

โ‡ฑ Query DynamoDB Items with Java - Java Code Geeks


On a previous post we proceeded on inserting data on a DynamoDB database.

On this tutorial we will issue some basic queries against our DynamoDB tables. The main rule is that every query has to use the hash key.

The simplest form of query is using the hash key only. We will query the Users table on this one. There would be only one result, therefore there is no use on iterating the Items list.

public Map<String,AttributeValue> getUser(String email) {

 Map<String,String> expressionAttributesNames = new HashMap<>();
 expressionAttributesNames.put("#email","email");

 Map<String,AttributeValue> expressionAttributeValues = new HashMap<>();
 expressionAttributeValues.put(":emailValue",new AttributeValue().withS(email));

 QueryRequest queryRequest = new QueryRequest()
 .withTableName(TABLE_NAME)
 .withKeyConditionExpression("#email = :emailValue")
 .withExpressionAttributeNames(expressionAttributesNames)
 .withExpressionAttributeValues(expressionAttributeValues);

 QueryResult queryResult = amazonDynamoDB.query(queryRequest);

 List<Map<String,AttributeValue>> attributeValues = queryResult.getItems();

 if(attributeValues.size()>0) {
 return attributeValues.get(0);
 } else {
 return null;
 }
 }

However we can issue more complex queries using conditions.
Logins Table suits well for an example. We will issue a query that will fetch login attempts between to dates.

public List<Map<String ,AttributeValue>> queryLoginsBetween(String email, Date from, Date to) {

 List<Map<String,AttributeValue>> items = new ArrayList<>();

 Map<String,String> expressionAttributesNames = new HashMap<>();
 expressionAttributesNames.put("#email","email");
 expressionAttributesNames.put("#timestamp","timestamp");

 Map<String,AttributeValue> expressionAttributeValues = new HashMap<>();
 expressionAttributeValues.put(":emailValue",new AttributeValue().withS(email));
 expressionAttributeValues.put(":from",new AttributeValue().withN(Long.toString(from.getTime())));
 expressionAttributeValues.put(":to",new AttributeValue().withN(Long.toString(to.getTime())));

 QueryRequest queryRequest = new QueryRequest()
 .withTableName(TABLE_NAME)
 .withKeyConditionExpression("#email = :emailValue and #timestamp BETWEEN :from AND :to ")
 .withExpressionAttributeNames(expressionAttributesNames)
 .withExpressionAttributeValues(expressionAttributeValues);

 Map<String,AttributeValue> lastKey = null;

 do {

 QueryResult queryResult = amazonDynamoDB.query(queryRequest);
 List<Map<String,AttributeValue>> results = queryResult.getItems();
 items.addAll(results);
 lastKey = queryResult.getLastEvaluatedKey();
 } while (lastKey!=null);

 return items;
 }

Keep in mind that DynamoDB Fetches data in pages, therefore you have to issue the same request more than once in case of multiple pages. Therefore you have to use the last evaluated key to your next request.

Last but not least querying on indexes is one of the basic actions. It is the same routine either for local or global secondary indexes.
Keep in mind that the results fetched depend on the projection type we specified once creating the Table. In our case the projection type is for all fields.

We shall use the Supervisors table.

public Map<String ,AttributeValue> getSupervisor(String company,String factory) {

 List<Map<String,AttributeValue>> items = new ArrayList<>();

 Map<String,String> expressionAttributesNames = new HashMap<>();
 expressionAttributesNames.put("#company","company");
 expressionAttributesNames.put("#factory","factory");

 Map<String,AttributeValue> expressionAttributeValues = new HashMap<>();
 expressionAttributeValues.put(":company",new AttributeValue().withS(company));
 expressionAttributeValues.put(":factory",new AttributeValue().withS(factory));

 QueryRequest queryRequest = new QueryRequest()
 .withTableName(TABLE_NAME)
 .withKeyConditionExpression("#company = :company and #factory = :factory ")
 .withIndexName("FactoryIndex")
 .withExpressionAttributeNames(expressionAttributesNames)
 .withExpressionAttributeValues(expressionAttributeValues);

 QueryResult queryResult = amazonDynamoDB.query(queryRequest);

 List<Map<String,AttributeValue>> attributeValues = queryResult.getItems();

 if(attributeValues.size()>0) {
 return attributeValues.get(0);
 } else {
 return null;
 }
 }

You can find full source code with unit tests on github.

Reference: Query DynamoDB Items with Java from our JCG partner Emmanouil Gkatziouras at the gkatzioura blog.
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

๐Ÿ‘ Photo of Emmanouil Gkatziouras
Emmanouil Gkatziouras
July 4th, 2016Last Updated: July 3rd, 2016
2 117 2 minutes read

Emmanouil Gkatziouras

He is a versatile software engineer with experience in a wide variety of applications/services.He is enthusiastic about new projects, embracing new technologies, and getting to know people in the field of software.
Subscribe

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
lihy70
9 years ago

The query can be simplified by AbacusUtil: http://www.landawn.com/dynamodb-executor.html

Account account = createAccount2();
dbExecutor.putItem(โ€œaccountโ€, account);

Account dbAccount = dbExecutor.getItem(Account.class, โ€œaccountโ€, DynamoDBExecutor.asKey(โ€œidโ€, account.getId()));

final QueryRequest queryRequest = new QueryRequest(โ€œaccountโ€).withKeyConditions(Filters.eq(โ€œidโ€, โ€œabc123โ€));
List accounts = dbExecutor.query(Account.class, queryRequest);

0
Reply
Reply to  lihy70

This seems to be a wonderful tool, thank you for mentioning! Most probably I will include it in one of my upcoming posts.

0
Reply
Back to top button
Close
wpDiscuz