ruby-on-rails - 在 Rails 中使用 elasticsearch-model 保存特定字段

标签 ruby-on-rails elasticsearch elasticsearch-model

我在 Rails 4 项目中使用 elasticsearch-model gem 将我的用户存储在 MySQL 和 Elasticsearch 中。在我的项目中,Elasticsearch 部分用于查找具有某些 MySQL 字段(如 geo_point、birthdate、gender 等)的人……但并不是我在 MySQL“用户”表中的每个字段都对用户搜索有用。

所以,我想将所有用户字段存储在 MySQL 中,并且只存储用户在 Elasticsearch 中搜索所需的字段。

为了在创建时只存储必填字段,我重写了方法“as_indexed_json”并使用了:

as_json(only: ['id', 'gender', 'location']

在创建时,一切都很好。但是,当我使用应该只保存在 MySQL 中的字段来更新用户时,无论如何它都会将其添加到 Elasticsearch 中。

例如,我的用户模型有“id”、“gender”、“is_premium”、“status”、“created_at”、“birthdate”、“location”。
在 Elasticsearch 中,我只想保存“id”、“gender”、“birthdate”、“location”

我怎样才能做到这一点?
谢谢你的帮助。

最佳答案

这是 elasticsearch-rails 的一个问题(参见 github )。

简而言之,默认更新回调调用 update_document不使用 as_indexed_json : 它使用 ActiveModel::Dirty仅发送更改的列。

您可以通过覆盖 update_document 来解决此问题。方法,使其仅包含您想要的内容,或者通过更改回调的功能,例如

after_commit on: [:create, :update] do
  index_document
end

after_commit on: [:destroy] do
  delete_document
end

而不是使用默认的回调模块将导致 index_document被使用,它总是做一个“愚蠢的”完整更新,而不是试图只发送增量。

关于ruby-on-rails - 在 Rails 中使用 elasticsearch-model 保存特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23059812/

相关文章:

ruby-on-rails - Rails 覆盖保存以执行选择性更新

elasticsearch - ElasticSearch不会复制到新节点

elasticsearch - 无法在 TFS 2017.1 上启动 ElasticSearch

ruby-on-rails - 通过 elasticsearch-model 搜索不返回记录

ruby-on-rails - 在 Rails API 中使用 render 而不是 respond_with/to 有什么区别?

ruby-on-rails - 尝试访问数据库时找不到 gem 'rails'

ruby-on-rails - Rails update_attribute 永远循环

java - Elasticsearch 将多个字段与 AND 运算符匹配不起作用

elasticsearch - 通过复杂结构进行全文搜索Elasticsearch