How To Setup Elasticsearch In Your Rails Application In Development

August 16, 2014

Step 1 – Install elasticsearch

If you haven’t installed elasticsearch on your local development machine, this article tells you how to do so in Linux

Step 2 – Add the right ruby gems for the Ruby elasticsearch client in your Gemfile and bundle install

gem 'elasticsearch-rails'
gem 'elasticsearch-model'
gem 'elasticsearch-extensions'

Step 3 – Configure indexes in your Rails model(s)

class User < ActiveRecord::Base
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks
  settings index: { number_of_shards: 2 } do
    mappings dynamic: 'false' do
      indexes :name, analyzer: 'english', index_options: 'offsets'
      indexes :email, analyzer: 'english', index_options: 'offsets'
      indexes :hobbies, analyzer: 'english', index_options: 'offsets'
    end
  end
  def self.search_users(search_words)
    User.import
    response = User.search(
      size: 20,
      query: {
            match: {
                "_all" => {
                  "query" => search_words,
                  "operator" => "or"
                }
            }
        }
    )
    response.records
  end
end

Step 4 – Create / refresh the index

Start up the rails console in development mode and issue the following commands:

User.__elasticsearch__.create_index! force: true
User.__elasticsearch__.refresh_index!

These commands will setup a search index with your desired configuration in the User model above. If you ever change your settings, you’ll need to reissue these commands. I hope to come back and update these instructions with a more automated process soon.

Choosing the query type

In the User model, I called the search method on the User model to return 20 results (see the size: 20 setting). The _all keyword tells elasticsearch to match all documents using the query search_words and “or” logic. For example if search_words is “Joe Smith”, elasticsearch searches for documents with the words Joe OR Smith. The query I use above should provide you what you need for simple searches.


Profile picture

Written by Bruce Park who lives and works in the USA building useful things. He is sometimes around on Twitter.