0

I'm using Elasticsearch on my Rails APP trhough gem 'chewy'.

I have two models: Products and Tags [many to many relationship, managed through ProductTag model].

I defined ProductsIndex as follow:

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

I can successfully query ProductsIndex in my controller with:

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

which returns me all the Product objects with the specified tag.

My question is: How can I query ProductIndex to return all the Product objects within a radius of 100Km from a given pair of coordinates (lat/lon)?

I do not strictly need sorting by distance, but if you include it in your answer it will be greatly appreciated :)

edit

I'm trying something like this but it doesn't work:

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

I got the following syntax error

 SyntaxError: (irb):10: syntax error, unexpected ':', expecting '}'
...uctsIndex.filter {geo_distance: {    distance: '100km',    l...
...                               ^
Community
  • 1
  • 1
davideghz
  • 3,596
  • 5
  • 26
  • 50

1 Answers1

0

It's been a wild hunt, and a long afternoon, but eventually the errors were pretty silly:

  1. I was using location in the query while I defined coordinates as field type;
  2. wrong brackets after .filter.

The correct syntax is as follow:

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

Hope it might help.

davideghz
  • 3,596
  • 5
  • 26
  • 50