Spatial search with SOLR now ridiculously simple in Sitecore 9

Spatial search was introduced as a built in feature in SOLR with Sitecore from Sitecore 9. This made it extremely easy to implement geo spatial searches based on global coordinates.

We had to achieve a couple of targets in our project, which we easily achieved using Sitecore’s new simple integrated functionality

  • Get a list of retailers closest to the current geo ip, sorted by retailers closest to me
  • Filter the list of retailers, by a maximum distance radius from me

All you need to do to get started here, is ensure that the template you use – to store coordinates, must inherit from /sitecore/templates/System/Geospatial/Coordinate

Once you do this, sitecore search API updates for spatial search will be supported in your code.

For instance, to be able to filter your results based on distance from a given point, all you need to do is

IQueryable search = context.GetQueryable  ().WithinRadius(s => s.Location, new Coordinate(40.7127, -74.0059), 100)

This query was used to return the list of retailers within a 100 km radius for New York City.
Ps. Note – the radius parameter here accepts the distance in kilometers! Please ensure you convert your data if needed.

To be able to just bring back a sorted list of results, based on distance from a given point –

IQueryable search = context.GetQueryable()
    .OrderByDistance(s => s.Location, new Coordinate(40.7127, -74.0059));

On a side note, if you wanted to calculate the distance between 2 coordinates, you have an extension method to GeoCoordinate available in System.Device.Location. A point to note here – is that the distance is returned in meters only – so please keep conversion in mind if it applies to you!

private double GetDistance(GeoCoordinate src, GeoCoordinate dest, bool isMetric)
            // GetDistanceTo returns distance in meters
            return isMetric
                ? Math.Round(src.GetDistanceTo(dest) / 1000, 2)
                : Math.Round(MetersToMiles(src.GetDistanceTo(dest)), 2);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s