Class: NoSE::Backend::MongoBackend::InsertStatementStep

Inherits:
Backend::InsertStatementStep show all
Defined in:
lib/nose/backend/mongo.rb

Overview

Insert data into an index on the backend

Instance Attribute Summary

Attributes inherited from Backend::StatementStep

#index

Instance Method Summary collapse

Methods included from Supertype

included

Constructor Details

#initialize(client, index, fields) ⇒ InsertStatementStep

Returns a new instance of InsertStatementStep.



140
141
142
143
144
# File 'lib/nose/backend/mongo.rb', line 140

def initialize(client, index, fields)
  super

  @fields = fields.map(&:id) & index.all_fields.map(&:id)
end

Instance Method Details

#process(results) ⇒ Object

Insert each row into the index



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/nose/backend/mongo.rb', line 147

def process(results)
  results.each do |result|
    values = Hash[@index.all_fields.map do |field|
      next unless result.key? field.id
      value = result[field.id]

      # If this is an ID, generate or construct an ObjectId
      if field.is_a?(Fields::IDField)
        value = if value.nil?
                  BSON::ObjectId.new
                else
                  BSON::ObjectId.from_string(value)
                end
      end
      [MongoBackend.field_path(@index, field).join('.'), value]
    end.compact]

    @client[@index.to_id_graph.key].update_one(
      { '_id' => values['_id'] },
      { '$set' => values },
      upsert: true
    )
  end
end