Search code examples
ruby-on-railssolrsunspotfacetsunspot-solr

Sunspot facet query with exclude option and any_of fields


After researching for a good amount of time, finally writing this.

I am doing a solr query to find all the records that have specific object_id and also another field which tells active/inactive. And then need to get the counts that are active and as well as total count (that includes active/inactive and also belongs to specified object_ids)

Model.search() do
  with(:object_id, params[:ids])
  active_condition = with(:active, true)
  facet(:object_id, exclude: active_condition)
end

This is returning all the records. But, the requirement is to fetch the count that are belongs to only specific object_ids and also both active/inactive.

Is it possible to get the counts with this approach ?


Solution

  • You need to facet on the active field instead:

    Model.search() do
      with(:object_id, params[:ids])
      active_condition = with(:active, true)
    
      facet(:active, exclude: active_condition)
    end
    

    This returns the active and inactive counts of the object_ids you scoped on.