2017-04-06 40 views
0

我是DynamoDB的新手,想知道如何使用hashKey和sortKey在DynamoDB的表上查詢。如何根據分區鍵和排序鍵[Java]查詢DynamoDB?

我有一張名爲Items的表格。它`模式是

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

我爲獲得具有product = 10所有項目查詢

Items it = new Items(); 
it.setProduct("apple"); 

DynamoDBQueryExpression<Items> queryExpression = new DynamoDBQueryExpression<Items>() 
      .withHashKeyValues(it); 


List<Items> itemList = mapper.query(Items.class, queryExpression); 

但是,現在我想有Product = "apple"ID = 100所有項目。

我可以在Java中爲DynamoDB寫一個查詢。

回答

2

爲了使用分區鍵和排序鍵從DynamoDB獲取數據。您可以使用DynamoDBMapper類中的load方法。你的情況Item類

DynamoDBMapper mapper = new DynamoDBMapper(dynamoDBClient); 
String product = "ball"; 
Integer id = 1; 
Item itemObj = mapper.load(Items.class, product, id); 

Model類,即: -

您應該對哈希和範圍鍵適當的註釋中定義的項目類。

@DynamoDBTable(tableName = "Items") 
public class Item { 

    private String product; 
    private Integer id; 

    @DynamoDBHashKey(attributeName = "Product") 
    public String getProduct() { 
     return autoID; 
    } 
    @DynamoDBRangeKey(attributeName = "ID") 
    public String getId() { 
     return id; 
    }   
} 
+0

我得到一個錯誤說,表;沒有用於RANGE鍵的映射 –

+0

ID是排序鍵而不是範圍鍵。 –

+0

用模型類更新了答案。同樣,您也可以定義非關鍵屬性。但是爲了加載工作,非關鍵屬性不是必需的。排序鍵被稱爲範圍鍵 – notionquest

0

我想補充一個更低級的方式(不使用映射和註釋):

String accessKey = ...; // Don't hardcode keys in production. 
String secretKey = ...; 

AmazonDynamoDB dynamoDBClient = 
     = AmazonDynamoDBClientBuilder 
      .standard() 
      .withRegion("us-east-1") 
      .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey))) 
      .build(); 

String tableName = ... 
Map.Entry<String, AttributeValue> partitionKey = ... 
Map.Entry<String, AttributeValue> sortKey = ... 

GetItemRequest request = 
    new GetItemRequest().withTableName(tableName) 
         .withKey(partitionKey, sortKey); 

GetItemResult result = dynamoDBClient.getItem(request); 
Map<String, AttributeValue> item = result.getItem();