Search code examples
ruby-on-rails-3sunspotsunspot-rails

Faceted Search with Sunspot


I'm trying to implement faceted search with Sunspot, but I must be doing something wrong.

class Product < ActiveRecord::Base
  attr_accessible :category, :color, :condition, :item_no, :size
  searchable do
    text :color, :size
  end
end

This is my product model, i want to have a menu on the side of the navigation which will allow to filter results by using category, color, condition etc.

In my controller i have:

 def index

    @search = Product.search do
      fulltext params[:search]
      facet :color
    end
    @products = @search.results

    respond_to do |format|
      format.html
      format.json { render json: @products }
    end
  end

But i keep getting an error that says:

Sunspot::UnrecognizedFieldError 
No field configured for Product with name 'color'

In the view I have:

<div id="facets">
  <h3>Category</h3>
  <ul>
    <% for row in @search.facet(:color).rows %>
      <li>
        <% if params[:color].blank? %>
          <%= link_to row.value, :color => row.value %> (<%= row.count %>)
        <% else %>
          <strong><%= row.value %></strong> (<%= link_to "remove", :color => nil %>)
        <% end %>
      </li>
    <% end %>
  </ul>
</div>

Can anyone point what to what I'm doing wrong?

Thanks a lot for the help!

Update: This is a piece of the trace of the error.

sunspot (1.3.3) lib/sunspot/query/restriction.rb:245:in `to_solr_conditional'
sunspot (1.3.3) lib/sunspot/query/restriction.rb:92:in `to_positive_boolean_phrase'
sunspot (1.3.3) lib/sunspot/query/restriction.rb:72:in `to_boolean_phrase'
sunspot (1.3.3) lib/sunspot/query/filter.rb:11:in `to_filter_query'
sunspot (1.3.3) lib/sunspot/query/scope.rb:5:in `block in to_params'
sunspot (1.3.3) lib/sunspot/query/scope.rb:5:in `map'
sunspot (1.3.3) lib/sunspot/query/scope.rb:5:in `to_params'
sunspot (1.3.3) lib/sunspot/query/common_query.rb:51:in `block in to_params'
sunspot (1.3.3) lib/sunspot/query/common_query.rb:50:in `each'
sunspot (1.3.3) lib/sunspot/query/common_query.rb:50:in `to_params'
sunspot (1.3.3) lib/sunspot/search/abstract_search.rb:37:in `execute'
sunspot_rails (1.3.3) lib/sunspot/rails/searchable.rb:329:in `solr_execute_search'
sunspot_rails (1.3.3) lib/sunspot/rails/searchable.rb:153:in `solr_search'

Solution

  • Two things missing here. First, you need to include the color as a field, and second, the facet method tells sunspot (i.e., solr) to return all the facets that are present in the result set, but not to scope the query by that facet. So, you need something like:

    searchable do
      text :color, :size
      string :color
    end
    
    
    @search = Product.search do
      fulltext params[:search]
      with(:color).all_of(params[:color]) unless params[:color].blank?
      facet :color
    end