Skip to content

Commit ffdb5f7

Browse files
porunovclaude
andcommitted
Use the Elasticsearch scroll API only for results larger than a page
Fixes #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>
1 parent 5e2a8ee commit ffdb5f7

13 files changed

Lines changed: 1124 additions & 94 deletions

File tree

‎docs/changelog.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -728,6 +728,27 @@ once, so bulk requests grow with the size of the documents they update; an updat
728728
`index.[X].elasticsearch.bulk-chunk-size-limit-bytes` is sent without it, as before this change, rather than failing. A
729729
mixed index on a cdc-only backend, whose documents are written asynchronously, is not affected.
730730

731+
##### Elasticsearch searches open a scroll context only for results larger than a page
732+
733+
Every mixed index query whose limit was at least `index.[X].max-result-set-size` (50 by default), and every query
734+
without a limit, read its result through the scroll API in pages of that size. A query with a limit whose result had at
735+
least as many hits also left its scroll context open until `index.[X].elasticsearch.scroll-keep-alive` expired, because
736+
the result stream stopped at the limit before the last page. So a `limit(1000)` was 20 requests and a 60 s scroll
737+
context, and a lookup without a limit was two requests, the scroll search and the one which released its context, both
738+
waited for. Elasticsearch also had to count every match of these queries, as a scroll may not switch the total off.
739+
JanusGraph now fetches a result whose offset and limit together are within 10,000 hits, Elasticsearch's default
740+
`index.max_result_window`, in one request of exactly that size and without counting the total, and Elasticsearch
741+
applies the offset of a direct index query in that request. A query without a limit, or beyond that size, first asks
742+
for one hit more than a page after the offset, or for what is left up to the 10,000th hit if that is less; only when
743+
the result is larger, or the offset is 10,000 or more, does a scroll take over, which costs such a result one request
744+
more than before. The scroll context is released as soon as the result has been read to its end,
745+
the limit is reached, or the traversal is closed, which JanusGraph Server does after every request; embedded code
746+
should close a traversal it abandons before its end, otherwise the context expires after the keep-alive as before. The
747+
release no longer waits for the cluster's answer, and a release which fails no longer fails the query; a release the
748+
cluster rejects is logged as a warning once. Deployments which set
749+
`index.[X].elasticsearch.setup-max-open-scroll-contexts` to `false`, such as Amazon OpenSearch Service, are therefore
750+
far less likely to reach the cluster's limit of open scroll contexts.
751+
731752
##### `tx.max-commit-time` now defaults to 300 s and is checked against the least a commit may take
732753

733754
`tx.max-commit-time` is the time after which transaction recovery considers a transaction failed and restores the index

‎docs/index-backend/elasticsearch.md‎

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,9 @@ index.search.elasticsearch.http.auth.basic.password=<password>
308308

309309
JanusGraph raises the cluster setting `search.max_open_scroll_context` when it opens the index. If the
310310
JanusGraph user may not update cluster settings (`cluster:admin/settings/update`), set
311-
`index.[X].elasticsearch.setup-max-open-scroll-contexts` to `false`.
311+
`index.[X].elasticsearch.setup-max-open-scroll-contexts` to `false`. Only a result larger than a page holds a
312+
scroll context, and it is released as soon as the result has been read or its traversal is closed (see
313+
[Search Requests](#search-requests)), so the default limit of 500 open contexts per node is rarely reached.
312314

313315
Amazon OpenSearch Service domains which use IAM based access control need signed requests, which a
314316
[custom authenticator](#rest-client-custom-http-authentication) can provide. These domains don't allow
@@ -383,6 +385,36 @@ diagnostic utility like `netstat`. Check the JanusGraph configuration.
383385

384386
## Optimizing Elasticsearch
385387

388+
### Search Requests
389+
390+
JanusGraph fetches the result of a mixed index query with as few requests as it can tell the result needs:
391+
392+
* A query whose offset and limit together are at most 10,000, Elasticsearch's default
393+
`index.max_result_window`, is one search request of exactly that size. Elasticsearch applies the offset of a
394+
[direct index query](direct-index-query.md) in that request.
395+
* A query without a limit, or beyond that size, first asks for one hit more than a page after the offset, or
396+
for what is left up to the 10,000th hit if that is less. The page size is `index.[X].max-result-set-size`
397+
(50 by default). When fewer hits come back than were asked for, that is the whole result. Only a larger
398+
result is read through the
399+
[scroll API](https://www.elastic.co/guide/en/elasticsearch/reference/current/paginate-search-results.html#scroll-search-results),
400+
from its first hit on and in pages of that size, which costs such a result one request more than the pages
401+
alone. An offset of 10,000 or more leaves nothing to ask for first, and such a query is read through a
402+
scroll at once, however small its result.
403+
404+
A scroll context is released as soon as the result has been read to its end, the limit is reached, or the
405+
traversal is closed, which JanusGraph Server does after every request. Embedded code which abandons a traversal
406+
before its end should close it, for example with try-with-resources; otherwise the context expires after
407+
`index.[X].elasticsearch.scroll-keep-alive` seconds (60 by default), as it did before JanusGraph 1.2.0. A
408+
release which the cluster rejects, for example for want of the privilege to clear scrolls, is logged as a
409+
warning once. Neither the single request nor the first request of an unlimited query counts the total number
410+
of hits; the pages of a scroll do, because Elasticsearch requires it. On an index which JanusGraph did not
411+
create, `index.max_result_window` must allow 10,000 hits, which is its default; JanusGraph lifts it on the
412+
indexes it creates.
413+
414+
If large results are common, a larger `index.[X].max-result-set-size` trades the size of one response for the
415+
number of requests: a result of 5,000 hits is about 100 scroll pages of 50, and one request when it is limited
416+
to 5,000.
417+
386418
### Write Optimization
387419

388420
For [bulk loading](../operations/bulk-loading.md) or other write-intense applications,

‎janusgraph-core/src/main/java/org/janusgraph/graphdb/util/SubqueryIterator.java‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,10 @@ public class SubqueryIterator extends CloseableAbstractIterator<JanusGraphElemen
4848

4949
private Iterator<? extends JanusGraphElement> elementIterator;
5050

51+
//Kept to be closed: an index backend may hold a resource behind its stream, such as an Elasticsearch scroll
52+
//context, which closing the stream hands back
53+
private final Stream<?> indexStream;
54+
5155
private List<Object> currentIds;
5256

5357
private QueryProfiler profiler;
@@ -86,6 +90,7 @@ public SubqueryIterator(JointIndexQuery.Subquery subQuery, IndexSerializer index
8690
throw new JanusGraphException("Could not call index", e);
8791
}
8892
}
93+
indexStream = stream;
8994
//Membership is tested once for every element the first index returns, and otherResults is deliberately
9095
//unbounded: StandardJanusGraphTx passes NO_LIMIT to processIntersectingRetrievals so that the intersection is
9196
//complete. Scanning the list for each element would make the intersection cost O(n*m).
@@ -141,6 +146,8 @@ public void close() {
141146
profiler.stopTimer();
142147
isTimerRunning = false;
143148
}
149+
//After the probe above, which may still read from it. Closing a stream twice is harmless
150+
indexStream.close();
144151
}
145152

146153
/**

‎janusgraph-core/src/test/java/org/janusgraph/graphdb/util/SubqueryIteratorTest.java‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,12 @@
2727
import java.util.Arrays;
2828
import java.util.Collections;
2929
import java.util.List;
30+
import java.util.concurrent.atomic.AtomicBoolean;
31+
import java.util.stream.Stream;
3032

3133
import static org.junit.jupiter.api.Assertions.assertEquals;
34+
import static org.junit.jupiter.api.Assertions.assertFalse;
35+
import static org.junit.jupiter.api.Assertions.assertTrue;
3236
import static org.mockito.ArgumentMatchers.any;
3337
import static org.mockito.Mockito.mock;
3438
import static org.mockito.Mockito.when;
@@ -106,6 +110,41 @@ public void shouldNotBeConfusedByADuplicateInTheOtherIndexResults() {
106110
Arrays.asList(ID_IN_EVERY_INDEX, ID_IN_EVERY_INDEX), Integer.MAX_VALUE));
107111
}
108112

113+
private SubqueryIterator iteratorOver(Stream<?> indexResults) {
114+
final JointIndexQuery.Subquery subQuery = mock(JointIndexQuery.Subquery.class);
115+
when(subQuery.getProfiler()).thenReturn(QueryProfiler.NO_OP);
116+
final IndexSerializer indexSerializer = mock(IndexSerializer.class);
117+
when(indexSerializer.query(any(), any(), any())).thenAnswer(invocation -> indexResults);
118+
final SubqueryCache indexCache = mock(SubqueryCache.class);
119+
when(indexCache.getIfPresent(any())).thenReturn(null);
120+
return new SubqueryIterator(subQuery, indexSerializer, mock(BackendTransaction.class),
121+
mock(StandardJanusGraphTx.class), indexCache, Integer.MAX_VALUE, id -> mock(JanusGraphElement.class), null);
122+
}
123+
124+
//An index backend may hold a resource behind its stream, such as an Elasticsearch scroll context, which
125+
//closing the stream hands back. A consumer which stops early only ever closes the iterator
126+
@Test
127+
public void shouldCloseTheIndexStreamWhenClosedBeforeTheEnd() {
128+
final AtomicBoolean closed = new AtomicBoolean();
129+
final SubqueryIterator iterator = iteratorOver(Stream.of(1L, 2L, 3L).onClose(() -> closed.set(true)));
130+
131+
iterator.next();
132+
assertFalse(closed.get());
133+
iterator.close();
134+
135+
assertTrue(closed.get());
136+
}
137+
138+
@Test
139+
public void shouldCloseTheIndexStreamOnceExhausted() {
140+
final AtomicBoolean closed = new AtomicBoolean();
141+
final SubqueryIterator iterator = iteratorOver(Stream.of(1L, 2L).onClose(() -> closed.set(true)));
142+
143+
iterator.forEachRemaining(element -> { });
144+
145+
assertTrue(closed.get());
146+
}
147+
109148
@Test
110149
public void shouldNotDependOnStreamOrderMatchingTheOtherIndexOrder() {
111150
//The streamed order is preserved, and is independent of the order the other indexes reported

‎janusgraph-es/src/main/java/org/janusgraph/diskstorage/es/ElasticSearchClient.java‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,11 @@ default boolean usesMappingTypes() {
8585

8686
ElasticSearchResponse search(String scrollId) throws IOException;
8787

88+
/**
89+
* Releases a scroll context which is no longer read. It is a courtesy to the cluster rather than part of the
90+
* search: the context expires after the scroll keep-alive on its own, so an implementation may return before
91+
* the cluster has released it, and the caller doesn't fail its search over a release which failed.
92+
*/
8893
void deleteScroll(String scrollId) throws IOException;
8994

9095
void addAlias(String alias, String index) throws IOException;

‎janusgraph-es/src/main/java/org/janusgraph/diskstorage/es/ElasticSearchIndex.java‎

Lines changed: 17 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -83,20 +83,16 @@
8383
import java.util.Collections;
8484
import java.util.HashMap;
8585
import java.util.HashSet;
86-
import java.util.Iterator;
8786
import java.util.List;
8887
import java.util.Map;
8988
import java.util.Objects;
9089
import java.util.Set;
91-
import java.util.Spliterator;
92-
import java.util.Spliterators;
9390
import java.util.UUID;
9491
import java.util.concurrent.ConcurrentHashMap;
9592
import java.util.function.Function;
9693
import java.util.stream.Collectors;
9794
import java.util.stream.IntStream;
9895
import java.util.stream.Stream;
99-
import java.util.stream.StreamSupport;
10096

10197
import static org.janusgraph.diskstorage.configuration.ConfigOption.disallowEmpty;
10298
import static org.janusgraph.diskstorage.es.ElasticSearchConstants.ES_DOC_KEY;
@@ -450,18 +446,13 @@ public class ElasticSearchIndex implements IndexProvider {
450446
private static final String MAX_OPEN_SCROLL_CONTEXT_PARAMETER = "search.max_open_scroll_context";
451447
private static final Map<String, Object> MAX_RESULT_WINDOW = ImmutableMap.of("index.max_result_window", Integer.MAX_VALUE);
452448

453-
private static final Parameter[] NULL_PARAMETERS = null;
454-
455-
private static final String TRACK_TOTAL_HITS_PARAMETER = "track_total_hits";
456-
private static final Parameter[] TRACK_TOTAL_HITS_DISABLED_PARAMETERS = new Parameter[]{new Parameter<>(TRACK_TOTAL_HITS_PARAMETER, false)};
457-
private static final Map<String, Object> TRACK_TOTAL_HITS_DISABLED_REQUEST_BODY = ImmutableMap.of(TRACK_TOTAL_HITS_PARAMETER, false);
458-
459449
private final Function<String, String> generateIndexStoreNameFunction = this::generateIndexStoreName;
460450
private final Map<String, String> indexStoreNamesCache = new ConcurrentHashMap<>();
461451
private final boolean indexStoreNameCacheEnabled;
462452

463453
private final AbstractESCompat compat;
464454
private final ElasticSearchClient client;
455+
private final ElasticSearchSearcher searcher;
465456
private final String indexName;
466457
private final int batchSize;
467458
private final boolean useExternalMappings;
@@ -501,6 +492,7 @@ public ElasticSearchIndex(Configuration config) throws BackendException {
501492
checkClusterHealth(config.get(HEALTH_REQUEST_TIMEOUT));
502493

503494
compat = ESCompatUtils.acquireCompatForVersion(client.getMajorVersion());
495+
searcher = new ElasticSearchSearcher(client, compat, batchSize);
504496

505497
indexSetting = ElasticSearchSetup.getSettingsFromJanusGraphConf(config);
506498

@@ -1551,37 +1543,18 @@ public Stream<String> query(IndexQuery query, KeyInformation.IndexRetriever info
15511543
if (!query.getOrder().isEmpty()) {
15521544
addOrderToQuery(informations, sr, query.getOrder(), query.getStore());
15531545
}
1554-
sr.setFrom(0);
1555-
if (query.hasLimit()) {
1556-
sr.setSize(Math.min(query.getLimit(), batchSize));
1557-
} else {
1558-
sr.setSize(batchSize);
1559-
}
1560-
15611546
sr.setDisableSourceRetrieval(true);
15621547

1563-
ElasticSearchResponse response;
15641548
try {
1565-
final String indexStoreName = getIndexStoreName(query.getStore());
1566-
final boolean useScroll = sr.getSize() >= batchSize;
1567-
response = client.search(indexStoreName,
1568-
compat.createRequestBody(sr, useScroll? NULL_PARAMETERS : TRACK_TOTAL_HITS_DISABLED_PARAMETERS),
1569-
useScroll);
1570-
log.debug("First Executed query [{}] in {} ms", query.getCondition(), response.getTook());
1571-
final Iterator<RawQuery.Result<String>> resultIterator = getResultsIterator(useScroll, response, sr.getSize());
1572-
final Stream<RawQuery.Result<String>> toReturn
1573-
= StreamSupport.stream(Spliterators.spliteratorUnknownSize(resultIterator, Spliterator.ORDERED), false);
1574-
return (query.hasLimit() ? toReturn.limit(query.getLimit()) : toReturn).map(RawQuery.Result::getResult);
1575-
} catch (final IOException | UncheckedIOException e) {
1549+
log.debug("Executing query [{}]", query.getCondition());
1550+
return searcher.search(getIndexStoreName(query.getStore()), sr, null, 0, query.getLimit())
1551+
.map(RawQuery.Result::getResult);
1552+
} catch (final IOException e) {
15761553
//Classified like a write failure, so that BackendOperation reattempts a transient one within the read time
15771554
throw convert(e);
15781555
}
15791556
}
15801557

1581-
private Iterator<RawQuery.Result<String>> getResultsIterator(boolean useScroll, ElasticSearchResponse response, int windowSize){
1582-
return (useScroll)? new ElasticSearchScroll(client, response, windowSize) : response.getResults().iterator();
1583-
}
1584-
15851558
private String convertToEsDataType(Class<?> dataType, Mapping mapping) {
15861559
if(String.class.isAssignableFrom(dataType)) {
15871560
return "string";
@@ -1614,35 +1587,6 @@ else if (Geoshape.class.isAssignableFrom(dataType)) {
16141587
return null;
16151588
}
16161589

1617-
private ElasticSearchResponse runCommonQuery(RawQuery query, KeyInformation.IndexRetriever informations, BaseTransaction tx, int size,
1618-
boolean useScroll) throws BackendException{
1619-
final ElasticSearchRequest sr = new ElasticSearchRequest();
1620-
sr.setQuery(compat.queryString(query.getQuery()));
1621-
if (!query.getOrders().isEmpty()) {
1622-
addOrderToQuery(informations, sr, query.getOrders(), query.getStore());
1623-
}
1624-
sr.setFrom(0);
1625-
sr.setSize(size);
1626-
sr.setDisableSourceRetrieval(true);
1627-
try {
1628-
Map<String, Object> requestBody = compat.createRequestBody(sr, query.getParameters());
1629-
if(!useScroll) {
1630-
if (requestBody == null) {
1631-
requestBody = TRACK_TOTAL_HITS_DISABLED_REQUEST_BODY;
1632-
} else {
1633-
requestBody.put(TRACK_TOTAL_HITS_PARAMETER, false);
1634-
}
1635-
}
1636-
return client.search(
1637-
getIndexStoreName(query.getStore()),
1638-
requestBody,
1639-
useScroll);
1640-
} catch (final IOException | UncheckedIOException e) {
1641-
//Classified like a write failure, so that BackendOperation reattempts a transient one within the read time
1642-
throw convert(e);
1643-
}
1644-
}
1645-
16461590
private long runCountQuery(RawQuery query) throws BackendException{
16471591
try {
16481592
long countTotal = client.countTotal(
@@ -1670,22 +1614,20 @@ private void addOrderToQuery(KeyInformation.IndexRetriever informations, Elastic
16701614
@Override
16711615
public Stream<RawQuery.Result<String>> query(RawQuery query, KeyInformation.IndexRetriever information,
16721616
BaseTransaction tx) throws BackendException {
1673-
final int size = query.hasLimit() ? Math.min(query.getLimit() + query.getOffset(), batchSize) : batchSize;
1674-
final boolean useScroll = size >= batchSize;
1675-
final ElasticSearchResponse response = runCommonQuery(query, information, tx, size, useScroll);
1676-
log.debug("First Executed query [{}] in {} ms", query.getQuery(), response.getTook());
1677-
final Iterator<RawQuery.Result<String>> resultIterator;
1617+
final ElasticSearchRequest sr = new ElasticSearchRequest();
1618+
sr.setQuery(compat.queryString(query.getQuery()));
1619+
if (!query.getOrders().isEmpty()) {
1620+
addOrderToQuery(information, sr, query.getOrders(), query.getStore());
1621+
}
1622+
sr.setDisableSourceRetrieval(true);
16781623
try {
1679-
//A scroll whose first page is also its last is closed right here, which is one more request that can
1680-
//fail the way the search itself can, so it is classified the same way
1681-
resultIterator = getResultsIterator(useScroll, response, size);
1682-
} catch (final UncheckedIOException e) {
1624+
log.debug("Executing query [{}]", query.getQuery());
1625+
return searcher.search(getIndexStoreName(query.getStore()), sr, query.getParameters(), query.getOffset(),
1626+
query.getLimit());
1627+
} catch (final IOException e) {
1628+
//Classified like a write failure, so that BackendOperation reattempts a transient one within the read time
16831629
throw convert(e);
16841630
}
1685-
final Stream<RawQuery.Result<String>> toReturn
1686-
= StreamSupport.stream(Spliterators.spliteratorUnknownSize(resultIterator, Spliterator.ORDERED),
1687-
false).skip(query.getOffset());
1688-
return query.hasLimit() ? toReturn.limit(query.getLimit()) : toReturn;
16891631
}
16901632

16911633
@Override

0 commit comments

Comments
 (0)