Rails中使用elasticsearch全文搜索引擎

Posted by baicai on August 11, 2016

安装好elasticsearch


http://www.liubaicai.net/articles/747 有介绍</p>


首先引入gem


gem 'elasticsearch-model'
gem 'elasticsearch-rails'
gem 'elasticsearch-persistence'

然后新建一个lib/tasks/elasticssearch.rake中</p>

require 'elasticsearch/rails/tasks/import'


为数据库表添加索引的迁移


class AddIndexsToArticles < ActiveRecord::Migration
def change
add_index :articles, :title
add_index :articles, :content
end
end


扩展model类</h3>


class Article < ActiveRecord::Base
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks

mapping dynamic: false do
indexes :title
indexes :content
end
end

也可以定制json输出的内容,比如关联表数据等

def as_indexed_json(options={})
   self.as_json(
     only: [:id, :name, :description, :status],   
     include: { tags: { only: [:name]}}
   )
 end


执行


rake environment elasticsearch:import:model CLASS='Article' FORCE=y

最后</p>

bundle install & rake db:migrate


就可以愉快的搜索了</p></blockquote>

articles = Article.search('苟利国家生死以').results