Method: Sunspot::Rails::Searchable::ClassMethods#solr_index

Defined in:
lib/sunspot/rails/searchable.rb

#solr_index(opts = {}) ⇒ Object

Add/update all existing records in the Solr index. The batch_size argument specifies how many records to load out of the database at a time. The default batch size is 50; if nil is passed, records will not be indexed in batches. By default, a commit is issued after each batch; passing false for batch_commit will disable this, and only issue a commit at the end of the process. If associated objects need to indexed also, you can specify include in format accepted by ActiveRecord to improve your sql select performance

Options (passed as a hash)

batch_size<Integer>

Batch size with which to load records. Passing ‘nil’ will skip batches. Default is 50.

batch_commit<Boolean>

Flag signalling if a commit should be done after after each batch is indexed, default is ‘true’

include<Mixed>

include option to be passed to the ActiveRecord find, used for including associated objects that need to be indexed with the parent object, accepts all formats ActiveRecord::Base.find does

first_id

The lowest possible ID for this class. Defaults to 0, which is fine for integer IDs; string primary keys will need to specify something reasonable here.

Examples

# index in batches of 50, commit after each
Post.index 

# index all rows at once, then commit
Post.index(:batch_size => nil) 

# index in batches of 50, commit when all batches complete
Post.index(:batch_commit => false) 

# include the associated +author+ object when loading to index
Post.index(:include => :author)


225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/sunspot/rails/searchable.rb', line 225

def solr_index(opts={})
  options = {
    :batch_size => 50,
    :batch_commit => true,
    :include => self.sunspot_options[:include],
    :first_id => 0
  }.merge(opts)

  if options[:batch_size]
    counter = 0
    find_in_batches(:include => options[:include], :batch_size => options[:batch_size]) do |records|
      solr_benchmark options[:batch_size], counter do
        Sunspot.index(records)
      end
      Sunspot.commit if options[:batch_commit]
      counter += 1
    end
    Sunspot.commit unless options[:batch_commit]
  else
    Sunspot.index!(all(:include => options[:include]))
  end
end