搜索引擎 使用 ElasticSearch-ruby 插件,怎么设置 model,排除不需要索引的字段?

jimmyc · March 04, 2014 · Last by fantasticfears replied at April 29, 2014 · 10435 hits

最近刚开始使用 ElasticSearch-ruby,不知道如何在 model 中设置,排除不需要索引的字段,就是让某一个字段无法被搜索到。

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

  attr_accessible :title, :content, :published_on

  mapping do
    indexes :title,      type: 'string'
    indexes :content,    store: 'false',   index: 'no'  
  end
end

这样好像不起作用啊 ```

同问…以前用 sphinx 可以自己写索引规则,用 elasticserach 却找不到怎么做…

同问…还没看明白 mapping 是什么。我现在是在 search 的时候指定 fields

用 as_indexed_json,比如: def as_indexed_json(options={}) { :id => self.id, :title => title, :content => content, :created_at => created_at } end

会不会跟 dynamic mapping http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/mapping-dynamic-mapping.html 有关

试试这样

mapping dynamic: 'false' do
  indexes :title, type: 'string'
end

#4 楼 @cqpx 测试了,好像不起作用,暂时只能采用@Rei 的方法,搜索的时候指定字段了。

mapping 简单地讲就是让 ES 如何对某个字段做什么处理,例如索引了浏览器的 UA,这时是不需要对它做分词处理的,可以设为 not_analyzed

另外排除不需要索引的字段可以定义一个 as_indexed_json 方法,默认是用 as_json

https://github.com/elasticsearch/elasticsearch-rails/blob/master/elasticsearch-model/lib/elasticsearch/model/serializing.rb#L28

#6 楼 @_samqiu Thanks。那我再去试一下。

还有一个坏消息,如果你定义了 as_indexed_json ,在更新时,默认是不通过 as_indexed_json 更新的。

https://github.com/elasticsearch/elasticsearch-rails/issues/5

但是看你的需求,应该只是要去掉不需要索引的字段,这点对你的使用影响不大。

1, 首先定义 mappings

mappings dynamic: 'false' do
  indexes :name, type: 'string'
  indexes :status, type: 'integer', include_in_all: false
end

2, 根据 mappings 建立索引

Piece.__elasticsearch__.client.indices.create \
  index: Piece.index_name,
  body: {mappings: Piece.mappings.to_hash }

3, 给 Piece 所有记录创建索引 Piece.import

10 Floor has deleted

推荐使用:tire

#11 楼 @hz_qiuyuanxin

NOTICE: This library has been renamed and retired in September 2013 (read the explanation). It is not considered compatible with Elasticsearch 1.x.

Have a look at the http://github.com/elasticsearch/elasticsearch-rails suite of gems, which contain similar set of features for ActiveModel/Record and Rails integration as Tire.

可以在 Console 里检查一下有没有错误。 Article.elasticsearch.create_index! force: true Article.elasticsearch.refresh_index! 详见 README

You need to Sign in before reply, if you don't have an account, please Sign up first.