Location Queries with Spring Data Solr

Last time we looked at how to work with Solr location field types in Spring. We retrieved a location as String Property in our Product Model then converted it to a Point or Distance value using the Spring Framework GeoConverters class as needed. Today we're going to cover different ways to perform location (or “Spatial”) Solr queries with Spring Data Solr. Using our Product Demo records in NixMash Spring we will perform the following queries:

  1. Stores within a certain number of miles of a location using a Spring Data Query Method
  2. Stores near a location using a Spring Data Query Method
  3. Stores near a location using a Spring Annotated Solr Query
  4. Stores near a location using the Spring Data Criteria API
  5. Stores located inside a GeoLocation Box area

The JUnit Setup

We'll be using JUnit to demonstrate our Spring Solr location queries so let's look at our Test @Before and @After logic. Basically we're creating two stores for each test, which will return one and only one store location.

As I said, each query will return one of the two store locations. Here are the shared asserts for most of the tests we'll be seeing.

1. Find Stores within a certain number of miles of Location

In our first location query we'll be using a Spring JPA Query Method located in our Product Repository.

public List<Product> findByLocationWithin(Point location, Distance distance);

Our query using standard Spring Query Method logic.

2. Find Stores near a given location

Again we'll use the Spring Query Method approach which is nearly identical to the findByLocationWithin() method, but now findByLocationNear(). Here's our JUnit query.

3. Using a Spring Annotated Solr Query

We can use all of the standard Spring Data query types for Solr Location searching, so here's an example of using an Annotated Query. In our Repository we add a “Somewhere” to our Method Name, but we're cool because we include the Solr @Query.

@Query("{!geofilt pt=?0 sfield=store d=?1}")
public List<Product> findByLocationSomewhereNear(Point location, Distance distance);

Our JUnit query.

4. Using the Spring Data Criteria API

We'll build our Solr location query with the Spring Data Criteria API this time.

5. Retrieving Stores Within a GeoLocation Box

We can also query locations by a boxed area using the Spring Solr Box object, which is the equivalent of Solr's bbox filter, or Bounding-Box Filter.

The main lesson I think we've learned today is that Solr Location Queries conform to Spring Data Standards and are therefore very straightforward.

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.

Posted January 14, 2016 03:18 PM EST

More Like This Post