Fork me on GitHub

Back Home

Sunspot Full-text Search for Rails/Ruby

by Phil McClure

Sunspot

I had the recent pleasure of using Sunspot, which is powered by Apache Solr, to provide full-text search functionality for a Ruby on Rails recent project.

Installation/Configuration

Installing Sunspot is reasonably simple. I installed the Sunspot gems along with the related Sunspot Rails Plugin, with the following commands:-

Sunspot gems

sudo gem install outoftime-sunspot outoftime-sunspot_rails --source=http://gems.github.com

Sunspot Rails Plugin

script/plugin install git://github.com/outoftime/sunspot_rails.git

Note that you will need to require the relevant library in the Rakefile which is in the base directory in your Rails app:-

require 'sunspot/rails/tasks'

Now you can generate the sunspot yaml configuration file with the built in generator:-

script/generate sunspot

This creates a sunspot.yml file in the rails config directory (more on this later).

Indexing Fields in your Models

Sunspot, in comparison to the alternatives, has really clean and clear syntax for defining indexed fields in the model. Here's an example:-

Here we can index string and text fields, or integer foreign keys or even foreign keys of a joining table. Full-text searching is performed against the text fields and filtering can be performed against the other fields, in the controller, like this:-

Then rendered in the view, like this:-

Development Server

You can start the sunspot/solr server in a development environment by using a built-in rake task, just key the following command:-

rake sunspot:solr:start

Production Server

While the rake task is great for development, it is not recommended for a production environment. To start the sunspot/solr server in production use this command:-

sunspot-solr start -- -p 8983 -d data/solr/myapp

This starts a daemon process on the server. You can check that the process is running by going to http://hostname:8983/data/solr/myapp.

You may be wondering how your Rails app knows to look in this location. Remember the sunspot.yml file in the config directory?... That's where!

Pitfalls

Links


blog comments powered by Disqus
© 2009 Phil McClure This site was developed using Compass, Blueprint and Ruby on Rails - Much thanks to these guys!