Search code examples
ruby-on-railselasticsearchruby-on-rails-5searchkick

Why do my searchkick has_many and HABTM association not work?


I recently setup searchkick and it works wonderfully for attributes on the model I have indexed.

However, when it comes to associations, it fails badly.

This is my model with associations & search_data method:

class Profile < ActiveRecord::Base
  searchkick

  has_and_belongs_to_many :positions
  belongs_to :school

  def search_data
    {
      name: name,
      bib_color: bib_color,
      height: height,
      weight: weight,
      player_type: player_type,
      school_name: school.name,
      age: age,
      position_name: positions.map(&:name)
    }
  end
end

I made sure to run Profile.reindex, but when I run a query for Center Back, which is the name of a position, it returns an empty query set when I know there are results.

> Profile.search("center back").to_a
  Profile Search (27.5ms)  curl http://localhost:9200/profiles_development/_search?pretty -d '{"query":{"dis_max":{"queries":[{"match":{"_all":{"query":"center back","boost":10,"operator":"and","analyzer":"searchkick_search"}}},{"match":{"_all":{"query":"center back","boost":10,"operator":"and","analyzer":"searchkick_search2"}}},{"match":{"_all":{"query":"center back","boost":1,"operator":"and","analyzer":"searchkick_search","fuzziness":1,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}},{"match":{"_all":{"query":"center back","boost":1,"operator":"and","analyzer":"searchkick_search2","fuzziness":1,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}}]}},"size":1000,"from":0,"timeout":"11s","_source":false}'
=> []

Yet here are the results otherwise:

> p
=> #<Position:0x007fa881566310 id: 1, created_at: Sun, 04 Sep 2016 06:49:45 UTC +00:00, updated_at: Wed, 14 Sep 2016 06:17:02 UTC +00:00, name: "Center Back">
> p.profiles.count
   (4.1ms)  SELECT COUNT(*) FROM "profiles" INNER JOIN "positions_profiles" ON "profiles"."id" = "positions_profiles"."profile_id" WHERE "positions_profiles"."position_id" = $1  [["position_id", 1]]
=> 5

There should be at least 5 profiles, yet the results return as empty.

I have even tried formatting my search_data like so:

  def search_data
    attrs = attributes.dup
    relational = {
       school_name: school.name,
       grade_name: grades.map(&:subject),
       position_names: positions.map(&:name)
    }
    attrs.merge! relational
  end

The same thing happens if I try a regular has_many association and declare it accordingly.

What could be causing this and how do I fix it?


Solution

  • So it turns out that the search_data is actually correct, but I didn't realize I had to run the rails searchkick:reindex:all command, as opposed to just doing Profile.reindex in my rails console that was running.

    Once I ran that command, I noticed that it reindexed everything including all the associations and now it works like a charm!