how to use searchkick to index according to some conditions

故事扮演 提交于 2020-01-15 10:12:32

问题


I am using searchkick and rails4.

I have an activerecord People, with attributes a,b,c. How can I do indexing only when b equals "type1", not indexing otherwise?

Currently what I know is

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

回答1:


Per the docs:

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

This should work for your case:

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



回答2:


A bit late but a teammate came up through this question earlier today and I think the topic deserves a more detailed answer.

As far as I can tell, you have two options to control which records are indexed by searchkick:

  1. At the class level, you can limit the records searchkick index by defining an ActiveRecord scope search_import. This scope is used, essentially, when indexing multiple records at once, like when running searchkick:reindex task.

  2. At the instance level, you can define a should_index? method which gets called on every record just before indexing, it determines whether a record should be added or removed from the index.

So, if you want to index only records that have b equals 'type1' you could do something like below:

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

  def should_index?
    b == 'type1'
  end
end

Note that returning false from should_import? will remove the record form the index as you can read here.



来源:https://stackoverflow.com/questions/47564187/how-to-use-searchkick-to-index-according-to-some-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!