Elasticsearch rails gem

时间:2014-04-21 12:09:49

标签: ruby-on-rails elasticsearch

我想问一下,如果有宝石,你会建议我使用它来连接我的Rails应用程序和像Searchkick或Chewy这样的弹性搜索。如果有一些关于如何使用它的简单教程,那将是非常好的。感谢。

1 个答案:

答案 0 :(得分:5)

这取决于您使用的Rails / elasticsearch组合:

elasticsearch版本> = 1

elasticsearch-rails

elasticsearch版本< = 1

Tire

Tire有很多例子,弹性搜索没有那么多,所以这里是一个快速的开始:

# Gemfile
gem 'elasticsearch-model'
gem 'elasticsearch-rails'

bundle install

# lib/tasks/elasticsearch.rake
require 'elasticsearch/rails/tasks/import'

将现有模型数据从db加载到elasticsearch:

bundle exec rake environment elasticsearch:import:model CLASS='YourModel'

# app/models/your_model.rb
class YourModel < ActiveRecord::Base
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks
end

代码中的其他位置(比如方法中的控制器或范围或您喜欢的任何位置)

# search with field filter
@your_models = YourModel.search(query: { match:  { your_field: "whatever" } }).records

# faceted search
@your_models = YourModel.search(query: { match:  { your_field: "whatever" } }, facets: { your_facet_name: { terms: { field: "your_facet_field", all_terms: true, order: "term" } } }).records
# to access to the faceted part of the elasticsearch response:
facet_results = @your_models..response.response['facets']['your_facet_name']['terms']