Search code examples
node.jsamazon-dynamodbdynamodb-queries

Dynamo db pagination


I want to use pagination in dynamodb using aws-sdk DocumentClient() I am using node.js.

What I want to do is get first 10 items and then return these value to the user. After that user makes a new request in which he tell the server to start from 10 and the server get other 10 from 10 to 20 and return the response back. I have tried the LastEvaluatedKey But my scenario is different. Is there any way that I can tell dynamodb to start from specific Item e.g 1 and then set Limit: 10.


Solution

  • I found a way to work around this. You need to get the LastEvaluatedKey from the dynamodb response and send it back to the front-end then your front-end should send the LastEvaluatedKey in params and you can use it as ExclusiveStartKey.

    getItems(pageSize, lastItem?) {
        try {
          const params = {
            TableName: 'User',
            Limit: pageSize,
          };
          if (lastItem) {
            params.ExclusiveStartKey = { item_id: lastItem};
          }
          const response = await dynamoDb.scan(params).promise();
          return {
             items: response.Items,
             lastItem: response.LastEvaluatedKey
          }
    
        } catch (error) {
          throw error;
        }