:neil_middleton

Ruby on Rails, Web Application Development and bollocks extraordinaire 
« Back to blog

Full Text Search in Rails with Thinking Sphinx

These days there's a common requirement to be searching data in a way that's not just a simple find query. People want to search against text, and do weird and wonderful things like fuzzy searching.  As I've been blogging about Rails a fair amount recently in a "Look Ma! I just figured this out!" way, I thought I would talk about how this could be done.  The requirement I have is to search property in a model that consists of text and  search it in as flexible way as possible (a LIKE just won't suffice here)

First up, I'm talking about using MySQL, so this probably won't apply to PostgreSQL or anything else.  Secondly, I'm also running this on Ubuntu Hardy in production and developing it on OS X 10.6.3.  If you're using Windows or similar to try and implement this, good luck.  You're on your own.

First up, I'm looking at using Sphinx, the full-text search engine.  The reason for this is that seems to be the most widely used and has a couple of nice gems out there for dealing with it in the shape of ThinkingSphinx and UltraSphinx.  For this project I'm using ThinkingSphinx due to the reasons laid out by Rein Henrichs from HashRocket back in 2008.

Once you've installed Sphinx and ThinkingSphinx int your application, you need to think about what you want to search.  In my case I only have one thing to worry about so I just need to define that in my model (the property I want to search is called 'goals'):

Simple.  Next up, I need to tell Sphinx to index the data I have in my database with a simple rake call, and then I need to fire up the sphinx process:

(Note that you can ignore the error about skipping the model - it's a Sphinx thing.

Next, is where you need to....do nothing - you're done.  You can now search your model with a string and get results back...

Now, obviously this is a very very high level overview on how to get started, so your best bet is to check up on the documentation, there's loads more info there.

Comments (0)

Leave a comment...