如何使用searchkick根据某些条件进行索引

how to use searchkick to index according to some conditions

我正在使用 searchkick 和 rails4。

我有一个 activerecord People,属性为 a、b、c。如何仅在 b 等于 "type1" 时进行索引,否则不进行索引?

目前我知道的是

def search_data
  {
    a:a,
    b:b,
    c:c,
  }
end

根据 docs:

By default, all records are indexed. To control which records are indexed, use the should_index? method together with the search_import scope.

这应该适用于您的情况:

class People < ApplicationRecord
  searchkick # you probably already have this
  scope :search_import, -> { where(b: "type1") }

  def should_index?
    self.search_import # only index records per your `search_import` scope above
  end

  def search_data # looks like you already have this, too
    {
      a:a,
      b:b,
      c:c,
    }
  end
end

有点晚了,但队友今天早些时候提出了这个问题,我认为这个话题值得更详细的回答。

据我所知,您有两个选项来控制哪些记录被 searchkick 编入索引:

  1. 在class级别,您可以通过定义一个ActiveRecord范围search_import来限制记录searchkick索引。本质上,在一次索引多个记录时使用此范围,例如 运行 searchkick:reindex task.

  2. 在实例级别,您可以定义一个 should_index? 方法,该方法在索引之前在每条记录上调用,它确定是否应将记录添加到索引中或从索引中删除。

因此,如果您只想索引 b 等于 'type1' 的记录,您可以执行如下操作:

class People < ApplicationRecord
  scope :search_import, -> { where(b: 'type1') }

  def should_index?
    b == 'type1'
  end
end

请注意,从 should_import? 返回 false 将从索引中删除记录,因为您可以阅读 here

如果您想在 should_index? 中使用 :search_import 范围,如上面 BigRon 的回答所示,您需要通过 self.class.search_import.

访问范围
class People < ApplicationRecord
  searchkick # you probably already have this
  scope :search_import, -> { where(b: "type1") }

  def should_index?
    self.class.search_import # only index records per your `search_import` scope above
  end

  def search_data # looks like you already have this, too
    {
      a:a,
      b:b,
      c:c,
    }
  end
end