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 //sphinxsearch.com/downloads//

Install Thinking Sphinx

Even though there are a couple of Sphinx in  Rails application, 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://github.com/freelancing-god/thinking-sphinx.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 lets 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

app/models/post.rb:
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 it’s 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 create action:

def create @posts = Post.search params[:search] end

Create your create view at app/views/search/create.html.erb with a bit of code to display your @posts in the usual way.

Note:

We can even paginate our results using the WillPaginate plugin:

def create

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

Get in touch with us.

Save

Leave a Comment

Your email address will not be published. Required fields are marked *