Integrating ElasticSearch Into a Rails App

We can spend hours handcrafting those perfect SQL queries and there are a lot of times where that may be preferable. There are times, however when we can rely on the beautiful Rails community to have done a lot of the heavy lifting for us. This is one of those times.

We’ll need two things to integrate an awesome search engine into our Rails app. First is the Searchkick gem. This will allow Elasitcsearch to communicate to ActiveRecord and our models. We need to add this gem to our gemfile and run bundler.

gem 'searchkick'

Second is installing Elasticsearch. There are a few ways to go about this. If our app is still in the development stages, installing it locally is a very good option. Install it from here.

Next up we’ll need to fire up the Elasticsearch server locally. By default it should fire on localhost:9200. In my case, on Linux, the command looks something like this.

sudo service elasticsearch start

After this we need to work on the model we’d like to search. In this case it’s a Client model. We include searchkick as part of the model. Then we write a search_data method that will have any model table columns we’d like to be included in our search params.

class Client < ApplicationRecord  searchkick  def search_data    {      name: name,       email: email,      phone: phone,      id: id,      postal_code: postal_code,      company_id: company_id    }   endend

Then we work on our controller.

class ClientsController < ApplicationController  def index    search = params[:term].present? ? params[:term] : nil    @clients = search  endend

Only two steps left. We have to create a search box in our view. Something along these lines should work. This code depends on having bootstrap integrated into the app. If bootstrap isn’t being used, edit the classes accordingly.

<%= form_tag(clients_path, method: :get, class: "form-inline", role: 'search') do %>  <div class="input-group">    <%= text_field_tag :term,        params[:term],        id: 'clients_search',        autocomplete: :off,        placeholder: 'Search',        class: 'form-control' %>  <div class="input-group-btn search-panel">   <%= submit_tag 'Search', name: nil, class: "btn btn-secondary" %>  </div>  </div><% end %>

Last but not least, we need to actually ask Searchkick to index our model. In the Rails console, run the following command. Any time we change the search_data method to add or delete columns, the model will have to be indexed again.


Quick, easy and painless. We now have an incredibly powerful search model integrated into our Rails app.