参考:
https://code.tutsplus.com/articles/full-text-search-in-rails-using-elasticsearch–cms-22920
https://github.com/ankane/searchkick/blob/v3.1.3/README.md
说明
软件版本
| 软件名称 | 版本号 | 
|---|---|
| rails | 4.2.5.2 | 
| ruby | 2.3.8 | 
| gem | 2.7.7 | 
| bundle | 2.0.2 | 
| searchkick | 3.1.3 | 
| elasticsearch | 5.6.16 | 
| ik | 5.6.16 | 
选择依据
根据上图来看,searchkick在热门度和活跃度上都有不错的表现。
以下是主要的搜索gem简介:来源
- ransack - Ransack enables the creation of both simple and advanced search forms for your Ruby on Rails application.
 - elasticsearch-rails - Elasticsearch integrations for ActiveModel/Record and Ruby on Rails.
 - Chewy - High-level Elasticsearch Ruby framework based on the official elasticsearch-ruby client.
 - pg_search - pg_search builds ActiveRecord named scopes that take advantage of PostgreSQL’s full text search
 - sunspot - Sunspot is a Ruby library for expressive, powerful interaction with the Solr search engine. Sunspot is built on top of the RSolr library, which provides a low-level interface for Solr interaction; Sunspot provides a simple, intuitive, expressive DSL backed by powerful features for indexing objects and searching for them.
 - searchkick - Intelligent search made easy with Rails and Elasticsearch.
 
环境部署
elasticsearch
安装:
1  | sudo dpkg -i elasticsearch-5.6.16.deb  | 
ik插件
ik插件是elasticsearch中文分词插件
ik插件项目地址
安装:
- download or compile
 
optional 1
- download pre-build package from here: https://github.com/medcl/elasticsearch-analysis-ik/releases
 
create plugin folder cd your-es-root/plugins/ && mkdir ik
unzip plugin to folder your-es-root/plugins/ik
optional 2
- use elasticsearch-plugin to install ( supported from version v5.5.1 ):
1
./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v5.6.16/elasticsearch-analysis-ik-5.6.16.zip
 
NOTE: replace 5.6.16 to your own elasticsearch version
- restart elasticsearch
 
elasticsearch可视化
代码实现
app/models/course.rb
1
2class Course < ActiveRecord::Base
searchkick language: "chinese"app/helpers/search_helper.rb
1  | module SearchHelper  | 
app/views/search/_form.html.erb
1
2
3
4
5
6<%= form_for :term, url: list_courses_path, method: :get do |form| %>
<p>
<%= text_field_tag :term, params[:term] %>
<%= submit_tag "Search", name: nil %>
</p>
<% end %>app/views/courses/list.html.erb
1
<%= render 'search/form' %>
