How to do Query in DynamoDB on the basis of HashKey and range Key?

后端 未结 3 2193
盖世英雄少女心
盖世英雄少女心 2021-02-19 11:08

I am new to DynamoDb stuff. I just want to know how can we query on a table in DynamoDB with the hashKey and rangeKey.

Let\'s say

相关标签:
3条回答
  • 2021-02-19 11:33

    You could use dynamoDbMapper.load() as following:

    TestTable testTable = new TestTable();
    testTable.setId("123");
    testTable.setDate("1234");
    TestTable result = dynamoDBMapper.load(testTable);
    
    0 讨论(0)
  • 2021-02-19 11:39

    If you're not using index, you should have exact one item, if any, whose Id ="123" and Date ="1234".

    For the exact hash key and range key (in case of = operator), you don't need a query operation. Please have a loot at GetItem API, which is nifty. See documentation page.

    And if you need non-EQ operator for range key (e.g. >=), you can use key condition expression in Query operation: Id = :id and Date >= :date.

    0 讨论(0)
  • 2021-02-19 11:47

    I wrote an article about DynamoDB queries and indexing using the AWS Java SDK some time ago: http://labs.journwe.com/2013/12/15/dynamodb-secondary-indexes/

    In your case, it should work like this (see http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/JavaQueryScanORMModelExample.html):

    AmazonDynamoDBClient client = new AmazonDynamoDBClient(new ProfileCredentialsProvider());
    DynamoDBMapper mapper = new DynamoDBMapper(client);
    
    String hashKey = "123";
    long twoWeeksAgoMilli = (new Date()).getTime() - (15L*24L*60L*60L*1000L);
    Date twoWeeksAgo = new Date();
    twoWeeksAgo.setTime(twoWeeksAgoMilli);
    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    String twoWeeksAgoStr = dateFormatter.format(twoWeeksAgo);            
    Condition rangeKeyCondition = new Condition()
            .withComparisonOperator(ComparisonOperator.GT.toString())
            .withAttributeValueList(new AttributeValue().withS(twoWeeksAgoStr.toString()));
    
    Reply replyKey = new Reply();
    replyKey.setId(hashKey);
    
    DynamoDBQueryExpression<Reply> queryExpression = new DynamoDBQueryExpression<Reply>()
            .withHashKeyValues(replyKey)
            .withRangeKeyCondition("ReplyDateTime", rangeKeyCondition);
    
    List<Reply> latestReplies = mapper.query(Reply.class, queryExpression);
    

    Check out the Java Object Persistence Model section of the DynamoDB docs for more info.

    0 讨论(0)
提交回复
热议问题