user0999
user0999

Reputation: 23

Pagination in aws dynamodb

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

let currentDate = moment().format('YYYY-MM-DD');
let code = "19";


let page = 1; 
let limit = 10; 
let offset = (page - 1) * limit;

const params = {
    TableName: "tablename,
    IndexName: "indexname",
    KeyConditionExpression: "code = :num AND Date = :keyValue",
    ExpressionAttributeValues: {
        ":num": code,
        ":keyValue": Date
    },
    Limit: limit,
    ExclusiveStartKey: offset > 0 ? {
        code: code,
        Date: currentDate,
    } : undefined
};

let output = await docClient.send(new QueryCommand(params));
return API.ok(output);

Want to switch from page n to page n. let say the table has 100 records each 10 records per page. user wants to switch from 1 to 49 or from 10 to 88 numbers can be anything.

Above code returning getting ValidationException: The provided starting key is invalid error

Index Structure is same in DynamoDB. also Data types of the attributes in the ExclusiveStartKey (code, Date) matches the data types defined in the DynamoDB table schema.

Upvotes: 0

Views: 25

Answers (1)

Leeroy Hannigan
Leeroy Hannigan

Reputation: 19813

DynamoDB does not page based on arbitrary indices, it pages based on your items. For a Query in your instance, code which is the partition key must remain the same, pagination uses the sort key Date to select items, which is what makes up your ExclusiveStartKey.

The short answer is you can't select pages they way you like, you can allow the user go back and forth between pages, but knowing what information would be on page 88 while you're on page 10 is not possible, at least not without reading all the items locally.

Upvotes: 1

Related Questions