8

i am using a geo_distance filter with tire in my query and it works fine:

search.filter :geo_distance, :distance => "#{request.distance}km", :location => "#{request.lat},#{request.lng}"

i expected that the result would somehow include the computed distance to the geo-location that i used for my filter.

is there a way to tell elasticsearch to include that in the response, so that i don't have to calculate it in ruby for every result?

== UPDATE ==

i found the answer in a google group:

search.sort do
  by "_geo_distance", "location" => "#{request.lat},#{request.lng}", "unit" => "km" if request.with_location?
end

sorting by the _geo_distance will yield the distance in the raw results.

phoet
  • 18,688
  • 4
  • 46
  • 74
  • Also please see https://github.com/karmi/tire/issues/417#issuecomment-7331381 and https://gist.github.com/1051213 – karmi Aug 01 '12 at 11:33
  • 1
    @karmi do you have a good solution for how to put the actual geo-distance into the result instead of the ```sort``` field? – phoet Aug 01 '12 at 14:00
  • @phoet Not sure about that at all, must research it... – karmi Aug 01 '12 at 14:59
  • Keep in mind, `sort` and `filter` are two different things. Sort will give you results that are organized by distance to the center point (if you do it like that), while filter can give you a bounding box of sorts where all results are say within X miles of your center point and then you can sort the results. – bcackerman Oct 29 '13 at 16:09

2 Answers2

4

Sorting by _geo_distance will return the distance in the results: http://www.elasticsearch.org/guide/reference/api/search/sort.html

gjb
  • 6,237
  • 7
  • 43
  • 71
1

For those that may be wondering, the distance is returned in the sort property of the elastic search results. In order to access it and display it in the view, use the each_with_hit method. For instance:

class Venue
    attr_accessor :distance
end

def index
    @search = Venue.search(params)
    @search.each_with_hit do |result, hit|
        result.distance = hit['sort'][0] # distance from the ES results
    end
    render json: @search.results
end

"each_with_hit" modifies the resulting object and renders the proper json. So far for this to work, you must set load to true when searching:

:load => true
chourobin
  • 4,004
  • 4
  • 35
  • 48