'Sorting, Skip and Limit(Skip) queries for Amazon DynamoDB

I am new to AWS Lambda, Amazon DynamoDB and serverless. I have one user table want to do like this.

  1. I want to fetch records pagination wise in each page fetch 10 records from the user table,
  2. I want to make sorting on columns like name and email. This both column with string datatype.

I am using serverless with node.js. Here I'm attaching my serverless.yaml file

UserDynamoDbTable:
  Type: 'AWS::DynamoDB::Table'
  DeletionPolicy: Retain
  Properties:
    AttributeDefinitions:
      -
        AttributeName: id
        AttributeType: S
    KeySchema:
      -
        AttributeName: id
        KeyType: HASH
    ProvisionedThroughput:
      ReadCapacityUnits: 1
      WriteCapacityUnits: 1
    TableName: 'user'

For sorting i'm trying with this query

let params = {
     TableName: 'user',
     limit: 10,
     ScanIndexForward: false
};
dynamoDb.scan(params, (error, result) => { })

But I didn't get a response as per my requirement. Please help me here I'm new into this. Thanks in advance.



Solution 1:[1]

ScanIndexForward works on range key only. As the table doesn't contain range key (i.e. sort key) defined, the data is not sorted.

Specifies ascending (true) or descending (false) traversal of the index. DynamoDB returns results reflecting the requested order determined by the range key.

Unfortunately, DynamoDB can't sort the data by any other attributes. It can sort by range key only.

Solution 2:[2]

If you need to work around this, the best solution would be to add a secondary global index. That is essentially a copy of your table that has the appropriate sorting keys that come in handy in scenarios such as this.

Using Global Secondary Indexes in DynamoDB

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 notionquest
Solution 2 Brandon Johnson