Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add max size limit to requests for bulk import #996

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 41 additions & 13 deletions elasticsearch-model/lib/elasticsearch/model/importing.rb
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ def import(options={}, &block)
transform = options.delete(:transform) || __transform
pipeline = options.delete(:pipeline)
return_value = options.delete(:return) || 'count'
max_size = options.delete(:max_size) || 10_000_000

unless transform.respond_to?(:call)
raise ArgumentError,
Expand All @@ -159,19 +160,46 @@ def import(options={}, &block)
end

__find_in_batches(options) do |batch|
params = {
index: target_index,
type: target_type,
body: __batch_to_bulk(batch, transform)
}

params[:pipeline] = pipeline if pipeline

response = client.bulk params

yield response if block_given?

errors += response['items'].select { |k, v| k.values.first['error'] }
batch = __batch_to_bulk(batch, transform)

until batch.empty?
todo = []
size = 0

# Accumulate until we hit max size
until size > max_size or batch.empty?
todo.push batch.shift
size += todo.last.to_s.size
end

# Put back last one if we went over
if size > max_size
batch.push todo.pop
size -= batch.last.to_s.size
end

# If we got here with nothing to do, we put our only todo back
# because it was too big - error.
if todo.empty?
item = batch.last
raise RuntimeError,
"#{target} #{item[:index][:_id]} size #{item.to_s.size} is larger than max_size #{max_size}"
end

params = {
index: target_index,
type: target_type,
body: todo
}

params[:pipeline] = pipeline if pipeline

response = client.bulk params

yield response if block_given?

errors += response['items'].select { |k, v| k.values.first['error'] }
end
end

self.refresh_index! index: target_index if refresh
Expand Down