Repository navigation
Use the Elasticsearch scroll API only for results larger than a page - #4994
Conversation
There was a problem hiding this comment.
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
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
ElasticSearchSearcherto unify and optimize hit fetching (single-request when possible; scroll only when needed). - Makes scroll cleanup best-effort and asynchronous (
DELETE /_search/scrollwith 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.
d9cc264 to
59105e0
Compare
There was a problem hiding this comment.
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
Open (3)
compat.createRequestBody(...)was previously treated as potentially returningnull(and/or… · New IfQuery.NO_LIMITisInteger.MAX_VALUE(common pattern), a finite largelimitcombined with… · New The Javadoc claims this predicate identifies client errors “which every later release will meet as… · New
59105e0 to
1a37b9f
Compare
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Large finite offset-and-limit combinations can truncate valid results, and the documentation omits immediate-scroll cases.
Review effort: Balanced
Findings: 1
Open (4)
Use long counters to preserve large finite offset and limit ranges · New Mention immediate scrolling for offsets beyond the result window · New Document immediate scrolling when the offset exceeds the result window · New Document immediate scrolling when offset plus page size exceeds the window · New
Resolved since last review (3)
1a37b9f to
ffdb5f7
Compare
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>
ffdb5f7 to
1fc7472
Compare



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.querydecideduseScroll = size >= max-result-set-size(50 by default). So:limit(1000)was 20 sequential requests, each a query and fetch phase on every shard..limit()stopped before the last, short page, andElasticSearchScrollonly released the context on a short page. The context lived untilscroll-keep-alive(60 s) expired.LimitAdjustingIterator, which re-executes with a doubled limit, abandoned one scroll per step.DELETE /_search/scroll/<id>when the first page was short, which is the common case. Withquery.smart-limit=falseandquery.hard-max-limitat its default, a plaing.V().has(mixedIndexedKey, value)is such a query. A failed release failed the query.track_total_hitsoff.search.max_open_scroll_contextto 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:index.max_result_window, which boundsfrom + size; JanusGraph lifts it on the indexes it creates but not on external ones) is one request withsize = limit,track_total_hits: false, andfrom = offsetfor a raw query, whose offset was skipped on the client before.max-result-set-size + 1hits 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 ofmax-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 along, so any finiteoffset + limitis represented whole.ElasticSearchScrolltakes 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 registersonClosefor it. A release which fails no longer fails a search whose hits are complete: the context expires on its own.RestElasticSearchClient.deleteScrollsendsDELETE /_search/scrollasynchronously 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.SubqueryIteratorkeeps the index result stream and closes it when it is closed, whichcomputeNextdoes once the iterator is exhausted.Traversal.close()reaches it throughGraphStepand 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 afterscroll-keep-alive, as before; the docs say so.elasticsearch.mdgets a "Search Requests" section, and the OpenSearch paragraph onsetup-max-open-scroll-contextsnotes 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-sizeoption 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. Withquery.smart-limitoff (the default) and nolimit()in the traversal, that is every traversal whose mixed index result exceedsmax-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 onclose(), 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_totalunchanged), 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 sharedIndexProviderTest.testScrollkeeps covering result sizes below, at and above the page size and limits at and beyond it.ElasticSearchSearcherTest,ElasticSearchScrollTest,RestClientScrollTest(32, withRestClientRetryTestandElasticSearchExceptionConversionTestalongside) andSubqueryIteratorTest,SubqueryIteratorCacheTest(16);ElasticsearchIndexTest(286 tests) andBerkeleyElasticsearchTest(92, the one skip is an@Disabledtest), which drivesSubqueryIteratoragainst a real cluster;testScroll(6 each), so the request shapes, thetrack_total_hitsparameter 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,
tookas reported by Elasticsearch and summed over the requests of a run):offset(9000).limit(100)took183 msfrom=9000, size=100), 2.9 ms wall, EStook1 mslimit(5000)took99 mssize=5000), 6.4 ms wall, EStook2 mslimit(200)size=51), 2.1 ms walltook400 mstook401 msSo the one-request path is cheaper on the cluster as well as for the client, including the
fromrequest 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
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.max-result-set-sizeremains both the page and the size of the first request of an unlimited query.🤖 Generated with Claude Code