DynamoDB will return sorted results for you when you have a table or index set up with a Composite Primary Key. This means that two of the attributes are used to create the key. The first attribute is the Partition Key and the second one is the Sort Key which sorts the results WITHIN the partition.
To adapt their example to yours, imagine you have a Songs table and a Global Secondary index with the following key schemas:
Songs Table:
- ArtistID (partition key)
- SongName (sort key)
- Timestamp (an attribute)
SongsByArtistIndex (Global Secondary Index on the Songs table):
- ArtistID (partition key)
- Timestamp (sort key)
- SongName (a projected attribute)
In this example, you can run 2 types of queries, based on your ability & desire to sort on different attributes.
- Alphabetized list of songs by artist: Query the Songs table and set the KeyCondition to the artist that you want.
- Songs by artist sorted by date: Query the SongsByArtistIndex and set the KeyCondition to the artist that you want.
You probably need to change your table's key schema to optimize for the sorted queries/access patterns that you need for your scenario. Remember, you can only sort within a partition. Does that make sense?
More info:
DynamoDB Query Method, Query & Scan Operations in DynamoDB