Module: Dynamini::BatchOperations

Included in:
Base
Defined in:
lib/dynamini/batch_operations.rb

Instance Method Summary collapse

Instance Method Details

#batch_find(ids = []) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/dynamini/batch_operations.rb', line 17

def batch_find(ids = [])
  return OpenStruct.new(found: [], not_found: []) if ids.length < 1
  objects = []
  key_structure = ids.map { |i| {hash_key => i} }
  key_structure.each_slice(100) do |keys|
    response = dynamo_batch_get(keys)
    response.responses[table_name].each do |item|
      objects << new(item.symbolize_keys, false)
    end
  end
  OpenStruct.new(found: objects, not_found: ids - objects.map(&hash_key))
end

#dynamo_batch_save(model_array) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/dynamini/batch_operations.rb', line 30

def dynamo_batch_save(model_array)
  put_requests = model_array.map do |model|
    {
        put_request: {
            item: model.attributes.reject { |_k, v| v.blank? }.stringify_keys
        }
    }
  end
  request_options = {
      request_items: {table_name => put_requests}
  }
  client.batch_write_item(request_options)
end

#import(models) ⇒ Object



6
7
8
9
10
11
12
13
14
15
# File 'lib/dynamini/batch_operations.rb', line 6

def import(models)
  # Max batch size is 25, per Dynamo BatchWriteItem docs

  models.each_slice(25) do |batch|
    batch.each do |model|
      model.send(:generate_timestamps!)
    end
    dynamo_batch_save(batch)
  end
end