Amazon DynamoDB (50 Qs)•Part 2: Intermediate Data Modeling & API Operations (Mid-Level)
How do you implement Pagination in DynamoDB queries?
mid LevelCode ExampleDynamoDBHTTP & REST APIs
In Simple Words:
DynamoDB returns at most 1 MB of data or the configured Limit in a single query:
- If more items remain, the response includes
LastEvaluatedKey. - Pass
ExclusiveStartKey: LastEvaluatedKeyin the subsequent query to fetch the next page. - Once
LastEvaluatedKeyis undefined/null, the last page has been reached.
Code Example (AWS SDK v3)
typescript
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, QueryCommand } from '@aws-sdk/lib-dynamodb';
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({ region: 'us-east-1' }));
export async function fetchAllOrders(userId: string) {
let lastEvaluatedKey: Record<string, any> | undefined = undefined;
const allOrders: any[] = [];
do {
const response = await docClient.send(
new QueryCommand({
TableName: 'OrdersTable',
KeyConditionExpression: 'PK = :pk',
ExpressionAttributeValues: { ':pk': `USER#${userId}` },
Limit: 50,
ExclusiveStartKey: lastEvaluatedKey,
})
);
if (response.Items) allOrders.push(...response.Items);
lastEvaluatedKey = response.LastEvaluatedKey;
} while (lastEvaluatedKey);
return allOrders;
}
Code Example (AWS SDK v3)
typescript
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, QueryCommand } from '@aws-sdk/lib-dynamodb';
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({ region: 'us-east-1' }));
export async function fetchAllOrders(userId: string) {
let lastEvaluatedKey: Record<string, any> | undefined = undefined;
const allOrders: any[] = [];
do {
const response = await docClient.send(
new QueryCommand({
TableName: 'OrdersTable',
KeyConditionExpression: 'PK = :pk',
ExpressionAttributeValues: { ':pk': `USER#${userId}` },
Limit: 50,
ExclusiveStartKey: lastEvaluatedKey,
})
);
if (response.Items) allOrders.push(...response.Items);
lastEvaluatedKey = response.LastEvaluatedKey;
} while (lastEvaluatedKey);
return allOrders;
}