Configure SOLR for Spatial Search Setup

One of our projects requires the spatial search to find the closest records for given address OR zipcodes. So we decided to use SOLR for performing a spatial search based on latitude & longitude for getting the closest records.

This blog describes on SOLR configuration for location-based spatial search and how to run queries on SOLR.

You can download latest SOLR from here: http://apache.mesi.com.ar/lucene/solr/

Schema Changes :

To add location data (latitude, longitude) in documents, we need to update the schema.xml file. We need to add a new field type (specifically used for geospatial searching). In case it's not already present (depends on SOLR version), we have to add the below fieldType definition to the schema.xml file.

FieldType definition is done. Now we need to define the fields for location data.

<field name="latlon" type="location" indexed="true" stored="true" />

indexed=true makes a field searchable (and sortable and facetable). For eg, if you have a field named test1 with indexed=true, then you can search it like q=test1:foo, where foo is the value you are searching for.

stored=true means you can retrieve the field when you search.

Indexing Location Data

Now to index the location data, we need to have the latitude and longitude in the following format as a string.

{latitude},{longitude}

The values are separated by a comma with no spaces between them.

Querying location data:

In order to make spatial query on the locaiton data, we need to make changes in SOLR query. If you want to fetch all the documents with in radius (distance) for certain latitude & longitude,

Replace the variables with your configuration details and the query will return all the documents within 10 miles of given lat, lng (32.7766642,-96.79698789999999).

geofilt: Filter allows you to retrieve results based on the geospatial distance from a given point. Another way of looking at it is that it creates a circular shape filter.

bbox : Filter is very similar to geofilt except it uses the bounding box of the calculated circle.

For more details, https://cwiki.apache.org/confluence/display/solr/Spatial+Search

In many cases, we want SOLR to return the distance with the document fields. For this purpose, SOLR provides distance function geodist. geodist function takes three optional parameters: (sfield,latitude,longitude). You can use the geodist function to sort results by distance or score return results.

The goal for customers is to not only have a visually attractive product but also make sure it has superb functionality. We accomplish this by building feature-rich, engaging, and user-friendly mobile app and web solutions consisting of intuitive UX, present-day technologies and tools and best-in-class interfaces.