Solr is an open source search platform from Apache. It has a very powerful full-text search capability among other things.
Solr is written in Java. And it runs as a standalone search server within a servlet container like Tomcat. When you are working on a Ruby on Rails application you do not want to maintain Tomcat server. This is where websolr comes in picture. Websolr manages the index and the Rails application interacts with index using a gem called sunspot-rails .
Here I am interested in searching products.
1 2 3 4 5 6
Using sunspot gem
Above command creates
config/sunspot.yml file. By default this file looks like following.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
The way sunspot works is that after every single web request it updates
solr about the changes that took place in the request. This is not
desirable. To turn that off add
option to false in the
I would also change the
log_level for development to
DEBUG . The revised
config/sunspot.yml file would look
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Taking care of callbacks
In the above case anytime I create, update or destroy a product then as
after_save callback solr commit commands are issued.
after_save callbacks are part of ActiveRecord
transaction, this slows up the create, update and destroy operation. I
like all these operations to happen in background.
Here is how I handled it
1 2 3 4 5 6 7 8 9
In the above case I used Delayed Job but you can use any background job processing tool.
In case of Delayed Job the higher the priority value the less is the priority. By bumping the priority value to 50, I’m making sure that emails and other background jobs are processed before solr work is taken up.
Problem with remove_from_index
In the above case the call to
remove_from_index has been
deferred to Delayed Job. However the record has already been destroyed.
So when Delayed Job takes up the work it first tries to retrieve the
record. However the record is missing and the background job fails.
Here is how we solved this problem.
1 2 3 4 5 6 7 8 9 10 11 12 13
Add another worker named
1 2 3 4 5 6 7 8 9
Connecting to websolr
From the websolr documentation it was not clear that the
sunspot gem first looks for an environment variable called
WEBSOLR_URL and if that envrionment variable has a value then
sunspot assumes that the solr index is at that url. If no value is found
then it assumes that it is dealing with local solr instance.
So if you are using websolr then make sure that your application has
WEBSOLR_URL properly configured in
staging and in production environment.