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

后端 未结 3 2214
盖世英雄少女心
盖世英雄少女心 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: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 queryExpression = new DynamoDBQueryExpression()
            .withHashKeyValues(replyKey)
            .withRangeKeyCondition("ReplyDateTime", rangeKeyCondition);
    
    List latestReplies = mapper.query(Reply.class, queryExpression);
    

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

提交回复
热议问题