Search code examples
ruby-on-railsrubysolrsunspot

Add/minus facets rails


Hi I'm a new rails developer using sunspot and solr.

Here's my searchable block:

searchable do
  text :name, :boost => 10
  text :description
  text :tags do
    tags.map(&:name)
  end
  text :ingredients do
    ingredients.map(&:ingredient)
  end
  string :ingredients, :multiple => true do 
    ingredients.map(&:ingredient)
  end
  string :user
end

and my controller:

@search = Recipe.search do |query|
  query.fulltext params[:search]
  query.paginate(:page => params[:page] || 1, :per_page => 20)
end
@recipes = @search.results

I'm building a recipe search engine. Basically, right now I have it so that you can search for the name of the recipe, ingredients, and tags associated with a recipe and have matching recipes show up.

But as you can see I'm also trying to create a faceted search on ingredients, which I have already made strings.

My goal is to be able to search for a recipe, like you can now, but have it so that if you add a plus symbol then an ingredient following, that it facets the search, and likewise for the minus symbol. So for example here's a query:

Chicken Piccata +lemon  => searches for chicken piccata with lemon
Chicken Piccata -lemon  => searches for chicken piccata without lemon

I've been trying on something like this:

with(:ingredients, params[:ingredients]) if params[:ingredients].present?

but I have no idea how to deal with the +/- side of it. How could I accomplish this?

Thanks for all help!


Solution

  • Not sure for Sunspot query creation, However ....
    Solr supports boolean operators, so NOT (-) is supported which will return results which do not have the word.

    So Chicken Piccata lemon -> With default operator AND, should return back all the results with

    Also, Solr supports NOT operator so Chicken Piccata -lemon, would get interpreted as all results which do not have lemon in the contents.

    You can also query -ingredients:lemon so exclude the results.