Steps to Install Elastic Search in a Rails 5.1 Application

Feature thumb snip20170703 6

This guide assumes that you're using Rails 5.1 and have deployed to Heroku with the Searchbox Elastic Search add on.


Step 1

Install the gems and run bundle install:

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


Step 2

Add this code to the models that you want to add the search feature to:

include Elasticsearch::Model
include Elasticsearch::Model::Callbacks


Step 3

Update the config/application.rb file and include this line inside of the application class definition:

Elasticsearch::Model.client = host: ENV['SEARCHBOX_URL']


Step 4

Now you need to create an index for the model(s) that you want to be searchable, you can do this from the Rails console:

<ModelName>.__elasticsearch__.create_index! force: true


After you have created the index, this only creates it from this point on. It does not retroactively add historical records to the index. (See step 6 if you have historical records that you need to index)


Step 5

Now you can run queries like this:'some word or phrase').records


And it will return the records that match that query. This code can be placed in your controller and be taken from traditional text boxes.


Optional Step 6

If you are adding Elastic Search to an application with historical records, you will need to add each record to the index, you can do it with a script like this:

Post.all.each do |post|