user93796
user93796

Reputation: 18389

dynamo db query

I have my dynamo db table as follows:

HashKey(xyz) ,RangeKey(timestamp)

Now for each hash key i have set of range key.

Now i want to query based on set of hashkey and i want only most recent value correspoding to that to be fetched .I dont want to do in memory sorting and then picking most recent version.

Can i do this in any way?

Use case is that i will do a bulkget and pass set of hashkey (say 100) , so i want to get one record for each hashkey

Upvotes: 0

Views: 3109

Answers (2)

ABHAY JOHRI
ABHAY JOHRI

Reputation: 2156

Use ScanIndexForward(true for ascending and false for descending) and can also limit the result using setLimit value of Query Expression.

Please find below the code where used QueryPage for finding the single record.

public EventLogEntitySave fetchLatestEvents(String id) {
    EventLogEntitySave entity = new EventLogEntitySave();
    entity.setId(id);

    DynamoDBQueryExpression<EventLogEntitySave> queryExpression = new DynamoDBQueryExpression<EventLogEntitySave>().withHashKeyValues(entity);
    queryExpression.setScanIndexForward(false);
    queryExpression.withLimit(1);
    queryExpression.setLimit(1);

    List<EventLogEntitySave> result = dynamoDBMapper.queryPage(EventLogEntitySave.class, queryExpression).getResults();
    System.out.println("size of records = "+result.size() );
    result.get(0);
}

@DynamoDBTable(tableName = "PROD_EA_Test")
public class EventLogEntitySave {

        @DynamoDBHashKey
        private String id;
        private String reconciliationProcessId;
        private String vin;
        private String source;
}

public class DynamoDBConfig {
    @Bean
    public AmazonDynamoDB amazonDynamoDB() {

            String accesskey = "";
            String secretkey = "";
            //
            // creating dynamo client
            BasicAWSCredentials credentials = new BasicAWSCredentials(accesskey, secretkey);
            AmazonDynamoDB dynamo = new AmazonDynamoDBClient(credentials);
            dynamo.setRegion(Region.getRegion(Regions.US_WEST_2));
            return dynamo;
        }

Upvotes: 0

DanneJ
DanneJ

Reputation: 368

You (currently) can't set constraints on a batch get. See http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/API_BatchGetItems.html

However, for single hash keys, you can set the direction using ScanIndexForward. See http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/API_Query.html for information.

Sample java code:

new QueryRequest().withTableName("table-name")
  .withScanIndexForward(false)
  .withLimit(1)
  .withHashKeyValue(new AttributeValue().withS("hash-key"));

It will not be very efficient though, as you will need to make this call 100 times.

Upvotes: 0

Related Questions