我正在使用searchkick和rails4。
我有一个activerecord People,属性为a,b,c。只有当b等于" type1"而不进行索引时,我该如何进行索引?
目前我所知道的是
def search_data
{
a:a,
b:b,
c:c,
}
end
答案 0 :(得分:1)
根据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
答案 1 :(得分:1)
有点晚了,但是队友今天早些时候提出了这个问题,我认为这个话题应该得到更详细的答案。
据我所知,您有两个选择来控制用searchkick索引哪些记录:
在类级别,您可以通过定义ActiveRecord范围search_import
来限制记录的搜索索引。本质上,当同时为多个记录建立索引时(例如运行searchkick:reindex
任务时),将使用此作用域。
在实例级别,您可以定义一个should_index?
方法,该方法在索引建立之前在每条记录上被调用,它确定是否应在索引中添加或删除记录。
因此,如果您只希望索引b
等于'type1'
的记录,则可以执行以下操作:
class People < ApplicationRecord
scope :search_import, -> { where(b: 'type1') }
def should_index?
b == 'type1'
end
end
请注意,从false
返回should_import?
会从索引中删除记录,您可以阅读here。