Skip to content

Use the Elasticsearch scroll API only for results larger than a page - #4994

Merged
porunov merged 1 commit into
JanusGraph:masterfrom
porunov:es-search-without-scroll
Oct 2, 2026
Merged

porunov merged 1 commit into
JanusGraph:masterfrom
porunov:es-search-without-scroll

Conversation

@porunov

@porunov porunov commented Sep 30, 2026 •

Copy link
Copy Markdown
Member

Fixes #1680

The Elasticsearch index backend now fetches a limited result in one request and uses the scroll API only for results larger than a page, releasing the scroll context as soon as the consumer is done with it.

Problem

ElasticSearchIndex.query decided useScroll = size >= max-result-set-size (50 by default). So:

  • Every query with a limit of 50 or more scrolled 50 hits at a time: limit(1000) was 20 sequential requests, each a query and fetch phase on every shard.
  • Its scroll context leaked. The result stream's .limit() stopped before the last, short page, and ElasticSearchScroll only released the context on a short page. The context lived until scroll-keep-alive (60 s) expired. LimitAdjustingIterator, which re-executes with a doubled limit, abandoned one scroll per step.
  • Every unlimited query paid two round trips before its first result: the scroll search, then a synchronous DELETE /_search/scroll/<id> when the first page was short, which is the common case. With query.smart-limit=false and query.hard-max-limit at its default, a plain g.V().has(mixedIndexedKey, value) is such a query. A failed release failed the query.
  • Elasticsearch counted every match of these queries: a scroll may not switch track_total_hits off.
  • JanusGraph hides the leaked contexts by raising search.max_open_scroll_context to the maximum cluster-wide, which Amazon OpenSearch Service does not allow, so there the leaks became query failures once 500 contexts were open on a node.

Changes

  • ElasticSearchSearcher (new, package-private) fetches the hits of a search for both the graph (IndexQuery) and the raw (RawQuery) path, which shared this logic in two copies before:
    • A result which a limit bounds within 10,000 hits (Elasticsearch's default index.max_result_window, which bounds from + size; JanusGraph lifts it on the indexes it creates but not on external ones) is one request with size = limit, track_total_hits: false, and from = offset for a raw query, whose offset was skipped on the client before.
    • A query without a limit, or with a larger one, first asks for max-result-set-size + 1 hits starting at the offset, so that Elasticsearch applies it, or for what is left up to the 10,000th hit if that is less. When fewer come back than were asked for, that is the whole result and no scroll context is opened. Only when the request comes back full, or when an offset of 10,000 or more leaves nothing to ask for, does a scroll take over from the start, in pages of max-result-set-size, with the offset skipped on the client as before, so no hit is counted twice and the scroll is the only source of the result. The scroll's bound is a long, so any finite offset + limit is represented whole.
  • ElasticSearchScroll takes the limit (offset included, since the offset of a scrolled result is still skipped on the client), stops fetching once the limit is within the pages received, releases the context then, on a short page, or when it is closed, and delivers no more than the limit. The result stream registers onClose for it. A release which fails no longer fails a search whose hits are complete: the context expires on its own.
  • RestElasticSearchClient.deleteScroll sends DELETE /_search/scroll asynchronously with the scroll id in the body, the form Elasticsearch has documented since the path form was deprecated in 7.0. The release no longer costs the search a round trip. A release the cluster rejects in a way every later release will meet as well, a request it doesn't accept (400, 405) or doesn't permit (401, 403, for example for want of the privilege to clear scrolls), is logged as a warning once per client, since every context then stays open until it expires; a context which is gone already (404), a busy cluster (429), a timed out request (408), a server error or a lost request are passing and logged at debug level without using the warning up.
  • SubqueryIterator keeps the index result stream and closes it when it is closed, which computeNext does once the iterator is exhausted. Traversal.close() reaches it through GraphStep and the iterator chain, and Gremlin Server closes every traversal it ran, so a server request which stops early hands the scroll context back. Embedded code which abandons a traversal without closing it still leaves the context to expire after scroll-keep-alive, as before; the docs say so.
  • Docs: elasticsearch.md gets a "Search Requests" section, and the OpenSearch paragraph on setup-max-open-scroll-contexts notes that only results larger than a page hold a context. The changelog names the change.

Results, their order and their scores are the same as before. The max-result-set-size option keeps its meaning for Elasticsearch: the page size of a scroll, and now also the size of the first request of an unlimited query. One cost is new: a result larger than a page which no limit bounds within 10,000 hits pays the first request on top of its scroll pages. With query.smart-limit off (the default) and no limit() in the traversal, that is every traversal whose mixed index result exceeds max-result-set-size; the lookups which stay within a page, and every limited query within 10,000 hits, are the ones which gain.

Tests

  • ElasticSearchSearcherTest (new, mocked client): the request of every path (size, from, track_total_hits, scroll flag), that a limited result and a page-sized unlimited result never open a scroll, that the scroll's hits replace the first request's, that the offset of a scrolled result is skipped on the client, that a limit beyond 10,000 bounds the scroll, that a page size of 10,000 scrolls at once, that closing the stream releases the scroll, and that scores are kept.
  • ElasticSearchScrollTest: the existing tests, plus stopping at the limit, releasing once, releasing on close(), and a failed release not failing the iteration.
  • RestClientScrollTest (new): the asynchronous request's method, path and body, and that a failure reported to its listener stays there.
  • SubqueryIteratorTest: the index stream is closed when the iterator is closed before the end and when it is exhausted.
  • ElasticsearchIndexTest (against a real cluster, page size 3): new tests read the cluster's own accounting (_nodes/stats/indices/search) to prove that limited queries larger than a page and unlimited queries which fit into a page open no scroll context (scroll_total unchanged), that a large unlimited result and one whose consumer stops after the first hit bring the open contexts back to the baseline observed before the test within seconds (so released, not expired), and that offsets beyond a page are applied for limited and unlimited raw queries, also with a sort. The shared IndexProviderTest.testScroll keeps covering result sizes below, at and above the page size and limits at and beyond it.
  • Locally, Java 11:
    • unit tests: ElasticSearchSearcherTest, ElasticSearchScrollTest, RestClientScrollTest (32, with RestClientRetryTest and ElasticSearchExceptionConversionTest alongside) and SubqueryIteratorTest, SubqueryIteratorCacheTest (16);
    • Elasticsearch 9.5.4: the whole ElasticsearchIndexTest (286 tests) and BerkeleyElasticsearchTest (92, the one skip is an @Disabled test), which drives SubqueryIterator against a real cluster;
    • OpenSearch 3.9.0, Elasticsearch 7.17.8 and Elasticsearch 6.6.0: the new context tests and testScroll (6 each), so the request shapes, the track_total_hits parameter of the first request and the body form of the scroll release work on every supported major version;
    • mvn validate (checkstyle, RAT) of both modules.

Measurements

Against a throwaway single-node Elasticsearch 9.5.4 container with one shard and 20,000 matching documents, replaying the request shapes of both versions with a small script (median of 7 runs, wall time from the client, took as reported by Elasticsearch and summed over the requests of a run):

Query Before After
direct index query offset(9000).limit(100) 183 requests, 326 ms wall, ES took 183 ms 1 request (from=9000, size=100), 2.9 ms wall, ES took 1 ms
graph query limit(5000) 101 requests, 102 ms wall, ES took 99 ms 1 request (size=5000), 6.4 ms wall, ES took 2 ms
graph query limit(200) 5 requests, 5.4 ms wall 1 request, 1.9 ms wall
lookup without a limit, 20 matches 2 requests (scroll + clear), 3.3 ms wall 1 request (size=51), 2.1 ms wall
query without a limit, 20,000 matches 402 requests, 448 ms wall, ES took 400 ms 403 requests (the first request, then the same scroll), 452 ms wall, ES took 401 ms

So the one-request path is cheaper on the cluster as well as for the client, including the from request of a direct index query: skipping 9,000 hits in one query phase cost Elasticsearch 1 ms, where scrolling past them page by page cost it 183 ms and 183 round trips. The only shape which pays is the unlimited query whose result is larger than a page, by one request, about 1 % here.

Not included

  • Point-in-time with search_after (Optimize ElasticSearch search queries to not always use Scroll API #1680 also mentions it). The scroll still serves results larger than a page; a follow-up can replace it where the version supports PIT.
  • A separate scroll page size for Elasticsearch. max-result-set-size remains both the page and the size of the first request of an unlimited query.

🤖 Generated with Claude Code

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Copilot review overview

Review effort: Lite
Findings: 2 Medium severity

Open (2)
What changed in this PR

This PR optimizes JanusGraph’s Elasticsearch index backend by avoiding the scroll API for results that fit in a single request, and by ensuring scroll contexts are released promptly (including on early consumer termination).

Changes:

  • Introduces ElasticSearchSearcher to unify and optimize hit fetching (single-request when possible; scroll only when needed).
  • Makes scroll cleanup best-effort and asynchronous (DELETE /_search/scroll with body) and improves scroll lifecycle management (limit-aware + close-aware).
  • Expands unit/integration tests and updates docs/changelog to describe the new request/scroll behavior.
File Description
janusgraph-es/​src/​main/​java/​org/​janusgraph/​diskstorage/​es/​ElasticSearchSearcher.java New shared search-fetching strategy to avoid scrolls unless necessary.
janusgraph-es/​src/​main/​java/​org/​janusgraph/​diskstorage/​es/​ElasticSearchScroll.java Releases scroll contexts earlier (limit/close/short-page) and makes release best-effort.
janusgraph-es/​src/​main/​java/​org/​janusgraph/​diskstorage/​es/​rest/​RestElasticSearchClient.java Makes scroll deletion asynchronous and switches to body-based scroll clear request.
janusgraph-es/​src/​main/​java/​org/​janusgraph/​diskstorage/​es/​ElasticSearchIndex.java Routes IndexQuery/RawQuery fetching through the new ElasticSearchSearcher.
janusgraph-es/​src/​main/​java/​org/​janusgraph/​diskstorage/​es/​ElasticSearchClient.java Documents new expectations (best-effort, non-blocking scroll release).
janusgraph-core/​src/​main/​java/​org/​janusgraph/​graphdb/​util/​SubqueryIterator.java Ensures index result streams are closed when the iterator closes/exhausts.
janusgraph-es/​src/​test/​java/​org/​janusgraph/​diskstorage/​es/​ElasticSearchSearcherTest.java New unit tests validating request shapes and scroll decision logic.
janusgraph-es/​src/​test/​java/​org/​janusgraph/​diskstorage/​es/​ElasticSearchScrollTest.java Extends tests for limit-aware stopping and close-time release behavior.
janusgraph-es/​src/​test/​java/​org/​janusgraph/​diskstorage/​es/​rest/​RestClientScrollTest.java New tests asserting async scroll delete request shape and behavior on failure.
janusgraph-es/​src/​test/​java/​org/​janusgraph/​diskstorage/​es/​ElasticsearchIndexTest.java Adds integration tests verifying scroll context accounting and offset handling.
janusgraph-core/​src/​test/​java/​org/​janusgraph/​graphdb/​util/​SubqueryIteratorTest.java Adds tests ensuring index streams close on early termination/exhaustion.
docs/​index-backend/​elasticsearch.md Documents new “Search Requests” behavior and scroll context lifecycle.
docs/​changelog.md Notes behavioral change and operational impact around scroll contexts.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Copilot review overview

Review effort: Lite
Findings: 1 High severity · 2 Medium severity

Open (3)
Resolved since last review (2)

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread docs/changelog.md Resolved
Comment thread docs/index-backend/elasticsearch.md Resolved
Comment thread docs/index-backend/elasticsearch.md Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🔵 Needs a closer look

Cross-module resource-lifecycle changes across several Elasticsearch and OpenSearch versions warrant final human validation.

Review effort: Balanced
Findings: None

Resolved since last review (4)

@porunov porunov added this to the 1.2.0 milestone Sep 30, 2026
Fixes JanusGraph#1680

Every mixed index query whose limit was at least max-result-set-size
(50), and every query without a limit, read its result through the
scroll API in pages of that size. A query with a limit left its scroll
context open until scroll-keep-alive expired, because the result stream
stopped at the limit before the last page. So limit(1000) was 20
requests and a 60 s scroll context, and a lookup without a limit was two
requests, the scroll search and the synchronous release of its context.
Elasticsearch also counted every match, as a scroll may not switch the
total off.

* ElasticSearchSearcher fetches a result which a limit bounds within
  10,000 hits (Elasticsearch's default index.max_result_window) in one
  request of exactly that size, without counting the total, and lets
  Elasticsearch apply the offset of a raw query.
* A query without a limit, or with a larger one, first asks for one hit
  more than a page after the offset. Only when the result is larger does
  a scroll take over from the start, in pages of max-result-set-size.
* ElasticSearchScroll stops at the limit, releases the context as soon
  as the limit is within the pages received or a page comes back short,
  and is closed when the result stream is closed. A release which fails
  no longer fails the query.
* RestElasticSearchClient releases a scroll asynchronously, with the id
  in the request body, and warns once when the cluster rejects the
  release.
* SubqueryIterator closes the index result stream when it is closed or
  exhausted, so a traversal which Gremlin Server closes after it stopped
  early hands the context back. A result larger than a page costs one
  request more than before, the first request; a traversal abandoned
  without close() still leaves its context to expire, as before.
* Tests: ElasticSearchSearcherTest (request shapes for every path),
  ElasticSearchScrollTest (limit, close, failed release),
  RestClientScrollTest, SubqueryIteratorTest, and ElasticsearchIndexTest
  reads the cluster's search context accounting to prove that limited
  and page-sized results open no scroll context and that scrolls are
  released, also when the consumer stops early.
* The Elasticsearch docs describe how results are fetched, and the
  changelog names the change.

Co-Authored-By: Oleksandr Porunov <alexandr.porunov@gmail.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Oleksandr Porunov <alexandr.porunov@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Optimize ElasticSearch search queries to not always use Scroll API

2 participants