Amazon DynamoDB
Developer Guide (API Version 2012-08-10)
Did this page help you?  Yes | No |  Tell us about it...
« 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.

Querying Tables Using the AWS SDK for Java Document API

The query function enables you to query a table or a secondary index. You must provide a hash key value and an equality condition. If the table or index has a range key, you can refine the results by providing a range key value and a condition.

Note

This section explains the AWS SDK for Java Document API. The AWS SDK for Java also provides a high-level object persistence model, enabling you to map your client-side classes to DynamoDB tables. This approach can reduce the amount of code you have to write. For more information, see Java: Object Persistence Model.

The following are the steps to retrieve an item using the AWS SDK for Java Document API.

  1. Create an instance of the DynamoDB class.

  2. Create an instance of the Table class to represent the table you want to work with.

  3. Call the query method of the Table instance. You must specify the hash key of the item(s) that you want to retrieve, along with any optional query parameters.

The response includes an ItemCollection object that provides all items returned by the query.

The following Java code snippet demonstrates the preceding tasks. The snippet assumes you have a Reply table that stores replies for forum threads. For more information, see Example Tables and Data.

Reply ( Id, ReplyDateTime, ... )

Each forum thread has a unique ID and can have zero or more replies. Therefore, the Id attribute of the Reply table is composed of both the forum name and forum subject. The Id and the ReplyDateTime make up the composite hash-and-range primary key for the table.

The following query retrieves all replies for a specific thread subject. The query requires both the table name and the Subject value.

DynamoDB dynamoDB = new DynamoDB(
    new AmazonDynamoDBClient(new ProfileCredentialsProvider()));

Table table = dynamoDB.getTable("Reply");

ItemCollection<QueryOutcome> items = table.query("Id", "Amazon DynamoDB#DynamoDB Thread 1");

Iterator<Item> iterator = items.iterator();
Item item = null;
while (iterator.hasNext()) {
    item = iterator.next();
    System.out.println(item.toJSONPretty());
}

Specifying Optional Parameters

The query method supports several optional parameters. For example, you can optionally narrow the results from the preceding query to return replies in the past two weeks by specifying a condition. The condition is called a range condition because DynamoDB evaluates the query condition that you specify against the range attribute of the primary key. You can specify other optional parameters to retrieve only a specific list of attributes from items in the query result.

The following Java code snippet retrieves forum thread replies posted in the past 15 days. The snippet specifies optional parameters using:

  • A range key condition to retrieve only the replies in the past 15 days. The condition specifies a ReplyDateTime value and a comparison operator to use for comparing dates.

  • The query filter condition specifies that only replies by a specific user are returned.

  • The withProjectionExpression method to specify the attributes to retrieve for items in the query results.

  • The withConsistentRead method as true to request a strongly consistent read. To learn more about read consistency, see DynamoDB Data Model.

This snippet uses a QuerySpec object which gives access to all of the low-level Query input parameters.

Table table = dynamoDB.getTable("Reply");

long twoWeeksAgoMilli = (new Date()).getTime() - (15L*24L*60L*60L*1000L);
Date twoWeeksAgo = new Date();
twoWeeksAgo.setTime(twoWeeksAgoMilli);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String twoWeeksAgoStr = df.format(twoWeeksAgo);

RangeKeyCondition rangeKeyCondition = new RangeKeyCondition("ReplyDateTime").gt(twoWeeksAgoStr);

Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":val", "User B");

QuerySpec spec = new QuerySpec()
    .withHashKey("Id", "Amazon DynamoDB#DynamoDB Thread 1")
    .withRangeKeyCondition(rangeKeyCondition)
    .withFilterExpression("PostedBy = :val")
    .withValueMap(expressionAttributeValues)
    .withConsistentRead(true) ;

Iterator<Item> iterator = items.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next().toJSONPretty());
}

You can also optionally limit the number of items per page by using the withMaxPageSize method. When time you call the query method, you get an ItemCollection that contains the resulting items. You can then step through the results, processing one page at a time, until there are no more pages.

The following Java code snippet queries the Reply table. In the request, the withMaxPageSize method is used. The Page class provides an Iterator that allows the code to process the items on each page.

Table table = dynamoDB.getTable("Reply");

ItemCollection<QueryOutcome> items = table.query("Id", "Amazon DynamoDB#DynamoDB Thread 1")
    .withMaxPageSize(10); // 10 items per page

// Process each page of results
int pageNum = 0;
for (Page<Item, QueryOutcome> page : items.pages()) {
        	
    System.out.println("\nPage: " + ++pageNum);

    // Process each item on the current page
    Iterator<Item> item = page.iterator();
    while (item.hasNext()) {
        System.out.println(item.next().toJSONPretty());
    }
}

Example - Query Using Java

The following tables store information about a collection of forums. For more information about table schemas, see Example Tables and Data.

Note

This section explains the AWS SDK for Java Document API. The AWS SDK for Java also provides a high-level object persistence model, enabling you to map your client-side classes to DynamoDB tables. This approach can reduce the amount of code you have to write. For more information, see Java: Object Persistence Model.

For a code example that demonstrates query operations using the object persistence model, see Example: Query and Scan.

Forum ( Name, ... ) 
Thread ( ForumName, Subject, Message, LastPostedBy, LastPostDateTime, ...) 
Reply ( Id, ReplyDateTime, Message, PostedBy, ...)

In this Java code example, you execute variations of finding replies for a thread 'DynamoDB Thread 1' in forum 'DynamoDB'.

  • Find replies for a thread.

  • Find replies for a thread, specifying a limit on the number of items per page of results. If the number of items in the result set exceeds the page size, you get only the first page of results. This coding pattern ensures your code processes all the pages in the query result.

  • Find replies in the last 15 days.

  • Find replies in a specific date range.

    Both the preceding two queries shows how you can specify range key conditions to narrow the query results and use other optional query parameters.

Note

This code example assumes that you have already loaded data into DynamoDB for your account by following the instructions in the Getting Started section. Alternatively, you can load the data programmatically using the instructions in the Creating Example Tables and Uploading Data Using the AWS SDK for Java topic.

For step-by-step instructions to run the following example, see Running Java Examples for DynamoDB.

package com.amazonaws.codesamples;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.ItemCollection;
import com.amazonaws.services.dynamodbv2.document.Page;
import com.amazonaws.services.dynamodbv2.document.QueryOutcome;
import com.amazonaws.services.dynamodbv2.document.RangeKeyCondition;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec;

public class DocumentAPIQuery {

	static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(new ProfileCredentialsProvider()));

    static String tableName = "Reply";

    public static void main(String[] args) throws Exception {
    	
        String forumName = "Amazon DynamoDB";
        String threadSubject = "DynamoDB Thread 1";

        findRepliesForAThread(forumName, threadSubject);
        findRepliesForAThreadSpecifyOptionalLimit(forumName, threadSubject);
        findRepliesInLast15DaysWithConfig(forumName, threadSubject);
        findRepliesPostedWithinTimePeriod(forumName, threadSubject);
        findRepliesUsingAFilterExpression(forumName, threadSubject);
    }
    
    private static void findRepliesForAThread(String forumName, String threadSubject) {
    	
		Table table = dynamoDB.getTable(tableName);

        String replyId = forumName + "#" + threadSubject;
        
        ItemCollection<QueryOutcome> items = table.query("Id", replyId);
        
        System.out.println("\nfindRepliesForAThread results:");

    	Iterator<Item> iterator = items.iterator();
    	while (iterator.hasNext()) {
    		System.out.println(iterator.next().toJSONPretty());
    	}
        
    }

    private static void findRepliesForAThreadSpecifyOptionalLimit(String forumName, String threadSubject) {
        
		Table table = dynamoDB.getTable(tableName);
		
		String replyId = forumName + "#" + threadSubject;        
		QuerySpec spec = new QuerySpec().withHashKey("Id", replyId).withMaxPageSize(1);

        ItemCollection<QueryOutcome> items = table.query(spec);
        
        System.out.println("\nfindRepliesForAThreadSpecifyOptionalLimit results:");

        // Process each page of results
        int pageNum = 0;
        for (Page<Item, QueryOutcome> page : items.pages()) {
        	
        	System.out.println("\nPage: " + ++pageNum);

        	// Process each item on the current page
        	Iterator<Item> item = page.iterator();
        	while (item.hasNext()) {
        		System.out.println(item.next().toJSONPretty());
        	}
        }
    }
    
    private static void findRepliesInLast15DaysWithConfig(String forumName, String threadSubject) {

		Table table = dynamoDB.getTable(tableName);

        long twoWeeksAgoMilli = (new Date()).getTime() - (15L*24L*60L*60L*1000L);
        Date twoWeeksAgo = new Date();
        twoWeeksAgo.setTime(twoWeeksAgoMilli);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        String twoWeeksAgoStr = df.format(twoWeeksAgo);
        
        String replyId = forumName + "#" + threadSubject;

   	    RangeKeyCondition rangeKeyCondition = new RangeKeyCondition("ReplyDateTime").le(twoWeeksAgoStr);

        ItemCollection<QueryOutcome> items = table.query("Id", replyId,
            rangeKeyCondition,
            null, //FilterExpression - not used in this example
            "Message, ReplyDateTime, PostedBy", //ProjectionExpression
            null, //ExpressionAttributeNames - not used in this example
            null); //ExpressionAttributeValues - not used in this example

        System.out.println("\nfindRepliesInLast15DaysWithConfig results:");
    	Iterator<Item> iterator = items.iterator();
    	while (iterator.hasNext()) {
    		System.out.println(iterator.next().toJSONPretty());
    	}

    }
    
    private static void findRepliesPostedWithinTimePeriod(String forumName, String threadSubject) {
        
		Table table = dynamoDB.getTable(tableName);

        long startDateMilli = (new Date()).getTime() - (15L*24L*60L*60L*1000L); 
        long endDateMilli = (new Date()).getTime() - (5L*24L*60L*60L*1000L);    
        java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        String startDate = df.format(startDateMilli);
        String endDate = df.format(endDateMilli);

        String replyId = forumName + "#" + threadSubject;

   	    RangeKeyCondition rangeKeyCondition = new RangeKeyCondition("ReplyDateTime").between(startDate, endDate);

        ItemCollection<QueryOutcome> items = table.query("Id", replyId,
                rangeKeyCondition,
                null, //FilterExpression - not used in this example
                "Message, ReplyDateTime, PostedBy",  //ProjectionExpression
                null, //ExpressionAttributeNames - not used in this example
                null); //ExpressionAttributeValues - not used in this example

        System.out.println("\nfindRepliesPostedWithinTimePeriod results:");
    	Iterator<Item> iterator = items.iterator();
    	while (iterator.hasNext()) {
    		System.out.println(iterator.next().toJSONPretty());
    	}    
    }


    private static void findRepliesUsingAFilterExpression(String forumName, String threadSubject) {
              
		Table table = dynamoDB.getTable(tableName);
		
        String replyId = forumName + "#" + threadSubject;
                
        Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
        expressionAttributeValues.put(":val", "User B");
        
        ItemCollection<QueryOutcome> items = table.query("Id", replyId,
                null, ///RangeKeyCondition - not used in this example
                "PostedBy = :val", //FilterExpression
                "Message, ReplyDateTime, PostedBy", //ProjectionExpression
                null, //ExpressionAttributeNames - not used in this example
                expressionAttributeValues);

        System.out.println("\nfindRepliesUsingAFilterExpression results:");
    	Iterator<Item> iterator = items.iterator();
    	while (iterator.hasNext()) {
    		System.out.println(iterator.next().toJSONPretty());
    	}    
     }
    
}