A Quick Guide to Getting Setup with Thinking Sphinx

Firstly, you’ll need to install both Sphinx and Thinking Sphinx. While Sphinx is compiling, go read what the difference is between fields and attributes for Sphinx is. It’s important stuff.

Once that’s all done, it’s time to set up an index on your model. In the example below, we’re assuming the model is the Article class.

class Article < ActiveRecord::Base
  # ...
  
  define_index do
    # fields
    indexes subject, :sortable => true
    indexes content
    indexes author.name, :as => :author, :sortable => true
    
    # attributes
    has author_id, created_at, updated_at
  end
  
  # ...
end

Please don’t forget that fields and attributes must reference columns from your model database tables, not methods. Sphinx talks directly to your database when indexing, and so the logic in your models doesn’t have any impact.

The next step is to index your data:

rake thinking_sphinx:index

You will see a warning like the following – it’s safe to ignore, it’s just Sphinx being overly fussy.

distributed index 'article' can not be directly indexed; skipping.

Once that’s done, let’s fire Sphinx up so we can query against it:

rake thinking_sphinx:start

And now we can search!

Article.search "topical issue"
Article.search "something", :order => :created_at,
  :sort_mode => :desc
Article.search "everything", :with => {:author_id => 5}
Article.search :conditions => {:subject => "Sphinx"}

Of course, that’s an extremely simple overview. It’s definitely worth reading some more for a better understanding of the best ways to index and search.