Rails: How to index SearchKick on Heroku with Bonsai

You might have followed this lovely tutorial to add the even lovelier SearchKick gem to your Rails app: https://shellycloud.com/blog/2013/10/adding-search-and-autocomplete-to-a-rails-app-with-elasticsearch

But, if you’re like me, you got a little stuck when deploying to Heroku. 

First, SearchKick is a gem that uses Elasticsearch and you did start by installing Elasticsearch. Bonsai’s first tier is free, so it’s a good option if you’re already using Heroku. But, when you follow the Bonsai setup instructions on Heroku, you might be confused as to why you need to add the elasticsearch-rails gem, the elasticsearch-model gem, and the bonsai-elasticsearch-rails gem to your app. You don’t need these! You have SearchKick, which has Elasticsearch in it. 

You do, however, need a file called config/initializers/bonsai.rb

if ENV[‘BONSAI_URL’]
     Searchkick.client = Elasticsearch::Client.new({url: ENV[‘BONSAI_URL’], logs: true})
end

Then, once deployed, you just need to run: 

heroku run rake searchkick:reindex:all

to index. And you’re done!

Thanks to Heroku Support for pointing out that I was using two different Elasticsearch clients and mixing up the console commands 🙂

PS: If you’re using erb, not slim, like in the tutorial linked above, this is what you’ll want in your view:

<%= form_tag users_path, class: “form-inline”, :method => :get do %>
<div class=“input-group input-group-lg”>
<% if params[:query].present? %>
<div class=“input-group-btn”>
<%= link_to “clear”, users_path, class: “btn btn-default” %>
</div>
<% else %>
<%= text_field_tag :query, params[:query], id: “user_search”, class: “form-control”, autocomplete: “off” %>
<div class=“input-group-btn”>
<%= submit_tag “Search”, class: “btn btn-default” %>
</div>
<% end %>
</div>
<% end %>