Radius search with the radius attribute in the searched model

Skip to first unread message


Aug 10, 2015, 9:33:30 AM8/10/15
to Sunspot
Hi everyone,

I already posted this to StackOverflow without finding a solution yet.
As I'm not sure if the sunspot-tags there are visited frequently, I thought I'd post it here as well.

I'm having a problem with a location based search which - as far as I see it - requires calculating and comparing a distance with a radius saved within the searched records.

The Setup

  • I have two models in my application: Viewers and Posts
  • Both viewers and posts have
    • A location specified by lat/lon fields
    • A radius represented by an integer value

The requested behaviour

  • Viewers may only see posts which are within their current search radius
  • Viewers may only see posts if they are within the post's radius. This is to provide a field of visibility for posts.

Basically, the following rules have to apply for a post to be displayed:

  post.radius   >= distance(post, viewer)
  viewer.radius >= distance(post, viewer)

The problem

The first rule is not too difficult to implement:

  class Post < ActiveRecord::Base
    searchable do
      integer :radius
      latlon(:location) { Sunspot::Util::Coordinates.new(latitude, longitude) }

  # PostsController
  Post.search do
    with(:location).in_radius(viewer.latitude, viewer.longitude, viewer.radius)

The second rule, however, would require that I am able to utilize the distance between the post and the viewer inside the solr query, e.g. with

  with(:radius).greater_than distance(:location, viewer.latitude, viewer.longitude)


As far as I see it, there is no way to achieve this with sunspot's built in methods.

Is solr even capable of handling queries like this?

If not, what might be a better solution to handle this problem?

Thanks in advance for any help (even it it's just a "Solr can't do that, sorry")!

Reply all
Reply to author
0 new messages