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 money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
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)