Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to integrate elasticsearch with rails application specifically using "Elasticsearch" gem

I am new to rails and to elastic search. I have seen other resources to configure using Tire, Searchkick and some others, but I want to use Elasticsearch gem. I have running rails application and running Elasticsearch server on my system but I do not how to configure them to communicate with each other.

Currently, I am facing a lot of troubles to do the same. Any help would be highly appreciated.

like image 557
Tulsi Avatar asked Nov 23 '15 09:11

Tulsi


2 Answers

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,

like image 116
Rajarshi Das Avatar answered Sep 21 '22 19:09

Rajarshi Das


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

like image 43
fagiani Avatar answered Sep 21 '22 19:09

fagiani