The design of DynamoDB means that it is not particularly good at returning all items.
Returning all items is a SCAN
, which although it allows you to impose limits on the returned items, is always unsorted.
The only way to get a sorted response is if you QUERY
on a table with a partition and sort key. In the case you can query on partition
and it will return the results ordered by sort
(ascending/descending is supported).
There's another question which gives a larger discussion about fixes you can do to sort a scan, but effectively it breaks down into:
- Have an attribute that is set to be the same in every item (let's call it
scannable
and it'll be set to scan_me
)
- Create a Global Secondary Index with partition
scannable
and sort created
keys
- Query
scannable == "scan_me"
and that will return all the data in your table (up to limit
in the string order of created
.
This is not a scalable solution, but it'll "work" for small amounts of data. Note that as @matthew-pope points out, your created
key does not sort (or, more specifically it sorts by hour-minute-day-month-year) which means you would also need to replace your created
key with either a epoch-seconds or ISO datestring (as these both sort with default comparators).
Finally if TOP N
is going to be important to you, then there is a probably a solution using a dynamodb -> dynamodb streams -> lambda -> another dynamodb table
pattern to maintain a materialised view. (This pattern is often the suggested solution to supporting more complex "queries" in dynamo.)