Elastic Search Rails find associated model attributes

1.2k Views Asked by At

I am using Elastic Search in my Rails project. I am doing real time full text search using elasticsearch-model gem. Suppose Model A belongs to Model B. If I am doing a search on Model A I am getting 10 records of A based on my search parameters.

A.search(x) => Gives 10 records which includes all attributes of A.

But when I am accessing Model B through A like: A.B.some_attrib I am getting

 undefined method B for <Elasticsearch::Model::Response::Result>

How to load the associations in ElasticSearch?

Also I want all the records in the search result. How to specify match_all in search method?

2

There are 2 best solutions below

0
On

You can configure model associations with as_indexed_json method. Here is the psuedo code for that:

def as_indexed_json(options={})
 self.as_json(
   include: {
     b: { only: :col1}
   }
 )
end
0
On

for associated_model see this link https://github.com/elastic/elasticsearch-rails/blob/master/elasticsearch-model/examples/activerecord_associations.rb

Include Elasticsearch::Model and callbacks in concern and do index mapping.
Include module in both associated model.

Note: Don't forget to import model.