Search code examples
ruby-on-railsthinking-sphinx

Thinking Sphinx - How to tell it to use ActiveRecord "include" feature, to avoid subsidiary SQL lookups?


Sphinx & ThinkingSphinx are working great for me, however when a search returns back an array of results (models), I then notice in my logs that there are a large number of subsidiary SQL lookups to retrieve any associated models, these associations are defined within my model classes.

If I was just using ActiveRecord I could use the "include" feature to retrieve these associated records as part of the original search query, for example:

Booking.find_all_by_date(Date.today, :include => [:event, :organizer, :sessions])

But I'm not sure how to implement this performance optimization in ThinkingSphinx, has anyone solved this?


Solution

  • You do it exactly the same way - use :include, it'll get passed through to the underlying ActiveRecord query when Thinking Sphinx translates Sphinx results to ActiveRecord objects.

    Edit: Since TS v3, the :include option is now contained within the :sql option:

    Booking.search(:sql => {:include => [:event, :organiser, :sessions]})