【问题标题】:How to query DynamoDB based on Partition Key and Sort Key [Java]?如何根据 Partition Key 和 Sort Key [Java] 查询 DynamoDB?
【发布时间】:2020-08-25 22:57:03
【问题描述】:

我是 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 编写查询。

【问题讨论】:

    标签: java amazon-dynamodb


    【解决方案1】:

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

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

    模型类,即在您的情况下为项目类:-

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

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

    【讨论】:

    • 我收到一条错误消息,表; RANGE 键没有映射
    • ID 是排序键而不是范围键。
    • 用模型类更新了答案。同样,您也可以定义非键属性。但是要使负载正常工作,不需要非关键属性。排序键也称为范围键
    • 如果我想在一个非常大的数据库上运行它,它的加载速度与查询一样快。
    • 没有表现。唯一的区别是您不能按非关键属性进行过滤。 Query API 可以在过滤条件中包含非关键属性以及关键属性。
    【解决方案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();
    

    【讨论】:

      【解决方案3】:

      鉴于此 DynamoDB 表:

      该表有以下详细信息:

      • 分区键 - 艺术家
      • 排序键 - 歌曲标题

      鉴于这个类:

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

      示例网址 - https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/UseDynamoMapping.java

      【讨论】:

        【解决方案4】:
        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();
        

        【讨论】:

          猜你喜欢
          • 2022-11-17
          • 1970-01-01
          • 2023-02-24
          • 2018-05-18
          • 1970-01-01
          • 2014-09-01
          • 1970-01-01
          • 2019-06-30
          • 2015-11-11
          相关资源
          最近更新 更多