diff --git a/lib/chewy/search/request.rb b/lib/chewy/search/request.rb index ffb93cdb..27d5cdef 100644 --- a/lib/chewy/search/request.rb +++ b/lib/chewy/search/request.rb @@ -46,7 +46,7 @@ class Request delegate :hits, :wrappers, :objects, :records, :documents, :object_hash, :record_hash, :document_hash, - :total, :max_score, :took, :timed_out?, to: :response + :total, :max_score, :took, :timed_out?, :terminated_early?, to: :response delegate :each, :size, :to_a, :[], to: :wrappers alias_method :to_ary, :to_a alias_method :total_count, :total @@ -891,7 +891,7 @@ def exists? def first(limit = UNDEFINED) request_limit = limit == UNDEFINED ? 1 : limit - if performed? && (request_limit <= size || size == total) + if performed? && (terminated_early? || request_limit <= size || size == total) limit == UNDEFINED ? wrappers.first : wrappers.first(limit) else result = except(EXTRA_STORAGES).limit(request_limit).to_a diff --git a/lib/chewy/search/response.rb b/lib/chewy/search/response.rb index 0a5becb2..5409a113 100644 --- a/lib/chewy/search/response.rb +++ b/lib/chewy/search/response.rb @@ -47,6 +47,13 @@ def timed_out? @timed_out ||= @body['timed_out'] end + # Has the request been terminated early? + # + # @return [true, false] + def terminated_early? + @terminated_early ||= @body['terminated_early'] + end + # The `suggest` response part. Returns empty hash if suggests # were not requested. # diff --git a/lib/chewy/search/scrolling.rb b/lib/chewy/search/scrolling.rb index 6074b325..f0c73837 100644 --- a/lib/chewy/search/scrolling.rb +++ b/lib/chewy/search/scrolling.rb @@ -39,7 +39,8 @@ def scroll_batches(batch_size: Request::DEFAULT_BATCH_SIZE, scroll: Request::DEF hits = hits.first(last_batch_size) if last_batch_size != 0 && fetched >= total yield(hits) if hits.present? scroll_id = result['_scroll_id'] - break if fetched >= total + + break if result['terminated_early'] || fetched >= total result = perform_scroll(scroll: scroll, scroll_id: scroll_id) end