Last Updated: February 25, 2016
· juliobetta

Running a single instance of solr with multiple rails applications

Tested in Ubuntu Server 14.04

Installing java and maven3

sudo apt-add-repository ppa:andrei-pozolotin/maven3
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install maven3 oracle-java8-installer

Installing solr and granting folder permissions

git clone git://github.com/ksclarke/solr-jetty-maven.git
sudo mv solr-jetty-maven /opt/solr
sudo chown -R www-data:www-data /opt/solr

Running solr as service

Before anything, make sure to open the file /opt/solr/etc/init.d/solr and
change the value of the variable SOLR_HOME on line 31 to "/opt/solr".
Then, run the following commands:

sudo cp etc/init.d/solr /etc/init.d/solr
sudo update-rc.d -f solr start 80 2 3 4 5 . stop 30 0 1 6 .

Now, you should be able to start and stop the service:

sudo service solr start
sudo service solr stop

Configuring the Rails application

First of, you need to add sunspot gems to the Gemfile and run
bundle install:

# Gemfile
gem 'sunspot_rails'
gem 'sunspot_solr'

Then, run the following command to create the file sunspot.yml under the
config folder and the solr specific configurations:

rake sunspot_rails:install

Make sure to add the following entries to the .gitignore:

# Solr

Now, on the server side, for each application, you should create a solr core,
which will separate the indexes for each application. To do that, replace the contents of the file /opt/solr/src/main/resources/solr/solr.xml to:

<?xml version="1.0" encoding="UTF-8" ?>
<solr persistent="false">
  <cores adminPath="/admin/cores" host="${host:}" hostPort="${jetty.port:}">
  <core name="project01Core" instanceDir="/path_to_project_01/solr" dataDir="default"/>
  <core name="projectNCore" instanceDir="/path_to_project_n/solr" dataDir="default"/>


Now, open the file config/sunspot.yml on your rails application and change the
production property according to your server's configuration.

    hostname: localhost
    port: 8983
    path: /solr/default
    log_level: WARNING

If you're using Figaro or another .env gem, make sure to add the variable

Another solution is to create an initializer.

# config/initializers/sunspot.rb
if Rails.env.production?
    ENV['WEBSOLR_URL'] = 'http://localhost:8983/solr/yourCoreName'

To make another rails application use the same solr instance, add another core entry on the file /opt/solr/src/main/resources/solr/solr.xml, as described above, and set the properties according with the application's path.

Happy Searching!