Method: ActsAsSolr::ClassMethods#rebuild_solr_index

Defined in:
lib/acts_as_solr/class_methods.rb

#rebuild_solr_index(batch_size = 0, &finder) ⇒ Object

It’s used to rebuild the Solr index for a specific model.

Book.rebuild_solr_index

If batch_size is greater than 0, adds will be done in batches. NOTE: If using sqlserver, be sure to use a finder with an explicit order. Non-edge versions of rails do not handle pagination correctly for sqlserver without an order clause.

If a finder block is given, it will be called to retrieve the items to index. This can be very useful for things such as updating based on conditions or using eager loading for indexed associations.



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/acts_as_solr/class_methods.rb', line 201

def rebuild_solr_index(batch_size=0, &finder)
  finder ||= lambda { |ar, options| ar.find(:all, options.merge({:order => self.primary_key})) }
  start_time = Time.now

  if batch_size > 0
    items_processed = 0
    limit = batch_size
    offset = 0
    begin
      iteration_start = Time.now
      items = finder.call(self, {:limit => limit, :offset => offset})
      add_batch = items.collect { |content| content.to_solr_doc }

      if items.size > 0
        solr_add add_batch
        solr_commit
      end

      items_processed += items.size
      last_id = items.last.id if items.last
      time_so_far = Time.now - start_time
      iteration_time = Time.now - iteration_start         
      logger.info "#{Process.pid}: #{items_processed} items for #{self.name} have been batch added to index in #{'%.3f' % time_so_far}s at #{'%.3f' % (items_processed / time_so_far)} items/sec (#{'%.3f' % (items.size / iteration_time)} items/sec for the last batch). Last id: #{last_id}"
      offset += items.size
    end while items.nil? || items.size > 0
  else
    items = finder.call(self, {})
    items.each { |content| content.solr_save }
    items_processed = items.size
  end
  solr_optimize
  logger.info items_processed > 0 ? "Index for #{self.name} has been rebuilt" : "Nothing to index for #{self.name}"
end