【问题标题】:Tire index elasticsearch轮胎指数elasticsearch
【发布时间】:2013-07-23 21:31:50
【问题描述】:

通过轮胎的 Elasticsearch 对我来说效果很好。我想要关于我在代码中遇到的问题的建议。

  mapping do
    indexes :id, :index => :not_analyzed
    indexes :locality
  end

这是我的映射的一部分。locality 对应于模型中定义为的方法

def locality
  self.locality.name
end

模型也是

belongs_to :locality

所以,你可以观察到被调用的方法会陷入死循环。我有一个限制,由于我们想要避免的前端的相应更改,我无法更改映射中的名称位置。 一种替代方法是在 Locality 模型中定义一个方法,该方法给出

def locality_name
  self.name
end

我尝试在 to_indexed_json 中包含 locality_name 方法并尝试以这种方式映射但失败了。

mapping do
  indexes :id, :index => :not_analyzed
  indexes :locality do
    indexes :locality_name
  end

end

我希望在不更改模型 Locality 的情况下,在结果中将 locality 的名称索引为“locality”。

【问题讨论】:

    标签: ruby-on-rails mapping elasticsearch tire


    【解决方案1】:

    您需要在模型中提供 to_indexed_json 的实现,以便为索引中的 locality 字段提供不同的值。 this question 中有更多关于 to_indexed_json 的详细信息,但这样的东西应该可以工作:

    self.include_root_in_json = false
    def to_indexed_json
      # Get the default json for the instance
      hash = as_json(:root => false)
      # Add a locality field mapped to the name of the locality
      hash.update(:locality => self.locality.name).to_json
    end
    

    【讨论】:

    • 映射中还有其他的属性和方法我没有展示,它们都包含在to_indexed_json中。会被跳过吗?
    • 我已经用一些 cmets 更新了答案代码。它基本上将 locality 参数与模型的默认 json 一起添加到 json 中。您可以进一步扩展它以提供或排除其他字段。
    猜你喜欢
    • 2013-09-26
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    相关资源
    最近更新 更多