Joh*_*ine 2 java amazon-dynamodb
我是DynamoDB的新手,想知道我们如何使用hashKey和sortKey在DynamoDB中的表上进行查询。
我有一个名为的表Items。它的模式是
1. Product (Partition Key of type String)
2. ID (Sort Key of type int)
3. Date ( attribute of type String)
Run Code Online (Sandbox Code Playgroud)
我为获得其所有项目的查询product = 10IS
Items it = new Items();
it.setProduct("apple");
DynamoDBQueryExpression<Items> queryExpression = new DynamoDBQueryExpression<Items>()
.withHashKeyValues(it);
List<Items> itemList = mapper.query(Items.class, queryExpression);
Run Code Online (Sandbox Code Playgroud)
但是,现在我想让所有项目都具有Product = "apple"和ID = 100。
我我可以写在查询Java了DynamoDB。
为了使用分区键和排序键从DynamoDB获取数据。您可以使用类上load存在的方法DynamoDBMapper。
DynamoDBMapper mapper = new DynamoDBMapper(dynamoDBClient);
String product = "ball";
Integer id = 1;
Item itemObj = mapper.load(Items.class, product, id);
Run Code Online (Sandbox Code Playgroud)
模型类,即您的项目类:-
您应该为Item类定义适当的Hash和Range键注释。
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
我想添加一种更底层的方式(不使用Mapper和注释):
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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7953 次 |
| 最近记录: |