2017-04-18 86 views
1

我是DynamoDB的新手,想知道如何使用Java在IN子句中查詢DynamoDB中的表。使用IN子句查詢DynamoDB

我有一個名爲items.它`架構表是

1. Product (Partition Key of type String) 
2. ID (Sort Key of type int) 
3. Date (attribute of type String) 

我要查詢類似

SELECT ID FROM items WHERE Product IN ("apple","orange"). 

SELECT Product FROM items WHERE ID IN (100,200). 
+0

認真!?首先谷歌命中=> http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SQLtoNoSQL.ReadData.Query.html – Zorglube

+0

這是在JavaScript中,我需要它在Java –

+0

你真的認爲一個SQL查詢是跟你用來發送它的語言不同?也許你構建查詢的方式可能會改變,但SQL會保留SQL。如果您熟悉標準,這將有助於=> http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryingJavaDocumentAPI.html如果您不瞭解標準,我建議您閱讀它。 – Zorglube

回答

1

由於要求得到沒有分區鍵的產品,有兩個選項可用。

1)排序鍵屬性創建GSI(全球第二索引)Id使用查詢API

2)掃描整個表到拿到產品 - 不是非常有效,因爲它會掃描整個表

這兩個選項均使用DynamoDB上提供的IN運算符。用於掃描使用ID

示例代碼: -

Map<String, AttributeValue> attributeValues = new HashMap<>(); 
attributeValues.put(":id1", new AttributeValue().withN("100")); 
attributeValues.put(":id2", new AttributeValue().withN("200")); 

DynamoDBScanExpression dynamoDBScanExpression = new DynamoDBScanExpression() 
                .withFilterExpression("ID IN (:id1, :id2)") 
                .withExpressionAttributeValues(attributeValues); 


PaginatedScanList<yourModelClass> scanList = dynamoDBMapper.scan(yourModelClass.class, dynamoDBScanExpression, 
     new DynamoDBMapperConfig(DynamoDBMapperConfig.ConsistentReads.CONSISTENT)); 

Iterator<yourModelClass> iterator = scanList.iterator(); 

while (iterator.hasNext()) { 
    System.out.println(iterator.next().getTitle()); 
} 

查詢由產物: -

1)無法使用IN操作爲分區鍵

2)不能在不知道排序鍵的情況下使用batchLoad API

結論: -

高效的解決方案是在屬性Id創建GSI(不排序鍵),然後使用batchLoad API。

注: GSI的分區鍵不必是唯一的