Skip to content

Latest commit

 

History

History
67 lines (55 loc) · 1.45 KB

File metadata and controls

67 lines (55 loc) · 1.45 KB
endpoint async_search
lang ruby
es_version 9.3
client elasticsearch==9.3.0

Elasticsearch 9.3 async_search endpoint (Ruby example)

Use client.async_search.submit to start a search that runs in the background. This is useful for long-running queries that would otherwise time out:

response = client.async_search.submit(
  index: 'products',
  body: { query: { match_all: {} } },
  wait_for_completion_timeout: '0s'
)

search_id = response['id']
puts "Search submitted: #{search_id[0..19]}..."

Polling for completion

Check the status of an async search, then retrieve the results once complete:

loop do
  status = client.async_search.status(id: search_id)
  break unless status['is_running']
  sleep 0.5
end

result = client.async_search.get(id: search_id)
result['response']['hits']['hits'].each do |hit|
  puts "  #{hit['_source']['name']}"
end

Cleanup

Always delete the async search when done to free server resources. Use begin/ensure to guarantee cleanup even if processing fails:

response = client.async_search.submit(
  index: 'products',
  body: { query: { match: { category: 'electronics' } } },
  wait_for_completion_timeout: '0s'
)
search_id = response['id']

begin
  result = client.async_search.get(
    id: search_id,
    wait_for_completion_timeout: '10s'
  )
  result['response']['hits']['hits'].each do |hit|
    puts hit['_source']['name']
  end
ensure
  client.async_search.delete(id: search_id)
end