Solr Spatial Search
One of our projects requires the spatial search to find the closest records for given addresses 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 SOLR configuration for location-based spatial search and how to run queries on 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.
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 a spatial query on the location data, we need to make changes in the
SOLR query. If you want to fetch all the documents within the radius (distance) for certain latitude & longitude,
http://{youripaddress}/:{solr_port}/solr/{solr_core}/select?wt=json&q=*:*&start=0&rows=10&fq={!geofilt pt=32.7766642,-96.79698789999999 sfield=latlon d=10}
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.
fl=*,_dist_:geodist(latlon,32.7766642,-96.79698789999999)
To sort your results by ascending distance, sort=geodist(latlon,32.7766642,-96.79698789999999) asc