0
0
DynamoDBquery~5 mins

Limit and pagination in DynamoDB

Choose your learning style9 modes available
Introduction

Limit and pagination help you get data in small parts instead of all at once. This makes it easier to handle and faster to load.

When you want to show only 10 items per page in a shopping app.
When you have a big list of users and want to load them bit by bit.
When you want to save data transfer by not loading everything at once.
When you want to let users scroll through data without waiting long.
When you want to avoid timeouts by fetching data in smaller chunks.
Syntax
DynamoDB
Scan or Query operation with parameters:
{
  Limit: number,
  ExclusiveStartKey: { primaryKeyAttribute: value, ... } (optional)
}

Limit sets the max number of items to return.

ExclusiveStartKey tells DynamoDB where to continue from for the next page.

Examples
Get up to 5 items from the Products table.
DynamoDB
Scan({
  TableName: 'Products',
  Limit: 5
})
Get up to 10 orders for customer 123.
DynamoDB
Query({
  TableName: 'Orders',
  KeyConditionExpression: 'CustomerId = :cid',
  ExpressionAttributeValues: { ':cid': '123' },
  Limit: 10
})
Get next 5 items starting after ProductId 'P100'.
DynamoDB
Scan({
  TableName: 'Products',
  Limit: 5,
  ExclusiveStartKey: { ProductId: 'P100' }
})
Sample Program

This example fetches the first 3 items from the 'Books' table, then fetches the next 3 items using pagination.

DynamoDB
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB.DocumentClient();

async function fetchFirstPage() {
  const params = {
    TableName: 'Books',
    Limit: 3
  };
  const data = await dynamodb.scan(params).promise();
  console.log('First page items:', data.Items);
  return data.LastEvaluatedKey;
}

async function fetchNextPage(lastKey) {
  if (!lastKey) {
    console.log('No more pages');
    return;
  }
  const params = {
    TableName: 'Books',
    Limit: 3,
    ExclusiveStartKey: lastKey
  };
  const data = await dynamodb.scan(params).promise();
  console.log('Next page items:', data.Items);
  return data.LastEvaluatedKey;
}

(async () => {
  const lastKey = await fetchFirstPage();
  await fetchNextPage(lastKey);
})();
OutputSuccess
Important Notes

If LastEvaluatedKey is empty, you reached the last page.

Limit is a maximum, DynamoDB may return fewer items.

Use ExclusiveStartKey from last response to get the next page.

Summary

Limit controls how many items you get at once.

Pagination uses ExclusiveStartKey to continue from last place.

This helps handle large data smoothly and fast.