简体   繁体   English

轮胎指数弹性搜索

[英]Tire index elasticsearch

Elasticsearch through tire is working fine for me. 通过轮胎进行Elasticsearch对我来说很好。 I wanted a suggestion regarding a problem I'm facing in my code. 我想对我的代码中遇到的问题提出建议。

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

This is a part of my mapping.locality corresponds to a method in the model which is defined as 这是我映射的一部分。局部性对应于模型中定义为的方法

def locality
  self.locality.name
end

The model also 该模型也

belongs_to :locality

So,you can observe the called method will fall into an infinite loop. 因此,您可以观察到被调用的方法将陷入无限循环。 I have a limitation that I can't change the name locality in the mapping due to corresponding changes in the frontend which we want to avoid. 我有一个局限性,因为我们要避免前端中的相应更改,因此无法更改映射中的名称局部性。 One alternative is to define a method in the Locality model which gives 一种选择是在“位置”模型中定义一种方法

def locality_name
  self.name
end

I tried to include locality_name method in to_indexed_json and tried mapping this way but failed. 我试图在to_indexed_json中包含locality_name方法,并尝试通过这种方式进行映射,但失败了。

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

end

I want the name of locality to be indexed as "locality" in the result without changing the model Locality. 我希望在不更改模型Locality的情况下将本地名称在结果中索引为“ locality”。

You will need to provide an implementation of to_indexed_json in your model to provide a different value for the locality field in your index. 您将需要在模型中提供to_indexed_json的实现, to_indexed_json索引中的locality字段提供不同的值。 There are some more details about to_indexed_json in this question but something like this should work: 这个问题中还有关于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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM