2017-04-06 132 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();