skip to Main Content

I need to get the rows by key (e.g. where status is "Active") but with sorting on multiple columns.

I’m using the pagination that’s why I cannot sort the result after fetching it from the DynamoDB. (Just for the information, I’m using the serverless framework)

Expected Output is array of rows sorted (ordered) by multiple columns.

2

Answers


  1. In DynamoDB you get "free" lexicographical sorting on the range keys.

    When an item is being inserted first its partition is calculated based on the partition key then the item is inserted into a b-tree which keeps the partition lexicographically sorted at all times. This doesn’t give you all of the features of SQLs Order By, which is not supported

    So if your sort keys look something like this

    Status#Active#UserId#0000004
    

    You can do "begins_with" query with SK = "Status#Active"

    This will give you all of the items that are in active status ordered by the UserId (that has to be zero-padded in order to enforce the lexicographical order).

    Login or Signup to reply.
  2. You can’t do that. Sorting can be only done on SK under the same PK. You could combine multiple columns into one value and query based on it. Something like column1-value1#column2-value2.

    In that case you’ll probably have issue in updating that field, dynamodb streams could help with it. You can trigger event on any modification and asynchronously update that sorting field.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search