Rails中Elasticsearch设index:false后email仍被索引的解决方法咨询
解决Elasticsearch中email字段仍被索引的问题
你当前配置的index: false只是让email字段不被分词建立倒排索引,但该字段依然会被存储到Elasticsearch的文档中。如果要彻底阻止它出现在索引里,可以试试以下几种方法:
方法1:从mapping中移除email字段的定义
既然你的mapping设置了dynamic: false(不自动映射未定义的字段),直接删掉indexes :email, index: false这行配置即可。修改后的mapping:
mappings dynamic: false do indexes :author, type: 'text' indexes :title, type: 'text' end
之后必须重建索引才能生效:
Book.__elasticsearch__.delete_index! Book.__elasticsearch__.create_index! Book.import force: true
方法2:在模型中过滤email字段
重写模型的as_indexed_json方法,排除email属性,这样导入时不会把该字段传给Elasticsearch:
class Book < ApplicationRecord include Elasticsearch::Model include Elasticsearch::Model::Callbacks mappings dynamic: false do indexes :author, type: 'text' indexes :title, type: 'text' end def as_indexed_json(options={}) self.as_json(except: [:email]) end end
修改后需要重新执行索引创建和导入操作。
方法3:导入时指定要包含的字段
执行导入命令时,用only参数明确指定需要导入的字段,email自然不会被包含:
Book.import force: true, only: [:author, :title]
内容的提问来源于stack exchange,提问作者rii
相关产品推荐
相关产品推荐

