Skip to content

Commit 4cf49bc

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 b3426dd commit 4cf49bc

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

0 commit comments

Comments
 (0)