如何基于分区键和排序键[Java]查询DynamoDB?

时间:2017-04-06 13:45:13

标签: 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)

我获取product = 10所有项目的查询是

Items it = new Items();
it.setProduct("apple");

DynamoDBQueryExpression<Items> queryExpression = new DynamoDBQueryExpression<Items>()
            .withHashKeyValues(it);


List<Items> itemList = mapper.query(Items.class, queryExpression);

但是,现在我想让所有项目都有Product = "apple"ID = 100

我可以在Java中为DynamoDB撰写查询。

4 个答案:

答案 0 :(得分:5)

为了使用分区键和排序键从DynamoDB获取数据。您可以使用load类中的DynamoDBMapper方法。

DynamoDBMapper mapper = new DynamoDBMapper(dynamoDBClient);
String product = "ball";
Integer id = 1;
Item itemObj = mapper.load(Items.class, product, id);

模型类,即您的案例类: -

您应该使用Hash和Range键的正确注释定义Item类。

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

答案 1 :(得分:2)

我想添加一种更低级的方式(不使用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();

答案 2 :(得分:0)

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

答案 3 :(得分:0)

给出此DynamoDB表:

enter image description here

该表具有以下详细信息:

  • 分区键-艺术家
  • 排序键-SongTitle

提供此类:

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



}

此代码有效:

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

    }
}
相关问题