jpountz commented on a change in pull request #754: LUCENE-8875: Introduce 
Optimized Collector For Large Number Of Hits
URL: https://github.com/apache/lucene-solr/pull/754#discussion_r300999896
 
 

 ##########
 File path: 
lucene/sandbox/src/java/org/apache/lucene/search/LargeNumHitsTopDocsCollector.java
 ##########
 @@ -0,0 +1,177 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.lucene.search;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+import org.apache.lucene.index.LeafReaderContext;
+
+import static org.apache.lucene.search.TopDocsCollector.EMPTY_TOPDOCS;
+
+/**
+ * Optimized collector for large number of hits.
+ * The collector maintains an ArrayList of hits until it accumulates
+ * the requested number of hits. Post that, it builds a Priority Queue
+ * and starts filtering further hits based on the minimum competitive
+ * score.
+ */
+public class LargeNumHitsTopDocsCollector implements Collector {
+  private final List<ScoreDoc> hits = new ArrayList<>();
+  private final int numHits;
+  HitQueue pq;
+  ScoreDoc pqTop;
+  int totalHits;
+  /** Whether {@link #totalHits} is exact or a lower bound. */
+  protected TotalHits.Relation totalHitsRelation = TotalHits.Relation.EQUAL_TO;
+
+  public LargeNumHitsTopDocsCollector(int numHits) {
+    this.numHits = numHits;
+    this.totalHits = 0;
+  }
+
+  // We always return COMPLETE since this collector should ideally
+  // be used only with large number of hits case
+  @Override
+  public ScoreMode scoreMode() {
+    return ScoreMode.COMPLETE;
+  }
+
+  @Override
+  public LeafCollector getLeafCollector(LeafReaderContext context) {
+    final int docBase = context.docBase;
+    return new TopScoreDocCollector.ScorerLeafCollector() {
+
+      @Override
+      public void setScorer(Scorable scorer) throws IOException {
+        super.setScorer(scorer);
+        updateMinCompetitiveScore(scorer);
+      }
+
+      @Override
+      public void collect(int doc) throws IOException {
+        float score = scorer.score();
+
+        // This collector relies on the fact that scorers produce positive 
values:
+        assert score >= 0; // NOTE: false for NaN
+
+        if (totalHits < numHits) {
+          hits.add(new ScoreDoc(doc, score));
+          totalHits++;
+          return;
+        } else if (totalHits == numHits) {
+          // Convert the list to a priority queue
+
+          // We should get here only when priority queue
+          // has been built
+          assert pq == null;
+          assert pqTop == null;
+          pq = new HitQueue(numHits, false);
+
+          for (int i = 0; i < hits.size(); i++) {
+            pq.add(hits.get(i));
+          }
+
+          pqTop = pq.top();
+        }
+
+        if (score > pqTop.score) {
+          pqTop.doc = doc + docBase;
+          pqTop.score = score;
+          pqTop = pq.updateTop();
+          updateMinCompetitiveScore(scorer);
+        }
+        ++totalHits;
+      }
+    };
+  }
+
+  protected void updateMinCompetitiveScore(Scorable scorer) throws IOException 
{
+    if (pqTop != null) {
+      scorer.setMinCompetitiveScore(Math.nextUp(pqTop.score));
+    }
+    totalHitsRelation = TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO;
+  }
+
+  public TopDocs topDocs(int howMany) {
+
+    if (howMany <= 0 || howMany > totalHits) {
+      throw new IllegalArgumentException("Incorrect number of hits requested");
+    }
+
+    ScoreDoc[] results = new ScoreDoc[howMany];
+
+    // Get the requested results from either hits list or PQ
+    populateResults(results, howMany);
+
+    return newTopDocs(results);
+  }
+
+  /**
+   * Populates the results array with the ScoreDoc instances. This can be
+   * overridden in case a different ScoreDoc type should be returned.
+   */
+  protected void populateResults(ScoreDoc[] results, int howMany) {
+    if (pq != null) {
+      assert totalHits >= numHits;
+      for (int i = howMany - 1; i >= 0; i--) {
+        results[i] = pq.pop();
+      }
+      return;
+    }
+
+    // Total number of hits collected were less than numHits
+    assert totalHits < numHits;
+    Collections.sort(hits, new Comparator<ScoreDoc>() {
+      @Override
+      public int compare(ScoreDoc o1, ScoreDoc o2) {
+        if (o1.score < o2.score) {
+          return -1;
+        }
+        else if (o1.score > o2.score) {
+          return 1;
+        }
+
+        assert o1.doc != o2.doc;
+
+        return o1.doc > o2.doc ? 1 : -1;
+      }
+    });
 
 Review comment:
   `Comparator.comparing(scoreDoc -> 
scoreDoc.score).reversed().thenComparing(scoreDoc -> scoreDoc.doc)`?

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to