Skip to content

Latest commit

 

History

History
67 lines (52 loc) · 1.39 KB

File metadata and controls

67 lines (52 loc) · 1.39 KB
endpoint scroll
lang ruby
es_version 9.3
client elasticsearch==9.3.0

Elasticsearch 9.3 scroll endpoint (Ruby example)

Use client.scroll to retrieve the next batch of results from a scrolling search. Start by calling search with a scroll parameter, then repeatedly call scroll until no more hits are returned:

response = client.search(
  index: 'products',
  scroll: '1m',
  size: 2,
  body: { query: { match_all: {} } }
)

scroll_id = response['_scroll_id']
hits = response['hits']['hits']

while hits.any?
  hits.each do |hit|
    puts "#{hit['_id']}: #{hit['_source']['name']}"
  end

  response = client.scroll(body: { scroll_id: scroll_id, scroll: '1m' })
  scroll_id = response['_scroll_id']
  hits = response['hits']['hits']
end

Cleaning up

Always clear the scroll context when you are done to free server resources. Pass the last scroll_id you received:

client.clear_scroll(body: { scroll_id: scroll_id })

To clear every open scroll context at once, call without arguments:

client.clear_scroll

Using helpers

The scroll_helper provides a convenient enumerator. Prefer this over manual scrolling in most cases:

helper = Elasticsearch::Helpers::ScrollHelper.new(client, 'products',
  body: { query: { match_all: {} } },
  scroll: '1m',
  size: 100
)

helper.each do |doc|
  puts "#{doc['_id']}: #{doc['_source']['name']}"
end