A developer is building a smart home energy monitoring dashboard. The energy usage data is stored in an Amazon DynamoDB table where the partition key is SmartMeterID and the sort key is ReadingTimestamp. The developer needs to retrieve all energy consumption readings for a specific SmartMeterID over the last 7 days to display them on a user dashboard.
Which of the following approaches is the most performant and cost-effective method to retrieve these records?
- Execute a Query operation with a KeyConditionExpression that specifies the SmartMeterID and uses a comparison operator on the ReadingTimestamp sort key.Answer
- BPerform a Scan operation across the entire table, applying a FilterExpression to filter by the target SmartMeterID and ReadingTimestamp range.
- CInstantiate the DynamoDB client using hardcoded IAM access keys in the code to ensure permissions are resolved quickly, then run a Scan operation with a filter.
- DPerform a Scan operation, and if a ProvisionedThroughputExceededException occurs, scale up the overall provisioned Read Capacity Units (RCUs) for the table.
Answer
Execute a Query operation with a KeyConditionExpression that specifies the SmartMeterID and uses a comparison operator on the ReadingTimestamp sort key.
The Query operation is the most efficient and cost-effective way to retrieve items from a DynamoDB table when the partition key is known. By specifying the partition key (SmartMeterID) and using a comparison operator on the sort key (ReadingTimestamp) in the KeyConditionExpression, DynamoDB only reads the items that match the criteria, minimizing the consumed Read Capacity Units (RCUs).
Step-by-Step Solution
Key Concept
Efficient data retrieval using the DynamoDB Query API vs Scan API