A glimpse to Solr (with Rails, of course!)
I’ve recently published an article for the italian webzine HTML.it on using Solr within a Rails application.
Basically Solr is a search engine that you can “embed” in your Rails application through a nice plugin acts_as_solr.
After installing the plugin, and started the solr server (rake solr:start) you should define what model in your app fall under solr control and on which fields.
Let’s see some (simple) code.
class Recipe < ActiveRecord::Base
has_and_belongs_to_many :tags
has_and_belongs_to_many :ingredients
validates_presence_of :name
validates_presence_of :description
validates_presence_of :preparation_time
acts_as_solr :fields => [:name, :description],
:include => [:ingredients, :tags]
end
Now we are able to find recipe objects with Solr facility:
results = Recipe.find_by_solr('tomato')
recipes_related_to_tomato = results.docs
Simple, isn’t it?
Of course things can go more exciting:
results = Recipe.multi_solr_search('tomato OR apple',
:models => [Tag, Ingredient])
objects_related_to_tomato_or_apple = results.docs
Finally, don’t forget to rebuild your Solr indexes when appropriate:
Recipe.rebuild_solr_index
Happy searching! ;)
