Using elasticsearch with Heroku | Adventures In Coding

Using elasticsearch with Heroku

  • Kevin Faustino
Heroku-logo

In my previous post, I wrote about how to integrate elasticsearch in a Ruby on Rails application. The next step after you have everything up and running is to deploy your app to production. I will detail how to do this via Heroku, since other deployment strategies have been well documented.

Bonsai ElasticSearch

Heroku has a wide variety of addons including Bonsai ElasticSearch. Bonsai allows you to have an elasticsearch server without having to write a single line of configuration. Add the addon to your application via the command-line:

$ heroku addons:add bonsai:test

Configuring Tire to work with Bonsai

Nick Zadrozny wrote a gist detailing a technique he used to use Bonsai in production and a local elasticsearch server for development.

To begin, we are going to create an initializer that sets a constant BONSAI_INDEX_NAME that will be used by our indexed model. First we determine if an environment variable is set for BONSAI_INDEX_URL. The BONSAI_INDEX_URL is the address of your Bonasi elasticsearch server. If present, we configure Tire to use http://index.bonsai.io as the base url for our elasticsearch calls and set our index name to the unique bonasi id found in the address. Otherwise, we use the technique described in my previous post to ensure a unique index per environment.

# config/initializers/bonsai.rb

if ENV['BONSAI_INDEX_URL']
  Tire.configure do
    url "http://index.bonsai.io"
  end
  BONSAI_INDEX_NAME = ENV['BONSAI_INDEX_URL'][/[^\/]+$/]
else
  app_name = Rails.application.class.parent_name.underscore.dasherize
  BONSAI_INDEX_NAME = "#{app_name}-#{Rails.env}"
end

Next update the index_name set on your indexed model to use BONSAI_INDEX_NAME.

class Post
  ...
  index_name BONSAI_INDEX_NAME
end

At this point, your application is ready for deployment to Heroku.

Indexing

Once you deploy your Heroku application, you must create and populate the elasticsearch index. We do this by running the Heroku console and entering the following code:

Post.create_elasticsearch_index # Post is our example model
Tire.index BONSAI_INDEX_NAME do 
   import Post.all
   refresh
 end

Once your index is in place, test your application on production to see if you are receiving search results.

Final Note

The Bonasi addon is in public beta at the time of writing. This is just a word of warning if you have a mission critical application and you wanted to try elasticsearch out.


Comments

blog comments powered by Disqus