5

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 .

4 Answers 4

9

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;
    }           
}   
Sign up to request clarification or add additional context in comments.

6 Comments

I get an error saying, table; no mapping for RANGE key
ID is the sort key not range key.
Updated the answer with model class. Similarly, you can define the non-key attributes as well. But for load to work, the non-key attributes are not required. Sort key is otherwise called range key
Is load as fast as query, if I wanted to run this on a very large database.
There is no performance. The only difference is you can't filter by non key attributes. Query API has a facility to include non-key attributes on filter criteria along with key attributes.
|
6

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

Comments

2

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.