Skip to content

Commit bdfb137

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 68ed00e commit bdfb137

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
@@ -703,6 +703,23 @@ public void testNumericLongOrDateSortOptimization() throws Exception {
703703
searchContext.sort(sortAndFormats);
704704
QueryPhase.executeInternal(searchContext);
705705
assertSortResults(searchContext.queryResult().topDocs().topDocs, (long) numDocs, true);
706+
707+
// 5. Test that sort optimization is NOT run with size 0
708+
{
709+
sortAndFormats = new SortAndFormats(longSort, new DocValueFormat[]{DocValueFormat.RAW});
710+
searchContext = spy(new TestSearchContext(null, indexShard, newContextSearcher(reader)));
711+
when(searchContext.mapperService()).thenReturn(mapperService);
712+
searchContext.sort(sortAndFormats);
713+
searchContext.parsedQuery(new ParsedQuery(new MatchAllDocsQuery()));
714+
searchContext.setTask(new SearchShardTask(123L, "", "", "", null, Collections.emptyMap()));
715+
searchContext.setSize(0);
716+
717+
QueryPhase.executeInternal(searchContext);
718+
TotalHits totalHits = searchContext.queryResult().topDocs().topDocs.totalHits;
719+
assertEquals(TotalHits.Relation.EQUAL_TO, totalHits.relation);
720+
assertEquals(numDocs, totalHits.value);
721+
}
722+
706723
reader.close();
707724
dir.close();
708725
}

0 commit comments

Comments
 (0)