【问题标题】:Why do my searchkick has_many and HABTM association not work?为什么我的 searchkick has_many 和 HABTM 关联不起作用?
【发布时间】:2016-11-04 01:47:35
【问题描述】:

我最近设置了 searchkick,它非常适用于我索引的模型上的属性。

但是,当涉及到关联时,它就失败了。

这是我的关联模型和search_data 方法:

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

我确保运行Profile.reindex,但是当我对Center Backposition 的名称)运行查询时,当我知道有结果时它会返回一个空查询集。

> 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}'
=> []

以下是其他结果:

> 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

应该至少有 5 个profiles,但结果返回为空。

我什至尝试过像这样格式化我的search_data

  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

如果我尝试一个常规的 has_many 关联并相应地声明它,也会发生同样的事情。

这可能是什么原因造成的,我该如何解决?

【问题讨论】:

    标签: ruby-on-rails elasticsearch ruby-on-rails-5 searchkick


    【解决方案1】:

    所以事实证明search_data 实际上是正确的,但我没有意识到我必须运行rails searchkick:reindex:all 命令,而不是在我正在运行的rails console 中执行Profile.reindex

    运行该命令后,我注意到它重新索引了包括所有关联在内的所有内容,现在它就像一个魅力!

    【讨论】:

      猜你喜欢
      • 2015-09-11
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多