Skip to content

Commit 904fe1d

Browse files
Don't run sort optimization on size=0 (#57044)
Sort optimization creates TopFieldCollector that errors when size=0. This ensures that sort optimization is not run when size=0. Closes #56923
1 parent 0e73721 commit 904fe1d

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

server/src/main/java/org/elasticsearch/search/query/QueryPhase.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ static boolean executeInternal(SearchContext searchContext) throws QueryPhaseExe
244244

245245
CheckedConsumer<List<LeafReaderContext>, IOException> leafSorter = l -> {};
246246
// try to rewrite numeric or date sort to the optimized distanceFeatureQuery
247-
if ((searchContext.sort() != null) && SYS_PROP_REWRITE_SORT) {
247+
if ((searchContext.sort() != null) && (searchContext.size() > 0) && SYS_PROP_REWRITE_SORT) {
248248
Query rewrittenQuery = tryRewriteLongSort(searchContext, searcher.getIndexReader(), query, hasFilterCollector);
249249
if (rewrittenQuery != null) {
250250
query = rewrittenQuery;

server/src/test/java/org/elasticsearch/search/query/QueryPhaseTests.java

+17
Original file line numberDiff line numberDiff line change
@@ -711,6 +711,23 @@ public void testNumericLongOrDateSortOptimization() throws Exception {
711711
searchContext.sort(sortAndFormats);
712712
QueryPhase.executeInternal(searchContext);
713713
assertSortResults(searchContext.queryResult().topDocs().topDocs, (long) numDocs, true);
714+
715+
// 5. Test that sort optimization is NOT run with size 0
716+
{
717+
sortAndFormats = new SortAndFormats(longSort, new DocValueFormat[]{DocValueFormat.RAW});
718+
searchContext = spy(new TestSearchContext(null, indexShard, newContextSearcher(reader)));
719+
when(searchContext.mapperService()).thenReturn(mapperService);
720+
searchContext.sort(sortAndFormats);
721+
searchContext.parsedQuery(new ParsedQuery(new MatchAllDocsQuery()));
722+
searchContext.setTask(new SearchShardTask(123L, "", "", "", null, Collections.emptyMap()));
723+
searchContext.setSize(0);
724+
725+
QueryPhase.executeInternal(searchContext);
726+
TotalHits totalHits = searchContext.queryResult().topDocs().topDocs.totalHits;
727+
assertEquals(TotalHits.Relation.EQUAL_TO, totalHits.relation);
728+
assertEquals(numDocs, totalHits.value);
729+
}
730+
714731
reader.close();
715732
dir.close();
716733
}

0 commit comments

Comments
 (0)