Algolia search is a "cloud search as a service" provider. You can beam up your data to their API and Algolia provides a hosted search service API in return. This makes creating a search results page in your application very easy. Their pricing is very reasonable, and they provide free accounts with some limits.

Prerequisities

This tutorial is meant to keep things very simple and get you on the road to having a search results page set up on your site. There are a few prerequisities:

- Set up a new Algolia account by going to their Sign Up page.

- Once registered, grab your API keys from their API keys management page in the Administrator dashboard. The credentials you will need for the purpose of this tutorial are the Application ID and the Admin API Key (full API access is needed to during the seeding / indexing process):

- I am using Rails 5 which means that traditional rake commands can be called via rails db:seed instead of rake db:seed

- Finally you'll need a Rails model like BlogPost, Product etc, and some actual data, otherwise the search results page will be severly lacking!

Let's get started

Firstly we will need to create the search box that will receive the users input for their searches of your site! Create a new partial view called _search-box.html.erb and place it in a relevant view directory. Next up, populate this view with the below HTML:

# app/views/layouts/_search-box.html.erb
<div class="search-box">
    <%= form_tag("/search", method: "get") do %>
      <%= text_field_tag :q, nil, placeholder:'Search the site' %>
      <%= submit_tag("Search") %>
    <% end %>
</div>

And include the partial in your main layout file:

# app/views/layouts/application.html.erb
<%= render partial: 'layouts/search-box' %>

Next up, we need to create a new controller for the search results page that will do all of the Algolia search processing. Run the command below on the command line in the root of your application's directory:

rails g controller Search index

Rails will generate the new controller and associated assets for you.

Open up the search_controller.rb file located in the app/controllers directory. It should look like this:

# app/controllers/search_controller.rb
class SearchController < ApplicationController
  def index
     # Nothing here yet!
  end
end

We now need to make the index action do something useful. First we will need to install Algolia using Bundler. Add the line below into your Gemfile:

# Gemfile
gem 'algoliasearch-rails'

Next up, run:

bundle

In the config/initializers directory, create a new file called algoliasearch.rb and populate it with the below initialization code, replacing XXX with the relevant credentials retrieved from Algolia's API key dashboard:

# config/initializers/algoliasearch.rb
AlgoliaSearch.configuration = { application_id: 'XXX', api_key: 'XXX' }

Now we need to populate our Algolia search account with some data. For the purposes of this tutorial, I will just be using the Rails seeds.rb file located in db/ to populate the Algolia index with data. We can differentiate between different Rails environments by switching on Rails.env so you can populate the index with test data or you can just index your existing production data. 

The code below is a very simple script to do just that. Just replace Article  with the relevant Rails model that you would like to be indexed. Comment in the Article.reindex!  line in the "development" block if you want to index some test data whilst getting this all setup:

# db/seeds.rb
case Rails.env
when "development"
    # Seed database with test data
    # Article.reindex!
when "production"
    # Index all articles with the Algolia API
    Article.reindex!
end

Once you've modified the script accordingly, we need to indicate to Algolia what data we want to be included when we upload the data to their API. So navigate to app/models/your-model.rb and make the below modifications to your model:

# app/models/article.rb
class Article < ApplicationRecord
    # Include the Rails Algolia search gem's functionality
    include AlgoliaSearch

    # search fields for algolia
    algoliasearch do
        # Change these to the attributes you would like to be included
        attributes :title, :content
        # Change these to the attribute names you would like to be indexed
        attributesToIndex ['title', 'content']
        # Indicate an attribute to order results by should two records text relevancy be equal (optional)
        customRanking ['desc(created_at)']
    end
end

Once you've done this, hop back onto the command line and run the seed script to index all of your model data with Algolia:

rails db:seed

If you want to index your Heroku production database:

heroku run rails db:seed

Now if you hop back onto the Algolia dashboard, you should see that an indexing operation has begun. Check to ensure that you have received 200 status codes for the indexing operations:

Now we have verified that the data is being indexed and has been beamed up to Algolia, we can focus on getting the search results element working. Next up, open up the new Search controller we created earlier in the tutorial. We are going to modify the index action so that it pulls back records from the Algolia API based on a query term.

Populate the empty index action with the below code, ensuring that you replace the model name Article with the name of the model that you opted to be indexed with Algolia:

# app/controllers/search_controller.rb
def index
   @q = params['q']
   return if @q.blank?
   @hits = Article.algolia_search(@q)
end

Finally we need to populate our search results view with some HTML. I kept it fairly simple. In the views/search/index.html.erb file, paste the below HTML code:

# app/views/search/index.html.erb
<div class="search-results">
    <h1>Search results</h1>
    <p>
        <span class="faded">There are <%= @hits.count %> results for "<%= @q %>"</span>
    </p>
    <% if @hits %>
      <div class="hits">
          <% @hits.each do |hit| %>
            <div class="hit">
              <div class="hit-date">
                  <%= raw(hit["created_at"].strftime('%b %d,<br/> %Y')) %>
              </div>
              <div class="hit-link">
                  <%= link_to hit['title'], article_path(hit) %>
              </div>
            </div>
          <% end %>
      </div>
    <% end %>
</div>

Modify this as you see fit. Your models will most definitely have different properties on them so hit['title'] may not apply.

Finally, modify config/routes.rb to include the new search route in your routing:

# config/routes.rb
Rails.application.routes.draw do
  get 'search' => 'search#index'
end

Now you should be able to load up your search results page by going to the url http://localhost:3000/search?q=hello

If there are no results showing, the first port of call would be to go into your Algolia dashboard to check that the query calls and indexing calls to their API have succeeded.

Final note

This is just a very simple way of getting a basic search results page set up on your website. There may be better wins to be had with Algolia, but for 15-30 mins development time spent on this, I'd say this is pretty good.