How to do Query in DynamoDB on the basis of HashKey and range Key?
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Introduction to Querying in DynamoDB
Amazon DynamoDB is a fully managed NoSQL database service that provides fast and predictable performance with seamless scalability. In DynamoDB, your data is stored in tables, and each table requires a primary key to uniquely identify its items. The primary key can be either a single attribute (the partition key or hash key) or a combination of two attributes (the partition key and the sort key or range key).
Querying DynamoDB databases allows you to retrieve data quickly and efficiently by specifying the primary key. This guide will walk you through the process of querying in DynamoDB using the hash and range keys.
Understanding the Data Model
Before diving into queries, it's essential to understand the structure of a DynamoDB table with the composite primary key, which consists of:
- Partition Key (Hash Key): This key is used to distribute data across nodes. It’s called the hash key because DynamoDB uses an internal hashing algorithm to determine where to store the data.
- Sort Key (Range Key): The sort key allows for multiple items with the same partition key because it adds a second level of uniqueness.
Here’s an example of a sample table schema:
| Attribute | Data Type |
| UserId (Hash) | String |
| OrderDate (Range) | Number |
| Amount | Number |
| Description | String |
How to Query Using Partition Key and Sort Key
The Query operation in DynamoDB allows retrieving multiple items with the same partition key, and optionally filter them using conditions on the sort key. Here's how to perform a query using both keys:
Setting Up a Query
- Identify the Table and Keys: You need to know the table name and both the partition and sort keys that define the schema. Let's assume:
- Table Name:
Orders - Partition Key:
UserId - Sort Key:
OrderDate
- Perform the Query: Using the AWS SDK, perform a query operation by specifying your partition key value and a condition on the sort key if needed.
Example Using AWS SDK for JavaScript
The following example demonstrates how to use the AWS SDK for JavaScript to query a DynamoDB table:
Explanation of the Code
- TableName: The name of the table you're querying, in this case, 'Orders'.
- KeyConditionExpression: This is where the magic happens. You specify that you want to retrieve all items where
UserIdis equal to:userIdandOrderDateis between:startand:end. - ExpressionAttributeValues: These are the actual values that are injected into the query to control its behavior:
:userIdis set to 'USER123', and:startand:endcontrol the date range.
Additional Subtopics
Query Performance Considerations
DynamoDB is optimized for fast, responsive querying, but it's crucial to understand some performance considerations:
- Provisioned Throughput: Ensure your table has adequate read units allocated to handle your query load.
- Efficient Use: Queries should be limited to retrieving only the data you need using projections.
- Indexing: Secondary indexes can be created to allow more complex queries but should be used judiciously to balance performance and cost.
Query vs Scan
It's essential to distinguish between the Query and Scan operations:
| Operation | Description | Performance | Best Use |
| Query | Retrieves items based on primary key | Highly efficient, low latency | Specific item lookup or range queries |
| Scan | Examines all items in the table | Resource-intensive, higher latency | Use sparingly for analyzing full datasets |
Use of Filters in Queries
Even though a query operation retrieves items based on primary and sort keys, you can further filter the results using conditions on non-key attributes. However, note that filters are applied after the data is retrieved; thus, they do not reduce the read capacity units consumed.
Conclusion
Querying in DynamoDB using hash and range keys is a powerful way to access data efficiently based on primary keys. With a firm understanding of the data model and proper usage of the AWS SDK, you can perform complex queries that suit your application's needs. Keep in mind performance considerations and strive to design your tables to leverage DynamoDB's strengths, ensuring they are provisioned appropriately and optimized for your specific use cases.
Related reading
- How to do scala heap dump in Kubernetes in Azure
- How to download a file from EC2 instance to Local Computer
- How to download data from Amazon's requester pay buckets?
- How to download the cuDNN straight from nvidia website to my linux instance on GCP
- How to do raw mongodb operations in mongoose?
- How to do SQL Like in Linq?
- How to download the latest build artifacts from Azure DevOps programmatically?
- How to Dynamodb send message to SQS

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.