Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat= Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – All Access – NPI EA (cat= Spring)
announcement - icon

All Access is finally out, with all of my Spring courses. Learn JUnit is out as well, and Learn Maven is coming fast. And, of course, quite a bit more affordable. Finally.

>> GET THE COURSE
Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

End-to-end testing is a very useful method to make sure that your application works as intended. This highlights issues in the overall functionality of the software, that the unit and integration test stages may miss.

Playwright is an easy-to-use, but powerful tool that automates end-to-end testing, and supports all modern browsers and platforms.

When coupled with LambdaTest (an AI-powered cloud-based test execution platform) it can be further scaled to run the Playwright scripts in parallel across 3000+ browser and device combinations:

>> Automated End-to-End Testing With Playwright

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

eBook – Guide Spring Cloud – NPI (cat=Cloud/Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

1. Introduction

Amazon DynamoDB is one of the core services offered by AWS. It is widely used for building fast, scalable, and serverless applications. It provides a fully managed NoSQL database solution with single-digit millisecond performance at any scale. Unlike traditional relational databases, DynamoDB uses a key-value and document data model that encourages designing data access patterns up front.

In this tutorial, we’ll focus on one of DynamoDB’s most powerful features: querying data using a composite primary key, which combines a Partition Key and a Sort Key. We’ll walk through how this composite key model works and demonstrate how to efficiently query data using it with the AWS SDK for Java.

2. Understanding the Composite Key Model

DynamoDB supports two types of primary keys: a simple key (just a Partition Key) and a composite key, which combines a Partition Key and a Sort Key.

The Partition Key determines where the data is stored, while the Sort Key allows sorting and filtering within that partition. This model fits related data, like user orders, under a single key. For example, in a UserOrders table:

  • userId can be the Partition Key
  • orderDate can be the Sort Key

This setup makes it easy to retrieve all a user’s orders, sort them by date, or filter by time range, all with a single query.

3. Maven Dependency

To interact with DynamoDB from a Java application, we’ll use the AWS SDK for Java v2, which provides a modern, non-blocking API:

<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>dynamodb</artifactId>
    <version>2.31.26</version>
</dependency>

This gives us access to the DynamoDbClient and other necessary classes to run queries against our table.

4. Querying by Partition Key

The simplest and most common way to query data in DynamoDB is by using the Partition Key. When we query by Partition Key, DynamoDB returns all items sharing the same partition key value.

Let’s say our UserOrders table stores orders for multiple users, and we want to retrieve all orders placed by a single user. Since userId is our Partition Key, we can do this with a basic query:

QueryRequest queryRequest = QueryRequest.builder()
  .tableName("UserOrders")
  .keyConditionExpression("userId = :uid")
  .expressionAttributeValues(Map.of(
    ":uid", AttributeValue.builder().s("user1").build()
  )).build();

QueryResponse response = dynamoDbClient.query(queryRequest);

In the example above, we use the DynamoDbClient to execute the query. We built the request using the builder pattern, making it easy to construct complex requests. After executing the query, the results are returned in the QueryResponse object. To access the actual data, we use the items() method:

List<Map<String, AttributeValue>> items = response.items();

for (Map<String, AttributeValue> item : items) {
    System.out.println("Order item: " + item.get("item").s());
}

This list contains each item as a map of attribute names to values, which you can further process or convert into application-specific objects.

5. Querying with Partition Key and Sort Key

While querying by Partition Key alone might be useful, sometimes we need more precise filtering. We can achieve this by combining the Partition Key with conditions on the Sort Key. This allows us to filter results within a partition, for example, by a date range or a specific prefix.

Let’s say we want to retrieve all orders placed by user1 after January 1st, 2025. Since orderDate is our Sort Key, we can include a comparison in the keyConditionExpression:

QueryRequest queryRequest = QueryRequest.builder()
  .tableName("UserOrders")
  .keyConditionExpression("userId = :uid AND orderDate > :startDate")
  .expressionAttributeValues(Map.of(
    ":uid", AttributeValue.builder().s("user1").build(),
    ":startDate", AttributeValue.builder().s("2025-01-01").build()
  )).build();

QueryResponse response = dynamoDbClient.query(queryRequest);

In this query, we use the Partition Key and a condition on the Sort Key to narrow down the results. DynamoDB will only scan the partition for user1 and return items where the orderDate is after 2025-01-01. This approach is efficient because it avoids scanning unrelated data.

6. Common Range Key Conditions

DynamoDB supports several useful operators for filtering by the Sort Key. These allow us to fine-tune our queries within a partition by using standard comparison logic.

6.1. BETWEEN

We can use BETWEEN to retrieve items within a specific range. This is especially helpful when working with timestamps or dates:

QueryRequest queryRequest = QueryRequest.builder()
  .tableName("UserOrders")
  .keyConditionExpression("userId = :uid AND orderDate BETWEEN :from AND :to")
  .expressionAttributeValues(Map.of(
    ":uid", AttributeValue.builder().s("user1").build(),
    ":from", AttributeValue.builder().s("2024-12-01").build(),
    ":to", AttributeValue.builder().s("2024-12-31").build()
  )).build();

This will return all orders placed by user1 in December 2024.

6.2. BEGINS_WITH

If our Sort Key is a string (like a formatted date), we can query all items that start with a specific prefix. This is helpful for grouping by year, month, or any string-based prefix.

QueryRequest queryRequest = QueryRequest.builder()
  .tableName("UserOrders")
  .keyConditionExpression("userId = :uid AND begins_with(orderDate, :prefix)")
  .expressionAttributeValues(Map.of(
    ":uid", AttributeValue.builder().s("user1").build(),
    ":prefix", AttributeValue.builder().s("2025-01").build()
  )).build();

This will return all orders placed in January 2025.

7. Handling Pagination in Queries

DynamoDB limits the size of each query response to 1 MB of data. If our query matches more than that, DynamoDB returns a LastEvaluatedKey in the response, which we can use to continue fetching the next page of results.

To handle this, we should paginate through the results in a loop:

List<Map<String, AttributeValue>> allItems = new ArrayList<>();
Map<String, AttributeValue> lastKey = null;

do {
    QueryRequest.Builder requestBuilder = QueryRequest.builder()
      .tableName("UserOrders")
      .keyConditionExpression("userId = :uid")
      .expressionAttributeValues(Map.of(
        ":uid", AttributeValue.fromS(userId)
      ));

    if (lastKey != null) {
        requestBuilder.exclusiveStartKey(lastKey);
    }

    QueryResponse response = dynamoDb.query(requestBuilder.build());
    allItems.addAll(response.items());
    lastKey = response.lastEvaluatedKey();
} while (lastKey != null && !lastKey.isEmpty());

return allItems;

<This pattern ensures we retrieve all matching items, regardless of how many are returned per page. It’s useful when querying large partitions or doing report-style exports.

8. Conclusion

DynamoDB’s composite key model gives us a powerful way to organize and retrieve data efficiently. Using a Partition Key together with a Range Key allows us to organize related data and create efficient, scalable access patterns for high-performance applications.

In this article, we explored how to query a table using just the Partition Key and how to enhance those queries by including the Range Key to filter results within a partition.

As always, the code examples are available over on GitHub.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (All)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)
eBook – eBook Guide Spring Cloud – NPI (cat=Cloud/Spring Cloud)
Subscribe
Notify of
guest
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments