4

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 specify that article that is not #published? should not be indexed?

Bogdan Gusiev
  • 8,027
  • 16
  • 61
  • 81

3 Answers3

7

If you want to make sure unpublished articles are never included in the search index, you can do it this way instead:

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

The model will then only be indexed when published.

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

Note: calling article.index! will add the instance to the index regardless of the :if => :method param.

webmat
  • 58,466
  • 12
  • 54
  • 59
7

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
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • In our case that will extend Solr index twice because most the articles stay drafts forever in our database. So this solution is not acceptable for us. – Bogdan Gusiev Apr 30 '10 at 14:35
  • Hi Simone. Let say an Article belongs_to a Category, and a (whole) category can be published. How do you search some articles filtered by categories published? – fro_oo Dec 19 '11 at 15:20
  • @Fro_oo I encourage you to open a new question – Simone Carletti Dec 19 '11 at 18:24
  • You're right :-) http://stackoverflow.com/questions/8574173/how-to-restrict-sunspot-search-with-nested-attributes – fro_oo Dec 20 '11 at 10:42
  • Hmmm, this approach is not super safe, though. I'd rather be able to exclude some records from being indexed at indexing time. This way, no matter in how many places in the code I search the model, I know there's no chance I'll forget to exclude unwanted instances. – webmat Aug 01 '12 at 20:20
3

A small look into the code base of sunspot_rails reveals a method called maybe_mark_for_auto_indexing which will be added to the models that include solr. You could override that method and set @marked_for_auto_indexing based on your criteria in the specific model. Its monkey patching but can help you solve the problem. The code for ur reference is in lib/sunspot/searchable.rb.

Kunday
  • 1,041
  • 6
  • 9