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 – 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 – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

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

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Introduction

In this article, we’ll learn how to use the geospatial capabilities of Elasticsearch.

We won’t delve into how to set up an Elasticsearch instance and the Java client. Instead, we’ll describe how to save geo-data and how we can search for it using geo queries.

Let’s dive into the available geo data types.

2. Geo Data Type

In Elasticsearch, we can work with two main types of geo data: a geo_point consists of latitude and longitude coordinates, and a geo_shape can depict different shapes like rectangles, lines, and polygons. We must manually create the index mapping and explicitly set the field mapping to use geo-queries to proceed. Furthermore, it’s important to note that dynamic mapping won’t work while setting mapping for geo types.

Moving forward, let’s delve into the specific details of each geo data type.

2.1. Geo Point Data Type

The simplest type is the geo_point, which represents a pair of latitude and longitude on a map. We can use a point in various ways, such as looking if it is inside a box or searching for objects in a specific range represented by a distance. Additionally, we could search for the indexed point within a query representing a complex geo_shape. As an illustration, we can view a geo_point as a pinpoint on a map.

Moreover, geo points allow us to group documents by location, including within specific regions or by distance from a specified point, and then sort the documents accordingly. For example, objects from near to our point to further away.

The first thing to remember is to create the mapping of geo_point using the properties of our index’s data type:

PUT /index_name
{
    "mappings": {
        "TYPE_NAME": {
            "properties": {
                "location": { 
                    "type": "geo_point" 
                } 
            } 
        } 
    } 
}

So, we are ready to send our data points to Elasticsearch.

2.2. Geo Shape Data Type

Unlike geo-point, geo-shape provides the functionality to save and search complex shapes like polygons and rectangles. To search documents that contain shapes other than geopoints, we must use a geo_shape data type.

Similarly, let’s map a geo shape in our index’s data type:

PUT /index_name
{
    "mappings": {
        "TYPE_NAME": {
            "properties": {
                "location": {
                    "type": "geo_shape"
                }
            }
        }
    }
}

Elasticsearch represents a geo_shape as a triangular mesh that allows it to provide a very high spatial resolution.

Next, we’ll look at how we can save the data inside our index.

3. Different Ways to Save Geo Point Data

Let’s assume we mapped a type location as a geo_point in our index.

3.1. Latitude Longitude Object

We can explicitly define the latitude and longitude of the points, providing them as keys to the location type:

PUT index_name/_doc
{
    "location": { 
        "lat": 23.02,
        "lon": 72.57
    }
}

This is the most readable method that doesn’t add any ambiguity.

3.2. Latitude Longitude Pair

We can reduce the verbosity of the previous method and define the latitude-longitude pair in plain string format:

{
    "location": "23.02,72.57"
}

To emphasize, string geopoints are ordered as lat, lon, while array geopoints, GeoJSON, and WKT are ordered as the reverse: lon, lat.

3.3. Longitude Latitude Array

Alternatively, we can provide the point as an array:

{
    "location": [72.57, 23.02]
}

It’s important to realize that the sequence of latitude-longitude is reversed when latitude and longitude are supplied as an array.

Initially, the latitude-longitude pair was used in both a string and an array, but later, it was reversed to match the format used by GeoJSON.

3.4. Geo Hash

At last, we can use geo hash instead of the explicit pair values to represent our point:

{
    "location": "tsj4bys"
}

Even though hash values are concise and great for proximity search, they are not very readable. For example, we can use the online tool to convert latitude-longitude to geo hash.

4. Different Ways to Save Geo Shape Data

Let’s assume we mapped a type region as a geo_shape in our index.

4.1. Point

We create first the most simple shape, which is a point:

POST /index/_doc
{
    "region" : {
        "type" : "point",
        "coordinates" : [72.57, 23.02]
    }
}

In short, inside the region field, we have a nested object consisting of field type and coordinates. In particular, these meta-fields help Elasticsearch identify the data.

4.2. LineString

Then, we are going to insert a linestring:

POST /index/_doc
{
    "region" : {
        "type" : "linestring",
        "coordinates" : [[77.57, 23.02], [77.59, 23.05]]
    }
}

In short, the coordinates for a linestring are two points that represent the starting point and the end of the line segment. Aggregating many LineString is helpful when creating navigation systems.

4.3. Polygon

Next, we’ll insert a polygon geo shape:

POST /index/_doc
{
    "region" : {
        "type" : "polygon",
        "coordinates" : [
            [ [10.0, 0.0], [11.0, 0.0], [11.0, 1.0], [10.0, 1.0], [10.0, 0.0] ]
        ]
    }
}

With attention to this example’s first and last coordinates, we must ensure the match for a closed polygon.

4.4. Other GeoJSON/WKT Formats

Finally, the list of GeoJSON/WKT structures supported by Elasticsearch is very rich:

  • MultiPoint
  • MultiLineString
  • MultiPolygon
  • GeometryCollection
  • Envelope (This is not valid GeoJSON, but Elasticsearch and WKT support it)

Moreover, we can check all the supported formats on the official ES site.

To sum up, we must provide the inner type and coordinates fields to index documents correctly. Additionally, sorting and retrieving geo-shape fields are currently impossible in Elasticsearch due to their complex structure. Therefore, the only way to retrieve geo fields is from the source field.

5. Insert Geo Data in ElasticSearch

Now, let’s insert some documents and learn how to fetch them using geo queries. To begin with, we must add the Elastic search’s Java Client:

<dependency>
    <groupId>co.elastic.clients</groupId>
    <artifactId>elasticsearch-java</artifactId>
    <version>8.9.0</version>
</dependency>

5.1. Create an Index With Explicit Mappings

Before we can insert data, we need to define the mappings for our index:

client.indices().create(builder -> builder.index(WONDERS_OF_WORLD)
  .mappings(bl -> bl
    .properties("region", region -> region.geoShape(gs -> gs))
    .properties("location", location -> location.geoPoint(gp -> gp))
  )
);

Here, the client is an instance of the ElasticsearchClient object. In short, we are creating two data types. The first is a geo_shape named region, and the second is a geo_point named location.

5.2. Insert geo_point Documents

To begin with, we create a Java Class that represents will represent our geo_point data:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Location {
    private String name;
    private List<Double> location;
}

In detail, the name will refer to the location’s name, and the list location will be the two values representing the position. In addition, we are using Lombok to keep the code clean and concise.

Now, we can index a new document using the index() method:

Location pyramidsOfGiza = new Location("Pyramids of Giza", List.of(31.1328, 29.9761));
IndexResponse response = client.index(builder -> builder
  .index(WONDERS_OF_WORLD)
  .document(pyramidsOfGiza));

Also, the .document() will automatically convert the Location object to a valid JSON. Alternatively, we can work directly with JSON strings and use .withJson() and provide the string as a StringReader:

String jsonObject = """
    {
        "name":"Lighthouse of alexandria",
        "location":{ "lat": 31.2139, "lon": 29.8856 }
    }
    """;
IndexResponse response = client.index(idx -> idx
  .index(WONDERS_OF_WORLD)
  .withJson(new StringReader(jsonObject)));

5.3. Insert geo_shape Documents

Next, to insert geo_shape documents, we can work with JSON strings directly:

String jsonObject = """
    {
        "name":"Agra",
        "region":{
            "type":"envelope",
            "coordinates":[[75,30.2],[80.1,25]]
        }
    }
    """;
IndexResponse response = client.index(idx -> idx
    .index(WONDERS_OF_WORLD)
    .withJson(new StringReader(jsonObject)));

Now, we are ready to make some queries to search for our data.

6. Query Geo Data in ElasticSearch

6.1. Geo Bounding Box Query

To begin with, suppose we have a bunch of geo points on a map, and we want to find them in a rectangular area. Then, we must use a bounding box query to fetch all the points:

{
   "query":{
      "geo_bounding_box":{
         "location":{
            "top_left":[30.0,31.0],
            "bottom_right":[32.0,28.0]
         }
      }
   }
}

Further, we can create a SearchRequest in our project for this purpose:

SearchRequest.Builder builder = new SearchRequest.Builder().index(WONDERS_OF_WORLD);
builder.query(query -> query
  .geoBoundingBox(geoBoundingBoxQuery ->
    geoBoundingBoxQuery.field("location")
      .boundingBox(geoBounds -> geoBounds.tlbr(bl4 -> bl4
        .topLeft(geoLocation -> geoLocation.coords(List.of(30.0, 31.0)))
        .bottomRight(geoLocation -> geoLocation.coords(List.of(32.0, 28.0))))
      )
  )
);

Moreover, the Geo Bounding Box query supports similar formats as we have in the geo_point data type. Additionally, sample queries for supported formats can be found on the official site.

Finally, we use the SearchRequest to query ElasticSearch:

SearchResponse<Location> searchResponse = client.search(build, Location.class);
log.info("Search response: {}", searchResponse);

6.2. Geo Shape Query

Next, to query geo_shape documents, we must use GeoJSON.

For example, we might want to find all the documents that fall within specific coordinates:

{
  "query":{
    "bool":{
      "filter":[
        {
          "geo_shape":{
            "region":{
              "shape":{
                "type":"envelope",
                "coordinates":[[74.0,31.2],[81.1,24.0]]
              },
              "relation":"within"
            }
          }
        }
      ]
    }
  }
}

In detail, the relation field in the query determines spatial relation operators used at search time. So, we can choose from a list of operators:

  • INTERSECTS – (default) returns all documents whose geo_shape field intersects the query geometry
  • DISJOINT – retrieves all documents whose geo_shape field has nothing in common with the query geometry
  • WITHIN – gets all documents whose geo_shape field is within the query geometry
  • CONTAINS – returns all documents whose geo_shape field contains the query geometry

Similarly, we can query using different GeoJSON shapes.

For example, the query above can be implemented as the following SearchRequest:

StringReader jsonData = new StringReader("""
    {
        "type":"envelope",
        "coordinates": [[74.0, 31.2], [81.1, 24.0 ] ]
    }
    """);

SearchRequest searchRequest = new SearchRequest.Builder()
  .query(query -> query.bool(boolQuery -> boolQuery
    .filter(query1 -> query1
      .geoShape(geoShapeQuery -> geoShapeQuery.field("region")
        .shape(
          geoShapeFieldQuery -> geoShapeFieldQuery.relation(GeoShapeRelation.Within)
            .shape(JsonData.from(jsonData))
  ))))).build();

Similarly, to query the data, we can call search() using the SearchRequest:

SearchResponse<Object> search = client.search(searchRequest, Object.class);
log.info("Search response: {}", search);

To point out the source of the SearchResponse maps to a generic Object class. Given that, geo_shapes can have various forms, and we don’t know what the query might return beforehand.

6.3. Geo Distance Query

Next, to find all the documents that come within a specified range of a point, we use a geo_distance query:

{
    "query":{
        "geo_distance":{
          "location":{
              "lat":29.976,
              "lon":31.131
          },
          "distance":"10 miles"
        }
    }
}

Likewise, we can implement the query above in Java using a SearchRequest:

SearchRequest searchRequest = new SearchRequest.Builder().index(WONDERS_OF_WORLD)
  .query(query -> query
    .geoDistance(geoDistanceQuery -> geoDistanceQuery
      .field("location").distance("10 miles")
      .location(geoLocation -> geoLocation
        .latlon(latLonGeoLocation -> latLonGeoLocation
          .lon(29.88).lat(31.21)))
    )
  ).build();

Like geo_point, geo distance query supports multiple formats for location coordinates.

6.4. Geo Polygon Query

Next, we’ll create a polygon within which we want to find all the points. In particular, we’ll create a geo_shape query of shape geo_polygon:

{
    "query":{
        "bool":{
          "filter":[
            {
                "geo_shape":{
                    "location":{
                        "shape":{
                            "type":"polygon",
                             "coordinates":[[[68.859, 22.733],[68.859, 24.733],[70.859, 23]]]
                        },
                        "relation":"within"
                    }
                }
            }
          ]
        }
    }
}

Again, we can rewrite the query in Java:

JsonData jsonData = JsonData.fromJson("""
    {
        "type":"polygon",
        "coordinates":[[[68.859,22.733],[68.859,24.733],[70.859,23]]]
    }
    """);

SearchRequest build = new SearchRequest.Builder()
  .query(query -> query.bool(
    boolQuery -> boolQuery.filter(
      query1 -> query1.geoShape(geoShapeQuery -> geoShapeQuery.field("location")
        .shape(
          geoShapeFieldQuery -> geoShapeFieldQuery.relation(GeoShapeRelation.Within)
            .shape(jsonData)))))
 ).build();

Only the geo_point data type is supported with this query.

7. Conclusion

In this article, we discussed different mapping options for indexing geo data, i.e. geo_point and geo_shape.

We also went through different ways to store geo-data, and finally, we observed geo-queries and Java API to filter results using geo queries.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
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.

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

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)