How to do an OR query with rails sunspot for rsolr

125 views Asked by At

I'm having trouble finding an example of how to do an OR query with sunspot. Here's my code.

class JobSearch < ActiveRecord::Base
  monetize :salary, as: 'salary', allow_nil: true
  DEFAULT_DISTANCE_IN_MILES = 50

  def search(page, page_size)
    latitude, longitude = LatitudeLongitudeLookup.latitude_longitude_from_string(location) if location.present?
    Job.search(include: [:state]) do
      facet(:minimum_compensation_cents) do
        row(150000..Float::INFINITY) do
          with(:minimum_compensation_cents).greater_than(150000)
        end
        row(100000..149999) do
          with(:minimum_compensation_cents, 100000..149999)
        end
        row(50000..99999) do
          with(:minimum_compensation_cents, 50000..99999)
        end
        row(25000..49999) do
          with(:minimum_compensation_cents, 25000..49999)
        end
      end

      facet :titles, limit: 5
      facet :city_state, limit: 5
      facet :job_type
      facet :work_remotely

      if !include_remote
        with(:location).in_radius(latitude, longitude, DEFAULT_DISTANCE_IN_MILES, bbox: true) if latitude && longitude
      else #need to do a location with an OR include_remote
        with(:location).in_radius(latitude, longitude, DEFAULT_DISTANCE_IN_MILES, bbox: true) if latitude && longitude
        #OR - how to do that?
        with(:work_remotely, true)
      end

      with(:city_state, location) if location.present? && (!latitude && !longitude)
      order_by_geodist(:location, latitude, longitude) if latitude && longitude
      with(:job_type, job_type) if job_type.present?
      with(:titles, position_title) if position_title.present?

      if !latitude && !longitude && !include_remote 
        with(:work_remotely, include_remote)
      end

      fulltext keyword
      paginate page: page, per_page: page_size
    end
  end
end

What I need to do is is directly under the facet section if they have searched on a location and also indicated to include remote jobs, the query should be something like "where location=locationsearchtext OR work_remotely=true". So, how do you construct that with sunspot? Thanks.

1

There are 1 answers

11
AmitejKalra On BEST ANSWER

This is what you need to do:

facet :work_remotely

      if !include_remote
        with(:location).in_radius(latitude, longitude, DEFAULT_DISTANCE_IN_MILES, bbox: true) if latitude && longitude
      else #need to do a location with an OR include_remote
        any_of do
          with(:location).in_radius(latitude, longitude, DEFAULT_DISTANCE_IN_MILES, bbox: true) if latitude && longitude
          with(:work_remotely, true)
        end
      end

You can find out more information on the sunspot wiki: https://github.com/sunspot/sunspot/wiki/Scoping-by-attribute-fields#disjunctions-and-conjunctions