【问题标题】:Rails - Elasticsearch - search by coordinates with ChewyRails - Elasticsearch - 使用 Chewy 按坐标搜索
【发布时间】:2016-07-03 08:02:07
【问题描述】:

我通过 gem 'chewy' 在我的 Rails APP 上使用 Elasticsearch。

我有两个模型:Products 和 Tags [多对多关系,通过 ProductTag 模型管理]。

我将 ProductsIndex 定义如下:

class ProductsIndex < Chewy::Index
  define_type Product do
    field :name
    field :tags, value: -> { tags.map(&:name)}
    field :coordinates, type: 'geo_point', value: ->{ {lat: lat, lon: lon} }
  end
end

我可以在我的控制器中成功查询 ProductsIndex:

q = params[:q]
@products = ProductsIndex.filter { tags(:and) == [q] }.load

它返回给我所有带有指定标签的 Product 对象。

我的问题是:如何查询 ProductIndex 以返回给定坐标对(纬度/经度)半径 100 公里内的所有产品对象?

我并不严格需要按距离排序,但如果您将其包含在您的答案中,将不胜感激:)

编辑

我正在尝试这样的事情,但它不起作用:

ProductsIndex.filter {
  geo_distance: {    
    distance: '100km',    
    location: {        
      lat: 60.0951482712848,        
      lon: -86.4810766234584    
    }
  }
}

我收到以下语法错误

 SyntaxError: (irb):10: syntax error, unexpected ':', expecting '}'
...uctsIndex.filter {geo_distance: {    distance: '100km',    l...
...                               ^

【问题讨论】:

    标签: ruby-on-rails coordinates chewy-gem


    【解决方案1】:

    这是一场疯狂的狩猎,一个漫长的下午,但最终错误非常愚蠢:

    1. 我在查询中使用了location,而我将coordinates 定义为字段类型;
    2. .filter 后面的括号错误。

    正确的语法如下:

    ProductsIndex.filter(geo_distance: {
      distance: "100km",
      coordinates: {
        lat: <latitude>,
        lon:<longitude>
      }
    })
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      相关资源
      最近更新 更多