Limiting and Ordering the Scan Result AWS

363 views Asked by At

I am using AWS mobilehub and I create a dynamoDb table(userId, username, usertoplevel, usertopscore). My Partition key is a string (userId) and I have created one Global Search Index (GSI) in which i make usertoplevel is Partition key and usertopscore as Sort Key. I can successfully query for all items by the following code

final DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
            List<UserstopcoreDO> results;
            DynamoDBMapper mapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();
            results = mapper.scan(UserstopcoreDO.class, scanExpression);
            for (UserstopcoreDO usertopScore : results) {
                Logger.d("SizeOfUserScore : " + usertopScore.getUsertopscore());
            }

Now I have 1500+ records in the table and I want to limit the result to fetch only the top 10 users. I will be thankful if someone help.

2

There are 2 answers

1
Rahul On BEST ANSWER

In order to achieve this you need to move away from Scan and use Query operation. The query operation provides you an option to specify if the index should be read forwards or in reverse. In order to get the top 10 results, you need to limit the results returned to 10. This can be done by setting a limit on your query operation. Therefore to summarize:

  1. Start using a query operation instead of scan.
  2. Set the scanIndexForward to false to start reading results in descending order.
  3. Set a limit on your query operation to return top 10 results.

This page describes all the things I mentioned in this answer: http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html

1
notionquest On

The limit can be set in the scan expression. Please read the definition of the LIMIT carefully. It is the limit for the maximum number of items to evaluate. However, you don't need worry if there is no filter expression used in scan.

In case, if you use filter expression, you may need to do recursive scan until LastEvaluatedKey is null.

DynamoDBScanExpression scanExpression = new DynamoDBScanExpression().withLimit(10);

The maximum number of items to evaluate (not necessarily the number of matching items). If DynamoDB processes the number of items up to the limit while processing the results, it stops the operation and returns the matching values up to that point, and a key in LastEvaluatedKey to apply in a subsequent operation, so that you can pick up where you left off. Also, if the processed data set size exceeds 1 MB before DynamoDB reaches this limit, it stops the operation and returns the matching values up to the limit, and a key in LastEvaluatedKey to apply in a subsequent operation to continue the operation.