0
0
DynamoDBquery~30 mins

Query with sort key conditions in DynamoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Query with sort key conditions in DynamoDB
📖 Scenario: You are managing a DynamoDB table that stores orders for an online store. Each order has a customer_id as the partition key and an order_date as the sort key. You want to find all orders for a specific customer within a certain date range.
🎯 Goal: Build a DynamoDB query that retrieves all orders for customer_id 'C123' where the order_date is between '2023-01-01' and '2023-01-31'.
📋 What You'll Learn
Create a variable called key_condition_expression that specifies the partition key equals 'C123' and the sort key is between '2023-01-01' and '2023-01-31' using DynamoDB condition functions.
Create a dictionary called expression_attribute_values with the exact keys :cust_id, :start_date, and :end_date and their corresponding values.
Write a query call using table.query() with the parameters KeyConditionExpression and ExpressionAttributeValues using the variables above.
Add a ScanIndexForward=False parameter to the query to sort results in descending order by order_date.
💡 Why This Matters
🌍 Real World
Querying DynamoDB tables with partition and sort key conditions is common in real-world applications like e-commerce order tracking, where you want to find all orders for a customer within a date range.
💼 Career
Understanding how to write DynamoDB queries with key conditions and sorting is essential for backend developers and cloud engineers working with AWS databases.
Progress0 / 4 steps
1
Create the key condition expression dictionary
Create a variable called key_condition_expression that uses the DynamoDB condition functions to specify customer_id equals :cust_id and order_date is between :start_date and :end_date. Use Key('customer_id').eq(:cust_id) & Key('order_date').between(:start_date, :end_date) exactly.
DynamoDB
Need a hint?

Use Key from boto3.dynamodb.conditions to build the condition.

2
Create the expression attribute values dictionary
Create a dictionary called expression_attribute_values with keys ':cust_id', ':start_date', and ':end_date' and values 'C123', '2023-01-01', and '2023-01-31' respectively.
DynamoDB
Need a hint?

Use a dictionary with the exact keys and values as shown.

3
Write the DynamoDB query call
Write a query call using table.query() with parameters KeyConditionExpression=key_condition_expression and ExpressionAttributeValues=expression_attribute_values. Assign the result to a variable called response.
DynamoDB
Need a hint?

Use table.query() with the correct parameters.

4
Add descending sort order to the query
Add the parameter ScanIndexForward=False to the table.query() call to sort the results by order_date in descending order.
DynamoDB
Need a hint?

Set ScanIndexForward to False inside the query call.