Searchkick: eager loading/include associations at serialize time?

Created on 5 Feb 2015  路  3Comments  路  Source: ankane/searchkick

I'm using ActiveModelSerializers to render json. In some cases, I'm calling #to_a on instances of Searckick::Results and rendering that. But my serializers have associations that are not indexed in elasticsearch. This is ending up in a n+1 query to the database and makes queries extremely slow.

Is there a way to eager load these associations at render time?

To be honest, I'm not sure if a good solution lies in Elasticsearch, ActiveRecord, Rails, AMS, or searchkick land. I don't think this is a searchkick issue, but opening it here because @ankane has been really helpful in the past and this seems like something other searchkick users could benefit from knowing. Stackoverflow is fairly unresponsive for niche issues like this.

Most helpful comment

Hey Mehul, you can use the include option to eager load association.

Product.search "milk", include: [:brand, :stores]

All 3 comments

Right now, the best solution seems to be that I map the ids from the searchkick response and make another database call like this:

MyModel.includes(associations).where(id: searchkick_results.map(&:id))

This makes another db call, but I was able to improve total roundtrip request time by about 10x this way.

Hey Mehul, you can use the include option to eager load association.

Product.search "milk", include: [:brand, :stores]

Oh nice. i though the include option was used to eager load when indexing. missed that part of the docs. Thanks.

Was this page helpful?
0 / 5 - 0 ratings