I am new to DynamoDb
stuff. I just want to know how can we query on a table in DynamoDB with the hashKey
and rangeKey
.
Let\'s say
You could use dynamoDbMapper.load() as following:
TestTable testTable = new TestTable();
testTable.setId("123");
testTable.setDate("1234");
TestTable result = dynamoDBMapper.load(testTable);
If you're not using index, you should have exact one item, if any, whose Id ="123"
and Date ="1234"
.
For the exact hash key and range key (in case of =
operator), you don't need a query operation. Please have a loot at GetItem
API, which is nifty. See documentation page.
And if you need non-EQ operator for range key (e.g. >=
), you can use key condition expression in Query
operation: Id = :id and Date >= :date
.
I wrote an article about DynamoDB queries and indexing using the AWS Java SDK some time ago: http://labs.journwe.com/2013/12/15/dynamodb-secondary-indexes/
In your case, it should work like this (see http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/JavaQueryScanORMModelExample.html):
AmazonDynamoDBClient client = new AmazonDynamoDBClient(new ProfileCredentialsProvider());
DynamoDBMapper mapper = new DynamoDBMapper(client);
String hashKey = "123";
long twoWeeksAgoMilli = (new Date()).getTime() - (15L*24L*60L*60L*1000L);
Date twoWeeksAgo = new Date();
twoWeeksAgo.setTime(twoWeeksAgoMilli);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String twoWeeksAgoStr = dateFormatter.format(twoWeeksAgo);
Condition rangeKeyCondition = new Condition()
.withComparisonOperator(ComparisonOperator.GT.toString())
.withAttributeValueList(new AttributeValue().withS(twoWeeksAgoStr.toString()));
Reply replyKey = new Reply();
replyKey.setId(hashKey);
DynamoDBQueryExpression<Reply> queryExpression = new DynamoDBQueryExpression<Reply>()
.withHashKeyValues(replyKey)
.withRangeKeyCondition("ReplyDateTime", rangeKeyCondition);
List<Reply> latestReplies = mapper.query(Reply.class, queryExpression);
Check out the Java Object Persistence Model section of the DynamoDB docs for more info.