Exclude draft articles from Solr Index using Sunspot

I have an indexed model called Article, and I don't want solr to index unpublished articles.

class Article < ActiveRecord::Base searchable do text :title text :body end end 

How can I indicate this article that has not been published? should not be indexed?

+4
source share
3 answers

Be sure to index the published status.

 class Article < ActiveRecord::Base searchable do text :title text :body boolean :is_published, :using => :published? end end 

Then add a filter to your query

 Sunspot.search(Article) do |search| search.with(:is_published, true) # ... end 
+7
source

If you want unpublished articles to never be included in the search index, you can do this as follows:

 class Article < ActiveRecord::Base searchable :if => :published? do text :title text :body end end 

Then the model will be indexed only after publication.

My approach is less interesting if you also want administrators to be able to search for articles, including unpublished ones.

Note: call article.index! will add an instance to the index regardless of the parameter :if => :method .

+7
source

A quick look at the sunspot_rails code base shows a method called maybe_mark_for_auto_indexing , which will be added to models that include solr. You can override this method and set @marked_for_auto_indexing based on your criteria in a particular model. His monkey fixes, but can help you solve the problem. The code for ur link is in lib/sunspot/searchable.rb .

+3
source

Source: https://habr.com/ru/post/1308252/


All Articles