2015-06-15 97 views
7

我是DynamoDb东西的新手。我只想知道如何使用hashKeyrangeKey在DynamoDB中的表上查询。如何在基于HashKey和range key的DynamoDB中执行查询?

比方说,我的表是TestTable,它的模式是这样的:

1.Id (HK of type String) 
2 Date (RK of type String) 
3 Name (attribute of type String) 

现在,如果我要对hashKey在此基础上为Id这里在此表中查询,我们做一个query为:

比方说我的查询是让有所有项目Id ="123".

TestTable testTable = new TestTable(); 
testTable.setId("123"); 

DynamoDBQueryExpression<TestTable> queryExpression = new DynamoDBQueryExpression<TestTable>() 
                   .withHashKeyValues(TestTable) 
                   .withConsistentRead(false); 

现在我想要获得所有具有Id ="123" and Date ="1234"的项目。

我如何可以查询DynamoDB

这件事情我使用java作为我的编程语言。

回答

7

我写了一篇关于DynamoDB查询和使用AWS的Java SDK索引前段时间的一篇文章:http://labs.journwe.com/2013/12/15/dynamodb-secondary-indexes/

在你的情况下,它应该像这样(见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); 

查看DynamoDB文档的Java对象持久性模型部分了解更多信息。

+0

嘿..我看了你已经......文章这的确是一个不错的one.Actually我不想让这样的条件用于范围键操作。没有其他方法吗? –

+0

我看到的其他可能性(但尚未尝试过)是使用低级Java查询api:http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryingJavaDocumentAPI.html QuerySpec( ).withKeyConditionExpression(“Id =:v_id and Date =:v_date”)。withValueMap(new ValueMap()。withString(“:v_id”,“123”).withString(“:v_date”,“1234” –

2

如果你不使用索引,你应该有一个确切的项目,如果有的话,其Id ="123"Date ="1234"

对于确切的散列键和范围键(在=运算符的情况下),您不需要查询操作。请在GetItem API处获得一个掠夺者,这很漂亮。请参阅documentation page

如果你需要非均衡运营商范围键(例如>=),你可以在Query操作使用key condition expressionId = :id and Date >= :date

4

你可以使用dynamoDbMapper.load()如下:

TestTable testTable = new TestTable(); 
testTable.setId("123"); 
testTable.setDate("1234"); 
TestTable result = dynamoDBMapper.load(testTable);