'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 1:[1]
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:
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 runningsearchkick:reindextask.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.
Solution 2:[2]
If you want to use the :search_import scope in should_index?, as seen in BigRon's answer above, you need to access the scope via 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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Diego Toral |
| Solution 2 | Patrick Crowley |
