0
0
DynamoDBquery~5 mins

Pagination with SDK in DynamoDB

Choose your learning style9 modes available
Introduction

Pagination helps you get data in small parts instead of all at once. This makes your app faster and easier to use.

When you want to show a list of items page by page in a website or app.
When your database has many records and loading all at once is slow.
When you want to save memory and bandwidth by loading only needed data.
When you want users to scroll or click to see more data gradually.
Syntax
DynamoDB
const params = {
  TableName: 'YourTableName',
  Limit: 10, // number of items per page
  ExclusiveStartKey: lastEvaluatedKey // from previous response
};

const data = await dynamodbClient.scan(params);
const lastEvaluatedKey = data.LastEvaluatedKey;

Limit controls how many items you get per page.

ExclusiveStartKey tells DynamoDB where to start the next page.

Examples
Get first 5 items from the 'Books' table.
DynamoDB
const params = {
  TableName: 'Books',
  Limit: 5
};
const data = await dynamodbClient.scan(params);
Get next 5 items starting after the last key from previous page.
DynamoDB
const params = {
  TableName: 'Books',
  Limit: 5,
  ExclusiveStartKey: lastKey
};
const data = await dynamodbClient.scan(params);
Sample Program

This code gets items from the 'Movies' table in pages of 3. It prints each page until no more items are left.

DynamoDB
import { DynamoDBClient, ScanCommand } from "@aws-sdk/client-dynamodb";

const client = new DynamoDBClient({ region: "us-east-1" });

async function paginateScan() {
  let lastEvaluatedKey = undefined;
  let page = 1;

  do {
    const params = {
      TableName: "Movies",
      Limit: 3,
      ExclusiveStartKey: lastEvaluatedKey
    };

    const command = new ScanCommand(params);
    const data = await client.send(command);

    console.log(`Page ${page}:`);
    data.Items.forEach(item => console.log(JSON.stringify(item)));

    lastEvaluatedKey = data.LastEvaluatedKey;
    page++;
  } while (lastEvaluatedKey);
}

paginateScan();
OutputSuccess
Important Notes

Always check if LastEvaluatedKey exists to know if more pages are available.

Pagination works similarly with QueryCommand in DynamoDB SDK.

Summary

Pagination splits large data into smaller pages for easier handling.

Use Limit to set page size and ExclusiveStartKey to continue from last page.

Keep fetching pages until LastEvaluatedKey is empty.