0

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.

user2512324
  • 791
  • 1
  • 6
  • 21

1 Answers1

0

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
Community
  • 1
  • 1
Shadwell
  • 34,314
  • 14
  • 94
  • 99
  • There are other attributes and methods too defined in the mapping which I haven't shown and which are included in to_indexed_json.Will they be skipped? – user2512324 Jul 24 '13 at 13:55
  • I've updated the answer code with some comments. It basically adds the locality parameter to the json alongside the default json for the model. You can further it extend it to provide or exclude other fields. – Shadwell Jul 24 '13 at 13:58