在Elasticsearch中计算地理距离

8
我正在使用带有geo_distance过滤器tire的查询,并且它可以正常工作:
search.filter :geo_distance, :distance => "#{request.distance}km", :location => "#{request.lat},#{request.lng}"

我原本期望结果中会包含筛选时使用的地理位置计算距离。有没有办法告诉 Elasticsearch 在响应中包含这个信息,这样我就不需要为每个结果在 Ruby 中计算了?
== 更新 ==
我在 Google 群组 找到了答案
search.sort do
  by "_geo_distance", "location" => "#{request.lat},#{request.lng}", "unit" => "km" if request.with_location?
end

按照 _geo_distance 进行排序将在原始结果中产生距离。

请参见 https://github.com/karmi/tire/issues/417#issuecomment-7331381 和 https://gist.github.com/1051213。 - karmi
1
@karmi,你有没有好的解决方案,可以将实际地理距离放入结果中,而不是sort字段? - phoet
@phoet 我不确定,必须进行研究... - karmi
请记住,“sort”和“filter”是两个不同的概念。如果您按照这种方式进行排序,排序将给您按距离中心点排序的结果,而过滤器可以为您提供一个类似边界框的东西,其中所有结果都在中心点的X英里范围内,然后您可以对结果进行排序。 - bcackerman
2个回答

4

1

对于那些可能会想知道的人,距离是在弹性搜索结果的排序属性中返回的。为了访问它并在视图中显示它,请使用each_with_hit方法。例如:

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”修改了结果对象并呈现了正确的JSON。到目前为止,要使其工作,您必须在搜索时将load设置为true:
:load => true

有人知道如何在 ElasticSearch Nest 中实现这个吗? - levininja

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接