DVA-C02 Question 99
Single answerYou are building an application that stores user data in an Amazon DynamoDB table. The table uses a partition key of 'UserId' and a sort key of 'Timestamp'. Your application needs to efficiently query all items for a specific user within a specific time range. How can you achieve this using DynamoDB?
- A
Use the Query operation with a KeyConditionExpression specifying the UserId and a range condition on the Timestamp attribute.
- B
Use the Scan operation with a FilterExpression to retrieve all items for the specific UserId within the time range.
- C
Create a Global Secondary Index (GSI) with UserId as the partition key and Timestamp as the sort key, and query the GSI with a KeyConditionExpression.
- D
Use BatchGetItem to retrieve all items for the specific UserId and filter the results programmatically in your application.
Show answer and explanation
Correct answer: A
Explanation
The Query operation is the optimal choice in this scenario because it directly uses the table's primary key (UserId and Timestamp) to retrieve the required data efficiently. Using Scan or BatchGetItem would result in unnecessary resource consumption and slower performance. Creating a GSI is unnecessary because the existing table schema already supports the query requirements.
- A. Correct.
Correct: The Query operation is the most efficient way to retrieve items by specifying both the partition key (UserId) and a range condition on the sort key (Timestamp). This utilizes the table's primary key directly.
- B. Incorrect.
Incorrect: The Scan operation is less efficient because it reads the entire table and applies the FilterExpression afterward, which can lead to higher latency and costs.
- C. Incorrect.
Incorrect: While creating a GSI is an option, it's unnecessary in this scenario because the table's existing primary key (UserId and Timestamp) already supports the query requirements.
- D. Incorrect.
Incorrect: BatchGetItem is intended for retrieving multiple specific items by their keys, not for querying a range of items based on conditions. Filtering programmatically also leads to inefficiencies.