Module: Caoutsearch::Index::Serialization

Extended by:
ActiveSupport::Concern
Included in:
Base
Defined in:
lib/caoutsearch/index/serialization.rb

Instance Method Summary collapse

Instance Method Details

#as_json(*keys) ⇒ Object

Serialize the object payload

Raises:



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/caoutsearch/index/serialization.rb', line 38

def as_json(*keys)
  keys = keys.map(&:to_s)
  _, partial_keys = analyze_keys(keys)

  raise SerializationError, format_keys("cannot serializer the following keys together: %{keys}", partial_keys) if keys.size > 1 && partial_keys.any?

  json = {}
  keys = properties if keys.empty?
  keys.each do |key|
    result = send(key)

    if partial_reindexations.include?(key)
      json = json.merge(result)
    else
      json[key.to_sym] = result
    end
  end

  simplify(json)
end

#bulkify(method, keys) ⇒ Object

Convert the object Elasticsearch ‘headerndata` payload format

Raises:

  • (ArgumentError)


90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/caoutsearch/index/serialization.rb', line 90

def bulkify(method, keys)
  raise ArgumentError, "unknown method #{method}" unless %i[index update delete].include?(method)

  keys = keys.map(&:to_s)
  payload = []
  property_keys, partial_keys = analyze_keys(keys)

  case method
  when :index
    raise SerializationError, format("cannot serialize the following keys: %{keys}", keys: partial_keys.to_sentence) if partial_keys.any?

    payload << {index: {_id: record.id}}
    payload << as_json(*keys)

  when :update
    if property_keys.any?
      payload << {update: {_id: record.id}}
      payload << {doc: as_json(*property_keys)}
    end

    partial_keys.each do |key|
      payload << {update: {_id: record.id}}
      payload << as_json(*key)
    end

  when :delete
    payload << {update: {_id: record.id}}
  end

  payload
end

#simplify(object) ⇒ Object

Recursive objects simplication:

[nil, 'A', 'A', 'B']          => ['A', 'B']
[nil, 'A', 'A']               => 'A'
[nil, nil]                    => nil
[]                            => nil

{ key: [nil, 'A', 'A', 'B'] } => { key: ['A', 'B'] }
{ key: [nil, 'A', 'A'] }      => { key: 'A' }
{ key: [nil, nil] }           => { key: nil }
{ key: [] }                   => { key: nil }
{ }                           => { }


76
77
78
79
80
81
82
83
84
85
86
# File 'lib/caoutsearch/index/serialization.rb', line 76

def simplify(object)
  case object
  when Array
    object = object.filter_map { |array_item| simplify(array_item) }.uniq
    object = object[0] if object.size <= 1
  when Hash
    object.each { |key, value| object[key] = simplify(value) }
  end

  object
end

#to_jsonObject



59
60
61
# File 'lib/caoutsearch/index/serialization.rb', line 59

def to_json(*)
  MultiJson.dump(as_json)
end