Scoping a sunspot solr search by text using a string field

Updated . Posted . Visible to the public.

Assuming the following sunspot setup of the post class:

class Post < ActiveRecord::Base
  searchable do
    text :title
    string :state
    integer :category_ids
  end
end

In Sunspot you can scope your search via the with method. It allows you to do stuff like:

Post.search {
  fulltext "your query", :fields => :title
  with(:category_ids).any_of([1,2,3,4,5])
}

If you want to scope your search based on a text field, you have to add another field of the type string (such as the state field above). It is not possible to scope based on a field of the type text! The difference is that text fields get tokenized for the fulltext search and string fields do not. For further explanation checkout the sunspot wiki Show archive.org snapshot . By the way, this is also possible if you already have added the same field as a text field.

Therefore, with the state field above you can scope like this:

Post.search {
  fulltext "your query", :fields => :title, :minimum_match => 0
  with(:state).any_of(['purchased', 'published'])
}

In the sunspot wiki Show archive.org snapshot you can also read further about scoping.

Last edit
License
Source code in this card is licensed under the MIT License.
Posted to makandra dev (2012-08-31 09:57)