@@ -193,16 +193,14 @@ private SimpleTopDocsCollectorContext(IndexReader reader,
193193 this .topDocsSupplier = topDocsCollector ::topDocs ;
194194 this .totalHitsSupplier = topDocsCollector ::getTotalHits ;
195195 } else {
196- final boolean canEarlyTerminate = canEarlyTerminate (reader , sortAndFormats );
196+ /**
197+ * We explicitly don't track total hits in the topdocs collector, it can early terminate
198+ * if the sort matches the index sort.
199+ */
197200 final TopDocsCollector <?> topDocsCollector = TopFieldCollector .create (sortAndFormats .sort , numHits ,
198- (FieldDoc ) searchAfter , true , trackMaxScore , trackMaxScore , canEarlyTerminate == false );
201+ (FieldDoc ) searchAfter , true , trackMaxScore , trackMaxScore , false );
199202 this .topDocsSupplier = topDocsCollector ::topDocs ;
200- if (canEarlyTerminate && trackTotalHits ) {
201- /**
202- * The top docs collector can early terminate the query on each segment
203- * so we cannot rely on it to track the total number of hits
204- */
205-
203+ if (trackTotalHits ) {
206204 // implicit total hit counts are valid only when there is no filter collector in the chain
207205 int count = hasFilterCollector ? -1 : shortcutTotalHitCount (reader , query );
208206 if (count != -1 ) {
@@ -212,13 +210,14 @@ private SimpleTopDocsCollectorContext(IndexReader reader,
212210 } else {
213211 // wrap a collector that counts the total number of hits even
214212 // if the top docs collector terminates early
215- final TotalHitCountCollector countCollector = new TotalHitCountCollector ();
216- this .totalHitsSupplier = countCollector :: getTotalHits ;
217- this .collector = MultiCollector . wrap ( topDocsCollector , countCollector ) ;
213+ final TotalHitCountCollector countingCollector = new TotalHitCountCollector ();
214+ this .collector = MultiCollector . wrap ( topDocsCollector , countingCollector ) ;
215+ this .totalHitsSupplier = countingCollector :: getTotalHits ;
218216 }
219217 } else {
220- this . totalHitsSupplier = topDocsCollector :: getTotalHits ;
218+ // total hit count is not needed
221219 this .collector = topDocsCollector ;
220+ this .totalHitsSupplier = topDocsCollector ::getTotalHits ;
222221 }
223222 }
224223 }
0 commit comments