Read more

Scoping a sunspot solr search by text using a string field

Andreas Robecke
August 31, 2012Software engineer

Assuming the following sunspot setup of the post class:

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

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Andreas Robecke to makandra dev (2012-08-31 11:57)