Class: Sunspot::Indexer

Inherits:
Object
  • Object
show all
Includes:
RSolr::Char
Defined in:
lib/sunspot/indexer.rb

Overview

This class presents a service for adding, updating, and removing data from the Solr index. An Indexer instance is associated with a particular setup, and thus is capable of indexing instances of a certain class (and its subclasses).

Instance Method Summary collapse

Constructor Details

#initialize(connection) ⇒ Indexer

Returns a new instance of Indexer.



11
12
13
# File 'lib/sunspot/indexer.rb', line 11

def initialize(connection)
  @connection = connection
end

Instance Method Details

#add(model) ⇒ Object

Construct a representation of the model for indexing and send it to the connection for indexing

Parameters

model<Object>

the model to index



23
24
25
26
27
28
29
30
# File 'lib/sunspot/indexer.rb', line 23

def add(model)
  documents = Util.Array(model).map { |m| prepare(m) }
  if @batch.nil?
    add_documents(documents)
  else
    @batch.concat(documents)
  end
end

#flush_batchObject

Write batch out to Solr and clear it



78
79
80
81
# File 'lib/sunspot/indexer.rb', line 78

def flush_batch
  add_documents(@batch)
  @batch = nil
end

#remove(*models) ⇒ Object

Remove the given model from the Solr index



35
36
37
38
39
# File 'lib/sunspot/indexer.rb', line 35

def remove(*models)
  @connection.delete_by_id(
    models.map { |model| Adapters::InstanceAdapter.adapt(model).index_id }
  )
end

#remove_all(clazz = nil) ⇒ Object

Delete all documents of the class indexed by this indexer from Solr.



53
54
55
56
57
58
59
# File 'lib/sunspot/indexer.rb', line 53

def remove_all(clazz = nil)
  if clazz
    @connection.delete_by_query("type:#{escape(clazz.name)}")
  else
    @connection.delete_by_query("*:*")
  end
end

#remove_by_id(class_name, *ids) ⇒ Object

Remove the model from the Solr index by specifying the class and ID



44
45
46
47
48
# File 'lib/sunspot/indexer.rb', line 44

def remove_by_id(class_name, *ids)
  @connection.delete_by_id(
    ids.map { |id| Adapters::InstanceAdapter.index_id_for(class_name, id) }
  )
end

#remove_by_scope(scope) ⇒ Object

Remove all documents that match the scope given in the Query



64
65
66
# File 'lib/sunspot/indexer.rb', line 64

def remove_by_scope(scope)
  @connection.delete_by_query(scope.to_boolean_phrase)
end

#start_batchObject

Start batch processing



71
72
73
# File 'lib/sunspot/indexer.rb', line 71

def start_batch
  @batch = []
end