Searching

Once you’ve got an index set up on your model, and have the Sphinx daemon running, then you can start to search, using a model named just that.

Article.search 'pancakes'

To focus a query on a specific field, you can use the :conditions option – much like in ActiveRecord:

Article.search :conditions => {:subject => 'pancakes'}

You can combine both field-specific queries and generic queries too:

Article.search 'pancakes', :conditions => {:subject => 'tasty'}

Please keep in mind that Sphinx does not support SQL comparison operators – it has its own query language. The :conditions option must be a hash, with each key a field and each value a string.

Filters on attributes can be defined using a similar syntax, but using the :with option.

Article.search 'pancakes', :with => {:author_id => @pat.id}

Filters have the advantage over focusing on specific fields in that they accept arrays and ranges:

Article.search 'pancakes', :with => {
  :created_at => 1.week.ago..Time.now,
  :author_id  => @fab_four.collect { |author| author.id }
}

And of course, you can mix and match global terms, field-specific terms, and filters:

Article.search 'pancakes',
  :conditions => {:subject => 'tasty'},
  :with       => {:created_at => 1.week.ago..Time.now}

Pagination

Sphinx paginates search results by default. Indeed, there’s no way to turn it off (but you can request really big pages should you wish). The parameters for pagination in Thinking Sphinx are exactly the same as Will Paginate: :page and :per_page.

Article.search 'pancakes', :page => params[:page], :per_page => 42

The output of search results can be used with Will Paginate’s view helper as well, just to keep things nice and easy.

# in the controller:
@articles = Article.search 'pancakes'

# in the view:
will_paginate @articles