Configure Sphinx in Rails application

Install Sphinx

Just run the following three commands on your server or dev machine to install Sphinx:

./configure make sudo make install

That will setup Sphinx with default for use with MySQL. If you want to use it with PostgreSQL, then run configure with the following flag:

./configure –with-pgsql

Note: you can download the sphinx from

Install Thinking Sphinx

Even though there are a couple of Sphinx plugins for Rails, I chose to go with Thinking Sphinx, as it seems to be the most popular and feature complete.

So you can install it as a Rails plugin using script/plugin install command:

script/plugin install git://

Writing code to use sphinx search:

We now need to index our models. This consists of adding a few small lines of code into each model that you want to be able to search. So let’s say we have a Blog app (doesn’t everyone!), which has a Post model. And that Post model contains the usual title and description fields. We therefore add the following bit of code beneath our association declarations in


define_index do indexes title, description end

Those very short three lines will tell Thinking Sphinx to index the title and description fields of the Post model, and allow us to search through all our posts. Now we just need to index and start Sphinx. And Thinking Sphinx makes this very easy with its handy Rake tasks.

Just run this:

rake ts:rebuild

That will stop (if it is started), index and start Sphinx for you. Now we need to create a quick search form. This will eventually be a global site search, and not just a Post search. So we will create a new controller:

script/generate controller search

Then create a view at app/views/search/index.html.erb and place the form within it:

Now in your new Search controller, create a new createaction:

def create @posts = params[:search] end

Create your createview at app/views/search/create.html.erbwith a bit of code to display your @postsin the usual way.

Note: We can even paginate our results using the WillPaginate plugin:

def create

@posts = params[:search], :page => params[:page], :per_page => 10



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s