问题
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 thesearch_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:
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:reindex
task.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