Guide to Querying and Pagination with AWS DynamoDB in NestJS
Introduction
In my previous article, I provided a basic guide on initializing and using AWS DynamoDB, but in this article, we will delve deeper into QueryCommand.
In AWS DynamoDB, the Query method allows you to search for data based on the primary key (Partition Key) and filter conditions (Sort Key). To optimize performance and cost, DynamoDB supports a Pagination mechanism through the ExclusiveStartKey and LastEvaluatedKey parameters. Applying pagination not only reduces the data transfer load but also enables the application to handle large data tables smoothly, ensuring system stability.
Detail
Use AWS CDK to create the file lib/dynamodb-gsi-stack.ts
By default, DynamoDB only allows you to query efficiently based on id. If you want to find "All products with status 'DELIVERED'", you would have to scan the entire table (Scan), which is very costly.
Adding StatusIndex (GSI) helps filter the list of products by status (e.g., Active, Pending, Deleted) without scanning the entire database.
- indexName: StatusIndex. This is the index name to use when querying.
- partitionKey (of Index): status. Helps query extremely fast based on the status column.
- sortKey (of Index): createdDate. Helps retrieve the list of products by status but still sorted by time (e.g., getting the latest pending orders).
- projectionType: ALL. This means that when querying on this Index, DynamoDB will return all fields (attributes) of that item, just like querying the main table.
Update the file bin/aws-cdk.ts
In the NestJS source code, please update the file dynamodb.service.ts
The code above includes 3 main functions for processing data:
- queryProduct: Executes a product query by ID and a time range (BETWEEN) of the creation date.
- queryProductByStatus: Uses a Global Secondary Index (GSI) named 'StatusIndex' to search by status. Note the use of ExpressionAttributeNames to avoid conflicts with the system keyword "status".
- queryProductsWithPagination: Implements pagination. The function receives a 'limit' to restrict the quantity and 'lastKey' (in Base64 form). If 'lastKey' exists, it decodes it to put into ExclusiveStartKey to retrieve the next page, then encodes the new LastEvaluatedKey into 'nextToken' to return to the Client.
Update the file dynamodb.controller.ts to use DynamoDBService
Check the results using Postman as follows
You can also query on the AWS Web Console
Happy coding!
Comments
Post a Comment