Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query DynamoDB based on Partition Key and Sort Key [Java]?

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 .

like image 419
John Constantine Avatar asked Dec 02 '22 13:12

John Constantine


2 Answers

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;
    }           
}   
like image 88
notionquest Avatar answered Dec 05 '22 03:12

notionquest


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();
like image 42
MarcG Avatar answered Dec 05 '22 01:12

MarcG