Search code examples
ruby-on-railssolrsunspotwebsolr

How can I reference the distance with the Solr Spatial Search in Sunspot?


I am using Apache Solr via Sunspot on Rails with the standard syntax:

class Post < ActiveRecord::Base
  searchable do
    # ...
    latlon(:location) { Sunspot::Util::Coordinates.new(lat, lon) }
  end
end

With a search:

Post.search do
  order_by_geodist(:location, 32, -68)
end

How can I get the distance from the search location in the hits? I have tried a million different syntax options for returning geodist in the hits but nothing seems to work.


Solution

  • In Sunspot 2.0.0.pre.120925, you have to incorporate the hack at http://wiki.apache.org/solr/SpatialSearch#Returning_the_distance. This will put the distance into the score, which would look something like:

    results = Post.search do
      fulltext "{!func}geodist(location_ll, 32, -68)"
      order_by(:score, :asc)
    end
    
    post = results.hits.first.result
    distance = results.hits.first.score