【问题标题】:how to use searchkick to index according to some conditions如何使用searchkick根据某些条件进行索引
【发布时间】:2017-11-30 00:45:42
【问题描述】:

我正在使用 searchkick 和 rails4。

我有一个活动记录 People,具有 a、b、c 属性。如何仅当 b 等于“type1”时才进行索引,否则不进行索引?

目前我知道的是

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

【问题讨论】:

    标签: ruby-on-rails-4 searchkick


    【解决方案1】:

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

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

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

    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

    【讨论】:

      【解决方案2】:

      根据docs

      默认情况下,所有记录都被索引。要控制对哪些记录进行索引,请将should_index? 方法与search_import 范围结合使用。

      这应该适用于您的情况:

      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
      

      【讨论】:

      • 在should_index里面,应该是b而不是self.search_import?
      • 不,不应该是bdef should_index? 仅索引在 should_index? 块内返回的记录。而且,self.search_import? 将调用search_import 范围,它只会返回b == "type1" 所在的记录,这意味着这些记录将被索引。
      • 你不能跳过 search_import 范围声明,把逻辑放在 should_index 里面吗?
      • 是的,从我在代码 herehere 中可以看到,search_importshould_index? 在记录被索引之前都会被调用,所以你应该可以使用其中任何一个.
      【解决方案3】:

      如果您想在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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-23
        • 1970-01-01
        • 2016-07-13
        • 2015-07-01
        • 2021-10-10
        • 2011-11-01
        • 2021-01-31
        • 1970-01-01
        相关资源
        最近更新 更多