amazon-web-servicesamazon-dynamodbdocumentclient

DynamoDB | BatchGet | Get results in same order as provided Keys


I'm using AWS DynamoDB to store users.

Consider the following code:

let params = {
  RequestItems: {
    'users': {
       Keys: [
        {id: '1111'},
        {id: '2222'},
        {id: '3333'},
        {id: '4444'},
        ]
        }
      }
    };

Using the above params in a BatchGet will return the reqeusted users but in a random order!

Question: Is it possible to BatchGet users without losing the order defined in Keys?


Solution

  • You'd have to sort the items once they are retrieved. As documented here, When designing your application, keep in mind that DynamoDB does not return items in any particular order.

    I had the same issue in the recent past & had to write some extra code to sort the items the way I wanted.

    Update 22-Aug-2019: I wanted to mention that you could switch to using query on a GSI with a sort key and retrieve sorted data if that is feasible in your case.

    Use ScanIndexForward: true || false to sort the data in ascending or descending as needed.

    More details here