--- lucene-2.2.0/src/java/org/apache/lucene/search/Hits.java 2007-06-17 07:20:34.000000000 +0200 +++ lucene-2.2.0-patch/src/java/org/apache/lucene/search/Hits.java 2007-07-09 18:08:36.000000000 +0200 @@ -45,12 +45,16 @@ private HitDoc last; // tail of LRU cache private int numDocs = 0; // number cached private int maxDocs = 200; // max to cache + + private boolean normalizeScores = true; + private final float scoreNorm; Hits(Searcher s, Query q, Filter f) throws IOException { weight = q.weight(s); searcher = s; filter = f; getMoreDocs(50); // retrieve 100 initially + scoreNorm = initScoreNorm(); } Hits(Searcher s, Query q, Filter f, Sort o) throws IOException { @@ -59,6 +63,20 @@ filter = f; sort = o; getMoreDocs(50); // retrieve 100 initially + scoreNorm = initScoreNorm(); + } + + private float initScoreNorm() { + if(hitDocs.isEmpty()) { + return 1.0f; + } else { + final float firstScore = ((HitDoc)hitDocs.get(0)).score; + if(firstScore > 1.0f) { + return 1.0f / firstScore; + } else { + return 1.0f; + } + } } /** @@ -75,15 +93,9 @@ length = topDocs.totalHits; ScoreDoc[] scoreDocs = topDocs.scoreDocs; - float scoreNorm = 1.0f; - - if (length > 0 && topDocs.getMaxScore() > 1.0f) { - scoreNorm = 1.0f / topDocs.getMaxScore(); - } - int end = scoreDocs.length < length ? scoreDocs.length : length; for (int i = hitDocs.size(); i < end; i++) { - hitDocs.addElement(new HitDoc(scoreDocs[i].score * scoreNorm, + hitDocs.addElement(new HitDoc(scoreDocs[i].score, scoreDocs[i].doc)); } } @@ -120,13 +132,18 @@ /** Returns the score for the nth document in this set. */ public final float score(int n) throws IOException { - return hitDoc(n).score; - } - - /** Returns the id for the nth document in this set. - * Note that ids may change when the index changes, so you cannot - * rely on the id to be stable. - */ + if (normalizeScores) { + return hitDoc(n).score * scoreNorm; + } else { + return hitDoc(n).score; + } + } + + /** + * Returns the id for the nth document in this set. Note that + * ids may change when the index changes, so you cannot rely on the id to be + * stable. + */ public final int id(int n) throws IOException { return hitDoc(n).id; } @@ -190,6 +207,29 @@ numDocs--; } + + /** + * Checks whether scores should be normalized to a maximum of 1.0. + * Turned on by default. + * + * @return true iff scores should be normalized to a maximum of 1.0. + * @see #setNormalizeScores(boolean) + */ + public boolean isNormalizeScores() { + return normalizeScores; + } + + /** + * Turns score normalization on/off. + * If turned on (true), the maximum score is 1.0. + * if turned off (false), raw scores from {@link Searcher}s are unaltered. + * + * @param normalizeScores true iff scores should be normalized to a maximum of 1.0. + */ + public void setNormalizeScores(boolean normalizeScores) { + this.normalizeScores = normalizeScores; + } + } final class HitDoc {