ruby-on-rails-4searchkick

how to use searchkick to index according to some conditions


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

Solution

  • 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