0
votes

Elasticsearch through tire is working fine for me. 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.

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.

1

1 Answers

0
votes

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. There are some more details about to_indexed_json in this question but something like this should work:

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