Search code examples
amazon-web-servicesamazon-dynamodbaws-mobilehub

Limiting and Ordering the Scan Result AWS


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.


Solution

  • 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