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...

Try a Query Using the AWS SDK for Java

The following Java code example uses the AWS SDK for Java to perform the following tasks:

  • Get an item from the ProductCatalog table.

  • Query the Reply table to find all replies posted in the last 15 days for a forum thread. In the code, you first describe your request by creating a QueryRequest object. The request specifies the table name, the primary key hash attribute value, a condition on the range attribute (ReplyDateTime) to retrieve replies posted after a specific date, and other optional parameters. The example uses pagination to retrieve one page of query results at a time. It sets the page size as part of the request.

For step-by-step instructions on configuring your AWS access keys, setting the default endpoint and running the sample, see Running Java Examples for DynamoDB.

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ComparisonOperator;
import com.amazonaws.services.dynamodbv2.model.Condition;
import com.amazonaws.services.dynamodbv2.model.GetItemRequest;
import com.amazonaws.services.dynamodbv2.model.GetItemResult;
import com.amazonaws.services.dynamodbv2.model.QueryRequest;
import com.amazonaws.services.dynamodbv2.model.QueryResult;

public class AmazonDynamoDBSampleData_TryQuery {

    static AmazonDynamoDBClient client;

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

        createClient();
        // Get an item.
        getBook("101", "ProductCatalog");
        
        // Query replies posted in the past 15 days for a forum thread.
        findRepliesInLast15DaysWithConfig("Reply", forumName, threadSubject);
        }  
        catch (AmazonServiceException ase) {
            System.err.println(ase.getMessage());
        }  
    }

    private static void createClient() throws IOException {
        
        AWSCredentials credentials = new PropertiesCredentials(
                AmazonDynamoDBSampleData_TryQuery.class.getResourceAsStream("AwsCredentials.properties"));

        client = new AmazonDynamoDBClient(credentials);
    }
    
    private static void getBook(String id, String tableName) {
        Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
        key.put("Id", new AttributeValue().withN(id));
        
        GetItemRequest getItemRequest = new GetItemRequest()
            .withTableName(tableName)
            .withKey(key)
            .withAttributesToGet(Arrays.asList("Id", "ISBN", "Title", "Authors"));
        
        GetItemResult result = client.getItem(getItemRequest);

        // Check the response.
        System.out.println("Printing item after retrieving it....");
        printItem(result.getItem());            
    }

    private static void findRepliesInLast15DaysWithConfig(String tableName, String forumName, String threadSubject) {

        String replyId = forumName + "#" + threadSubject;
        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);
        
        Map<String, AttributeValue> lastEvaluatedKey = null;
        do {
            
            Condition hashKeyCondition = new Condition()
                .withComparisonOperator(ComparisonOperator.EQ.toString())
                .withAttributeValueList(new AttributeValue().withS(replyId));
            
            Condition rangeKeyCondition = new Condition()
                .withComparisonOperator(ComparisonOperator.GT.toString())
                .withAttributeValueList(new AttributeValue().withS(twoWeeksAgoStr));
            
            Map<String, Condition> keyConditions = new HashMap<String, Condition>();
            keyConditions.put("Id", hashKeyCondition);
            keyConditions.put("ReplyDateTime", rangeKeyCondition);
            
            QueryRequest queryRequest = new QueryRequest().withTableName(tableName)
                .withKeyConditions(keyConditions)
                .withAttributesToGet(Arrays.asList("Message", "ReplyDateTime", "PostedBy"))
                .withLimit(1).withExclusiveStartKey(lastEvaluatedKey);   
            
           QueryResult result = client.query(queryRequest);
            for (Map<String, AttributeValue> item : result.getItems()) {
                printItem(item);
            }
            lastEvaluatedKey = result.getLastEvaluatedKey();
        } while (lastEvaluatedKey != null);        
    }
  
    private static void printItem(Map<String, AttributeValue> attributeList) {
        for (Map.Entry<String, AttributeValue> item : attributeList.entrySet()) {
            String attributeName = item.getKey();
            AttributeValue value = item.getValue();
            System.out.println(attributeName + " "
                    + (value.getS() == null ? "" : "S=[" + value.getS() + "]")
                    + (value.getN() == null ? "" : "N=[" + value.getN() + "]")
                    + (value.getB() == null ? "" : "B=[" + value.getB() + "]")
                    + (value.getSS() == null ? "" : "SS=[" + value.getSS() + "]")
                    + (value.getNS() == null ? "" : "NS=[" + value.getNS() + "]")
                    + (value.getBS() == null ? "" : "BS=[" + value.getBS() + "] \n"));
        }
    }
}