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.
Using sunspot gem
Above command creates
config/sunspot.yml file. By default this file looks like following.
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
auto_commit_after_request option to false in the
I would also change the
log_level for development to
DEBUG . The revised
config/sunspot.yml file would look like
Taking care of callbacks
In the above case anytime I create, update or destroy a product then as part of
after_save callback solr commit commands are issued. Since
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
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.
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.
Add another worker named
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 environment 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 environment variable
WEBSOLR_URL properly configured in staging and in production environment.