2015-06-15 46 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);