How to integrate elasticsearch with rails application specifically using “Elasticsearch” gem

邮差的信 提交于 2019-12-12 07:49:39

问题


I am new to rails and as well 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.


回答1:


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




回答2:


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,



来源:https://stackoverflow.com/questions/33867852/how-to-integrate-elasticsearch-with-rails-application-specifically-using-elasti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!