Algolia Search for Rails

This gem let you easily integrate the Algolia Search API to your favorite ORM. It's based on the algoliasearch-client-ruby gem.

Build Status Gem Version Code Climate

Table of Content

Get started

  1. Install
  2. Setup
  3. Quick Start
  4. Options
  5. Indexing
  6. Search settings
  7. Typeahead UI
  8. Note on testing

Install

gem install algoliasearch-rails

If you are using Rails 3, add the gem to your Gemfile:

gem "algoliasearch-rails"

And run:

bundle install

Setup

Create a new file config/initializers/algoliasearch.rb to setup your APPLICATION_ID and API_KEY.

AlgoliaSearch.configuration = { application_id: 'YourApplicationID', api_key: 'YourAPIKey' }

We support both will_paginate and kaminari as pagination backend. For example to use :will_paginate, specify the :pagination_backend as follow:

AlgoliaSearch.configuration = { application_id: 'YourApplicationID', api_key: 'YourAPIKey', pagination_backend: :will_paginate }

Quick Start

The following code will create a Contact index and add search capabilities to your Contact model:

class Contact < ActiveRecord::Base
  include AlgoliaSearch

  algoliasearch do
    attribute :first_name, :last_name, :email
  end
end

You can either specify the attributes to send (here we restrict to :first_name, :last_name, :email) or not (in that case, all attributes are sent).

class Product < ActiveRecord::Base
  include AlgoliaSearch

  algoliasearch do
    # all attributes will be sent
  end
end
p Contact.search("jon doe")

Options

Each time a record is saved; it will be - asynchronously - indexed. In the other hand, each time a record is destroyed, it will be - asynchronoulsy - removed from the index.

You can disable auto-indexing and auto-removing setting the following options:

class Contact < ActiveRecord::Base
  include AlgoliaSearch

  algoliasearch auto_index: false, auto_remove: false do
    attribute :first_name, :last_name, :email
  end
end

You can force indexing and removing to be synchronous by setting the following option:

class Contact < ActiveRecord::Base
  include AlgoliaSearch

  algoliasearch synchronous: true do
    attribute :first_name, :last_name, :email
  end
end

You can force the index name using the following option:

class Contact < ActiveRecord::Base
  include AlgoliaSearch

  algoliasearch index_name: "MyCustomName" do
    attribute :first_name, :last_name, :email
  end
end

You can suffix the index name with the current Rails environment using the following option:

class Contact < ActiveRecord::Base
  include AlgoliaSearch

  algoliasearch per_environment: true do # index name will be "Contact_#{Rails.env}"
    attribute :first_name, :last_name, :email
  end
end

Indexing

You can trigger indexing using the index! instance method.

c = Contact.create!(params[:contact])
c.index!

And trigger index removing using the remove_from_index! instance method.

c.remove_from_index!
c.destroy

To reindex all your records, use the reindex! class method:

Contact.reindex!

To clear an index, use the clear_index! class method:

Contact.clear_index!

Search settings

All settings can be specified either statically in your model or dynamically at search time using search options:

class Contact < ActiveRecord::Base
  include AlgoliaSearch

  algoliasearch do
    attribute :first_name, :last_name, :email
    minWordSizeForApprox1 2
    minWordSizeForApprox2 5
    hitsPerPage 42
  end
end
p Contact.search("jon doe", hitsPerPage: 5, page: 2)

Typeahead UI

Require algolia/algoliasearch.min (see algoliasearch-client-js) and algolia/typeahead.js (a modified version of typeahead.js with custom transports, see the pull request) somewhere in your JavaScript manifest, for example in application.js if you are using Rails 3.1+:

//= require algolia/algoliasearch.min
//= require algolia/typeahead.min

We recommend the usage of hogan, a JavaScript templating engine from Twitter.

//= require hogan

Turns any input[type="text"] element into a typeahead, for example:

<input name="email" placeholder="[email protected]" id="user_email" />
<script type="text/javascript">
  $(document).ready(function() {
    var client = new AlgoliaSearch('YourApplicationID', 'SearchOnlyApplicationKey');
    $('input#user_email').typeahead({
      name: 'emails',
      remote: client.initIndex('#{Contact.index_name}').getTypeaheadTransport(),
      engine: Hogan,
      template: '{{{_highlightResult.email.value}}} ({{{_highlightResult.first_name.value}}} {{{_highlightResult.last_name.value}}})',
      valueKey: 'email'
    });
  });
</script>

Note on testing

To run the specs, please set the ALGOLIA_APPLICATION_ID and ALGOLIA_API_KEY environment variables. Since the tests are creating and removing indexes, DO NOT use your production account.