Class: RSolr::Document

Inherits:
Object
  • Object
show all
Defined in:
lib/rsolr/document.rb

Constant Summary collapse

CHILD_DOCUMENT_KEY =
'_childDocuments_'.freeze
ATOMIC_MULTI_VALUE_OPERATIONS =
i[set add add-distinct remove]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(doc_hash = {}) ⇒ Document

“doc_hash” must be a Hash/Mash object If a value in the “doc_hash” is an array, a field object is created for each value…



13
14
15
16
17
18
19
# File 'lib/rsolr/document.rb', line 13

def initialize(doc_hash = {})
  @fields = []
  doc_hash.each_pair do |field, values|
    add_field(field, values)
  end
  @attrs={}
end

Instance Attribute Details

#attrsObject

“attrs” is a hash for setting the “doc” xml attributes “fields” is an array of Field objects



8
9
10
# File 'lib/rsolr/document.rb', line 8

def attrs
  @attrs
end

#fieldsObject

“attrs” is a hash for setting the “doc” xml attributes “fields” is an array of Field objects



8
9
10
# File 'lib/rsolr/document.rb', line 8

def fields
  @fields
end

Instance Method Details

#add_field(name, values, options = {}) ⇒ Object

Add a field value to the document. Options map directly to XML attributes in the Solr <field> node. See wiki.apache.org/solr/UpdateXmlMessages#head-8315b8028923d028950ff750a57ee22cbf7977c6

Example:

document.add_field('title', 'A Title', :boost => 2.0)


40
41
42
43
44
45
46
47
# File 'lib/rsolr/document.rb', line 40

def add_field(name, values, options = {})
  RSolr::Array.wrap(values).each do |v|
    field_attrs = { name: name }
    field_attrs[:type] = DocumentField if name.to_s == CHILD_DOCUMENT_KEY

    @fields << RSolr::Field.instance(options.merge(field_attrs), v)
  end
end

#as_jsonObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/rsolr/document.rb', line 49

def as_json
  @fields.group_by(&:name).each_with_object({}) do |(field, values), result|
    v = values.map(&:as_json)
    if v.length > 1 && v.first.is_a?(Hash)
      if v.first.key?(:value)
        v = v.first.merge(value: v.map { |single| single[:value] })
      else
        (v.first.keys & ATOMIC_MULTI_VALUE_OPERATIONS).each do |op|
          v = [{ op => v.map { |single| single[op] } }]
        end
      end
    end
    v = v.first if v.length == 1 && field.to_s != CHILD_DOCUMENT_KEY
    result[field] = v
  end
end

#field_by_name(name) ⇒ Object

returns the first field that matches the “name” arg



27
28
29
# File 'lib/rsolr/document.rb', line 27

def field_by_name(name)
  @fields.detect{|f|f.name==name}
end

#fields_by_name(name) ⇒ Object

returns an array of fields that match the “name” arg



22
23
24
# File 'lib/rsolr/document.rb', line 22

def fields_by_name(name)
  @fields.select{|f|f.name==name}
end