Skip to content

Latest commit

 

History

History
69 lines (56 loc) · 1.64 KB

File metadata and controls

69 lines (56 loc) · 1.64 KB
endpoint async_search
lang javascript
es_version 9.3
client @elastic/elasticsearch@9.3.0

Elasticsearch 9.3 async_search endpoint (JavaScript example)

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

const response = await client.asyncSearch.submit({
  index: "products",
  query: { match_all: {} },
  wait_for_completion_timeout: "0s",
});

const searchId = response.id;
console.log(`Search submitted: ${searchId.substring(0, 20)}...`);

Polling for completion

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

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

while (true) {
  const status = await client.asyncSearch.status({ id: searchId });
  if (!status.is_running) break;
  await sleep(500);
}

const result = await client.asyncSearch.get({ id: searchId });
for (const hit of result.response.hits.hits) {
  console.log(`  ${hit._source.name}`);
}

Cleanup

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

const response = await client.asyncSearch.submit({
  index: "products",
  query: { match: { category: "electronics" } },
  wait_for_completion_timeout: "0s",
});
const searchId = response.id;

try {
  const result = await client.asyncSearch.get({
    id: searchId,
    wait_for_completion_timeout: "10s",
  });
  for (const hit of result.response.hits.hits) {
    console.log(hit._source.name);
  }
} finally {
  await client.asyncSearch.delete({ id: searchId });
}