I am new to DynamoDB and wanted to know how can we query on a table in DynamoDB with the hashKey and sortKey.
I have a table named Items
. It`s schema is
1. Product (Partition Key of type String)
2. ID (Sort Key of type int)
3. Date ( attribute of type String)
My query for getting all items having product = 10
is
Items it = new Items();
it.setProduct("apple");
DynamoDBQueryExpression<Items> queryExpression = new DynamoDBQueryExpression<Items>()
.withHashKeyValues(it);
List<Items> itemList = mapper.query(Items.class, queryExpression);
But, now I want to get all items having Product = "apple"
and ID = 100
.
I can I write a query in Java
for DynamoDB
.
In order to get the data from DynamoDB using partition key and sort key. You can use the load
method present on DynamoDBMapper
class.
DynamoDBMapper mapper = new DynamoDBMapper(dynamoDBClient);
String product = "ball";
Integer id = 1;
Item itemObj = mapper.load(Items.class, product, id);
Model class i.e. in your case Item class:-
You should have the Item class defined with proper annotation for Hash and Range key.
@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;
}
}
I would like to add a more low-level way (not using Mapper and annotations):
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With