How to integrate elasticsearch with rails application specifically using "Elasticsearch" gem
For a very basic quick start of the elastic's github gem for model indexing you could do the following in development environment with elasticsearch running on localhost:9200
in Gemfile:
gem 'elasticsearch-model'
then run on terminal:
$ bundle install
in app/models/service.rb include right after class declaration:
include Elasticsearch::Model
you can now play with it on console with existing data (results are just an example):
$ rails console# Create the index for Service model on elasticsearch> Service.__elasticsearch__.create_index!=> {"acknowledged"=>true}# Import current Service records into the index> Service.import Service Load (207.3ms) SELECT "services".* FROM "services" ORDER BY "services"."id" ASC LIMIT 1000# Sample search returning total results> Service.__elasticsearch__.search("mykeyword").results.total=> 123
For more information and details you can take a look at the project's github page
Better use elasticsearch-rails
in Gemfile:
gem install elasticsearch-rails
To import the records from your Article model, run:
$ bundle exec rake environment elasticsearch:import:model CLASS='Article'
To limit the imported records to a certain ActiveRecord scope, pass it to the task:
$ bundle exec rake environment elasticsearch:import:model CLASS='Article' SCOPE='published'
Run this command to display usage instructions:
$ bundle exec rake -D elasticsearch
If you want to use for model
elasticsearch-model, which contains search integration for Ruby/Rails models such as ActiveRecord::Base and Mongoid,