Search code examples
ruby-on-rails-3elasticsearchsearchkick

How to eager load related models when indexing using SearchKick / ElasticSearch?


This is my search_data method:

def search_data
  {
    email: email,
    skills: interests.pluck(:name)
  }
end

where my User has_many :skills. When I run User.where(conditions).reindex it load the skills records like

SELECT * FROM skills WHERE skills.user_id = 1
SELECT * FROM skills WHERE skills.user_id = 2
SELECT * FROM skills WHERE skills.user_id = 3
SELECT * FROM skills WHERE skills.user_id = 4
. . .

I wonder if it's possible to make it load like this:

SELECT * FROM skills WHERE skills.user_id IN (1, 2, 3, 4, . . .)

Solution

  • You can use eager load when indexing, so to reindex your User model, you'd write something like User.includes(:skills).reindex

    Then you'd need to use map instead pluck here too:

    def search_data
      {
        email: email,
        skills: interests.map(&:name)
      }
    end