John Constantine
John Constantine

Reputation: 1092

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 .

Upvotes: 5

Views: 31758

Answers (4)

smac2020
smac2020

Reputation: 10704

Given this DynamoDB table:

enter image description here

The table has the following details:

  • Partition key — Artist
  • Sort key — SongTitle

Given this class:

@DynamoDBTable(tableName="Music")
public class MusicItems {

    //Set up Data Members that correspond to items in the Music Table
    private String artist;
    private String songTitle;
    private String albumTitle;
    private int awards;

    @DynamoDBHashKey(attributeName="Artist")
    public String getArtist() { return this.artist; }
    public void setArtist(String artist) {this.artist = artist; }

    @DynamoDBRangeKey(attributeName="SongTitle")
    public String getSongTitle() { return this.songTitle; }
    public void setSongTitle(String title) {this.songTitle = title; }

    @DynamoDBAttribute(attributeName="AlbumTitle")
    public String getAlbumTitle() { return this.albumTitle; }
    public void setAlbumTitle(String title) {this.albumTitle = title; }

    @DynamoDBAttribute(attributeName="Awards")
    public int getAwards() { return this.awards; }
    public void setAwards(int awards) {this.awards = awards; }



}

This code works:

    import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
    import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
    import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute;
    import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
    import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
    import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
    import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;

    public class UseDynamoMapping {

    public static void main(String[] args)
    {

       AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
       MusicItems items = new MusicItems();

       try{

          //add new content to the Music Table
           items.setArtist("Famous Band");
           items.setSongTitle("Our Famous Song");
           items.setAlbumTitle("Our First Album");
           items.setAwards(0);

           // Save the item
           DynamoDBMapper mapper = new DynamoDBMapper(client);
           mapper.save(items);

            //Load an item based on the Partition Key and Sort Key
           //both values need to be passed to the mapper.load method
           String artist = "Famous Band";
           String songQueryTitle = "Our Famous Song";

           // Retrieve the item.
           MusicItems itemRetrieved = mapper.load(MusicItems.class, artist, songQueryTitle);
           System.out.println("Item retrieved:");
           System.out.println(itemRetrieved);

            //Modify the Award value
           itemRetrieved.setAwards(2);
           mapper.save(itemRetrieved);
           System.out.println("Item updated:");
           System.out.println(itemRetrieved);


            System.out.print("Done");
       }
       catch (Exception e)
       {
           e.getStackTrace();
       }

    }
}

URL to example - https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/UseDynamoMapping.java

Upvotes: 2

Vikky
Vikky

Reputation: 1223

GetItemRequest getItemRequest = new GetItemRequest().withTableName("Employee").
            addKeyEntry("departmentId", new AttributeValue().withS(String.valueOf(departmentId))).
            addKeyEntry("employeeId", new AttributeValue().withN(String.valueOf(employeeId)));

    Map<String, AttributeValue> responseItem = dynamoDbClient.getItem(getItemRequest).getItem();

Upvotes: 1

Marcelo Glasberg
Marcelo Glasberg

Reputation: 30879

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();

Upvotes: 6

notionquest
notionquest

Reputation: 39176

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;
    }           
}   

Upvotes: 9

Related Questions