lucene-java-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From mikemcc...@apache.org
Subject svn commit: r738219 [1/3] - in /lucene/java/trunk: ./ contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/ contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/ contrib/miscellaneous/src/test/org/apache/lucene/index/ cont...
Date Tue, 27 Jan 2009 20:15:23 GMT
Author: mikemccand
Date: Tue Jan 27 20:15:21 2009
New Revision: 738219

URL: http://svn.apache.org/viewvc?rev=738219&view=rev
Log:
LUCENE-1483: switch to newly added MultiReaderHitCollector for all core collectors, that is aware of segment transitions during searching, to improve performance of searching and warming

Added:
    lucene/java/trunk/src/java/org/apache/lucene/search/FieldComparator.java   (with props)
    lucene/java/trunk/src/java/org/apache/lucene/search/FieldComparatorSource.java   (with props)
    lucene/java/trunk/src/java/org/apache/lucene/search/FieldValueHitQueue.java   (with props)
    lucene/java/trunk/src/java/org/apache/lucene/search/MultiReaderHitCollector.java   (with props)
    lucene/java/trunk/src/java/org/apache/lucene/search/TopFieldCollector.java   (with props)
    lucene/java/trunk/src/java/org/apache/lucene/search/TopScoreDocCollector.java   (with props)
    lucene/java/trunk/src/java/org/apache/lucene/util/SorterTemplate.java   (with props)
    lucene/java/trunk/src/test/org/apache/lucene/search/TestStressSort.java   (with props)
Modified:
    lucene/java/trunk/CHANGES.txt
    lucene/java/trunk/build.xml
    lucene/java/trunk/common-build.xml
    lucene/java/trunk/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SortableSimpleDocMaker.java
    lucene/java/trunk/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchWithSortTask.java
    lucene/java/trunk/contrib/miscellaneous/src/test/org/apache/lucene/index/TestFieldNormModifier.java
    lucene/java/trunk/contrib/miscellaneous/src/test/org/apache/lucene/misc/TestLengthNormModifier.java
    lucene/java/trunk/src/demo/org/apache/lucene/demo/SearchFiles.java
    lucene/java/trunk/src/java/org/apache/lucene/index/FilterIndexReader.java
    lucene/java/trunk/src/java/org/apache/lucene/index/IndexReader.java
    lucene/java/trunk/src/java/org/apache/lucene/index/MultiReader.java
    lucene/java/trunk/src/java/org/apache/lucene/index/MultiSegmentReader.java
    lucene/java/trunk/src/java/org/apache/lucene/search/BooleanScorer.java
    lucene/java/trunk/src/java/org/apache/lucene/search/FieldSortedHitQueue.java
    lucene/java/trunk/src/java/org/apache/lucene/search/Hit.java
    lucene/java/trunk/src/java/org/apache/lucene/search/HitCollector.java
    lucene/java/trunk/src/java/org/apache/lucene/search/HitIterator.java
    lucene/java/trunk/src/java/org/apache/lucene/search/Hits.java
    lucene/java/trunk/src/java/org/apache/lucene/search/IndexSearcher.java
    lucene/java/trunk/src/java/org/apache/lucene/search/MultiSearcher.java
    lucene/java/trunk/src/java/org/apache/lucene/search/ParallelMultiSearcher.java
    lucene/java/trunk/src/java/org/apache/lucene/search/QueryWrapperFilter.java
    lucene/java/trunk/src/java/org/apache/lucene/search/ScoreDocComparator.java
    lucene/java/trunk/src/java/org/apache/lucene/search/SortField.java
    lucene/java/trunk/src/java/org/apache/lucene/search/TimeLimitedCollector.java
    lucene/java/trunk/src/java/org/apache/lucene/search/TopDocCollector.java
    lucene/java/trunk/src/java/org/apache/lucene/search/TopFieldDocCollector.java
    lucene/java/trunk/src/test/org/apache/lucene/index/TestIndexReaderReopen.java
    lucene/java/trunk/src/test/org/apache/lucene/index/TestOmitTf.java
    lucene/java/trunk/src/test/org/apache/lucene/search/CheckHits.java
    lucene/java/trunk/src/test/org/apache/lucene/search/QueryUtils.java
    lucene/java/trunk/src/test/org/apache/lucene/search/TestDocBoost.java
    lucene/java/trunk/src/test/org/apache/lucene/search/TestMultiTermConstantScore.java
    lucene/java/trunk/src/test/org/apache/lucene/search/TestScorerPerf.java
    lucene/java/trunk/src/test/org/apache/lucene/search/TestSetNorm.java
    lucene/java/trunk/src/test/org/apache/lucene/search/TestSimilarity.java
    lucene/java/trunk/src/test/org/apache/lucene/search/TestSort.java
    lucene/java/trunk/src/test/org/apache/lucene/search/TestTermScorer.java
    lucene/java/trunk/src/test/org/apache/lucene/search/TestTimeLimitedCollector.java

Modified: lucene/java/trunk/CHANGES.txt
URL: http://svn.apache.org/viewvc/lucene/java/trunk/CHANGES.txt?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/CHANGES.txt (original)
+++ lucene/java/trunk/CHANGES.txt Tue Jan 27 20:15:21 2009
@@ -46,6 +46,11 @@
    newly added NoSuchDirectoryException if the directory does not
    exist.  (Marcel Reutegger, Mike McCandless)
 
+7. LUCENE-1483: Added new MultiReaderHitCollector which enables faster
+   hit collection by notifying the collector for each sub-reader
+   that's visited.  All core collectors now use this API.  (Mark
+   Miller, Mike McCandless)
+
 Bug fixes
 
 1. LUCENE-1415: MultiPhraseQuery has incorrect hashCode() and equals()
@@ -152,6 +157,13 @@
     environment.  (Todd Feak, Yonik Seeley, Jason Rutherglen via Mike
     McCandless)
 
+ 6. LUCENE-1483: When searching over multiple segments we now visit
+    each sub-reader one at a time.  This speeds up warming, since
+    FieldCache entries (if required) can be shared across reopens for
+    those segments that did not change, and also speeds up searches
+    that sort by relevance or by field values.  (Mark Miller, Mike
+    McCandless)
+
 Documentation
 
 Build

Modified: lucene/java/trunk/build.xml
URL: http://svn.apache.org/viewvc/lucene/java/trunk/build.xml?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/build.xml (original)
+++ lucene/java/trunk/build.xml Tue Jan 27 20:15:21 2009
@@ -111,7 +111,7 @@
 	  <mkdir dir="${tags.dir}/${tag}"/>
       <exec dir="${tags.dir}/${tag}" executable="${svn.exe}"
             failifexecutionfails="false">
-        <arg line="checkout http://svn.apache.org/repos/asf/lucene/java/${tag}/src/test/"/>
+        <arg line="checkout https://svn.apache.org/repos/asf/lucene/java/${tag}/src/test/"/>
       </exec>
 	</sequential>
   </target>

Modified: lucene/java/trunk/common-build.xml
URL: http://svn.apache.org/viewvc/lucene/java/trunk/common-build.xml?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/common-build.xml (original)
+++ lucene/java/trunk/common-build.xml Tue Jan 27 20:15:21 2009
@@ -41,7 +41,7 @@
   <property name="name" value="${ant.project.name}"/>
   <property name="Name" value="Lucene"/>
   <property name="version" value="2.9-dev"/>
-  <property name="compatibility.tag" value="tags/lucene_2_4_back_compat_tests_20090123"/>
+  <property name="compatibility.tag" value="tags/lucene_2_4_back_compat_tests_20090127"/>
   <property name="spec.version" value="${version}"/>	
   <property name="year" value="2000-${current.year}"/>
   <property name="final.name" value="lucene-${name}-${version}"/>

Modified: lucene/java/trunk/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SortableSimpleDocMaker.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SortableSimpleDocMaker.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SortableSimpleDocMaker.java (original)
+++ lucene/java/trunk/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SortableSimpleDocMaker.java Tue Jan 27 20:15:21 2009
@@ -6,20 +6,44 @@
 import org.apache.lucene.benchmark.byTask.utils.Config;
 
 /**
- * Adds fields appropriate for sorting.
+ * Adds fields appropriate for sorting: country,
+ * random_string and sort_field (int).
  * 
  */
 public class SortableSimpleDocMaker extends SimpleDocMaker {
   private int sortRange;
+  
+  private static String[] COUNTRIES = new String[] {"European Union", "United States", "Japan", "Germany", "China (PRC)", "United Kingdom", "France", "Italy", "Spain", "Canada", "Brazil", "Russia", "India", "South Korea", "Australia", "Mexico", "Netherlands", "Turkey", "Sweden", "Belgium", "Indonesia", "Switzerland", "Poland", "Norway", "Republic of China", "Saudi Arabia", "Austria", "Greece", "Denmark", "Iran", "South Africa", "Argentina", "Ireland", "Thailand", "Finland", "Venezuela", "Portugal", "Hong Kong", "United Arab Emirates", "Malaysia", "Czech Republic", "Colombia", "Nigeria", "Romania", "Chile", "Israel", "Singapore", "Philippines", "Pakistan", "Ukraine", "Hungary", "Algeria", "New Zealand", "Egypt", "Kuwait", "Peru", "Kazakhstan", "Slovakia", "Morocco", "Bangladesh", "Vietnam", "Qatar", "Angola", "Libya", "Iraq", "Croatia", "Luxembourg", "Sudan", "Slovenia", "Cuba", "Belarus", "Ecuador", "Serbia", "Oman", "Bulgaria", "Lithuania", "Syria", "Dominican Republic", "T
 unisia", "Guatemala", "Azerbaijan", "Sri Lanka", "Kenya", "Latvia", "Turkmenistan", "Costa Rica", "Lebanon", "Uruguay", "Uzbekistan", "Yemen", "Cyprus", "Estonia", "Trinidad and Tobago", "Cameroon", "El Salvador", "Iceland", "Panama", "Bahrain", "Ivory Coast", "Ethiopia", "Tanzania", "Jordan", "Ghana", "Bosnia and Herzegovina", "Macau", "Burma", "Bolivia", "Brunei", "Botswana", "Honduras", "Gabon", "Uganda", "Jamaica", "Zambia", "Senegal", "Paraguay", "Albania", "Equatorial Guinea", "Georgia", "Democratic Republic of the Congo", "Nepal", "Afghanistan", "Cambodia", "Armenia", "Republic of the Congo", "Mozambique", "Republic of Macedonia", "Malta", "Namibia", "Madagascar", "Chad", "Burkina Faso", "Mauritius", "Mali", "The Bahamas", "Papua New Guinea", "Nicaragua", "Haiti", "Benin", "alestinian flag West Bank and Gaza", "Jersey", "Fiji", "Guinea", "Moldova", "Niger", "Laos", "Mongolia", "French Polynesia", "Kyrgyzstan", "Barbados", "Tajikistan", "Malawi", "Liechtenstein", "New 
 Caledonia", "Kosovo", "Rwanda", "Montenegro", "Swaziland", "Guam", "Mauritania", "Guernsey", "Isle of Man", "Togo", "Somalia", "Suriname", "Aruba", "North Korea", "Zimbabwe", "Central African Republic", "Faroe Islands", "Greenland", "Sierra Leone", "Lesotho", "Cape Verde", "Eritrea", "Bhutan", "Belize", "Antigua and Barbuda", "Gibraltar", "Maldives", "San Marino", "Guyana", "Burundi", "Saint Lucia", "Djibouti", "British Virgin Islands", "Liberia", "Seychelles", "The Gambia", "Northern Mariana Islands", "Grenada", "Saint Vincent and the Grenadines", "Saint Kitts and Nevis", "East Timor", "Vanuatu", "Comoros", "Samoa", "Solomon Islands", "Guinea-Bissau", "American Samoa", "Dominica", "Micronesia", "Tonga", "Cook Islands", "Palau", "Marshall Islands", "S�o Tom� and Pr�ncipe", "Anguilla", "Kiribati", "Tuvalu", "Niue"};
 
   protected DocData getNextDocData() throws NoMoreDataException {
+    Random r = new Random();
     DocData doc = super.getNextDocData();
     Properties props = new Properties();
-    props.put("sort_field", Integer.toString(getRandomNumber(0, sortRange)));
+
+    // random int
+    props.put("sort_field", Integer.toString(nextInt(r, sortRange)));
+
+    // random string
+    int len = nextInt(r, 2, 20);
+    char[] buffer = new char[len];
+    for(int i=0;i<len;i++)
+      buffer[i] = (char) nextInt(r, 0x80);
+    props.put("random_string", new String(buffer));
+
+    // random country
+    props.put("country", COUNTRIES[nextInt(r, COUNTRIES.length)]);
     doc.setProps(props);
     return doc;
   }
 
+  private int nextInt(Random r, int lim) {
+    return r.nextInt(lim);
+  }
+
+  private int nextInt(Random r, int start, int end) {
+    return start + r.nextInt(end-start);
+  }
+
   /*
    * (non-Javadoc)
    * 
@@ -29,10 +53,4 @@
     super.setConfig(config);
     sortRange = config.get("sort.rng", 20000);
   }
-
-  private int getRandomNumber(final int low, final int high) {
-    Random r = new Random();
-    int randInt = (Math.abs(r.nextInt()) % (high - low)) + low;
-    return randInt;
-  }
 }

Modified: lucene/java/trunk/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchWithSortTask.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchWithSortTask.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchWithSortTask.java (original)
+++ lucene/java/trunk/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/SearchWithSortTask.java Tue Jan 27 20:15:21 2009
@@ -45,18 +45,24 @@
     SortField[] sortFields = new SortField[fields.length];
     for (int i = 0; i < fields.length; i++) {
       String field = fields[i];
-      int index = field.lastIndexOf(":");
-      String fieldName;
-      String typeString;
-      if (index != -1) {
-        fieldName = field.substring(0, index);
-        typeString = field.substring(1+index, field.length());
+      SortField sortField0;
+      if (field.equals("doc")) {
+        sortField0 = SortField.FIELD_DOC;
       } else {
-        typeString = "auto";
-        fieldName = field;
+        int index = field.lastIndexOf(":");
+        String fieldName;
+        String typeString;
+        if (index != -1) {
+          fieldName = field.substring(0, index);
+          typeString = field.substring(1+index, field.length());
+        } else {
+          typeString = "auto";
+          fieldName = field;
+        }
+        int type = getType(typeString);
+        sortField0 = new SortField(fieldName, type);
       }
-      int type = getType(typeString);
-      sortFields[i] = new SortField(fieldName, type);
+      sortFields[i] = sortField0;
     }
     this.sort = new Sort(sortFields);
   }
@@ -69,6 +75,8 @@
       type = SortField.INT;
     } else if (typeString.equals("string")) {
       type = SortField.STRING;
+    } else if (typeString.equals("string_val")) {
+      type = SortField.STRING_VAL;
     } else {
       type = SortField.AUTO;
     }

Modified: lucene/java/trunk/contrib/miscellaneous/src/test/org/apache/lucene/index/TestFieldNormModifier.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/contrib/miscellaneous/src/test/org/apache/lucene/index/TestFieldNormModifier.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/contrib/miscellaneous/src/test/org/apache/lucene/index/TestFieldNormModifier.java (original)
+++ lucene/java/trunk/contrib/miscellaneous/src/test/org/apache/lucene/index/TestFieldNormModifier.java Tue Jan 27 20:15:21 2009
@@ -22,14 +22,11 @@
 
 import junit.framework.TestCase;
 
-import org.apache.lucene.index.Term;
-import org.apache.lucene.index.IndexWriter;
-import org.apache.lucene.index.IndexReader;
 import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.MultiReaderHitCollector;
 import org.apache.lucene.search.Similarity;
 import org.apache.lucene.search.DefaultSimilarity;
 import org.apache.lucene.search.TermQuery;
-import org.apache.lucene.search.HitCollector;
 import org.apache.lucene.store.RAMDirectory;
 import org.apache.lucene.store.Directory;
 import org.apache.lucene.analysis.SimpleAnalyzer;
@@ -126,9 +123,13 @@
     float lastScore = 0.0f;
     
     // default similarity should put docs with shorter length first
-    searcher.search(new TermQuery(new Term("field", "word")), new HitCollector() {
+    searcher.search(new TermQuery(new Term("field", "word")), new MultiReaderHitCollector() {
+      private int docBase = -1;
       public final void collect(int doc, float score) {
-        scores[doc] = score;
+        scores[doc + docBase] = score;
+      }
+      public void setNextReader(IndexReader reader, int docBase) {
+        this.docBase = docBase;
       }
     });
     searcher.close();
@@ -146,9 +147,13 @@
     
     // new norm (with default similarity) should put longer docs first
     searcher = new IndexSearcher(store);
-    searcher.search(new TermQuery(new Term("field", "word")),  new HitCollector() {
+    searcher.search(new TermQuery(new Term("field", "word")),  new MultiReaderHitCollector() {
+      private int docBase = -1;
       public final void collect(int doc, float score) {
-        scores[doc] = score;
+        scores[doc + docBase] = score;
+      }
+      public void setNextReader(IndexReader reader, int docBase) {
+        this.docBase = docBase;
       }
     });
     searcher.close();
@@ -183,9 +188,14 @@
     float lastScore = 0.0f;
     
     // default similarity should return the same score for all documents for this query
-    searcher.search(new TermQuery(new Term("untokfield", "20061212")), new HitCollector() {
+    searcher.search(new TermQuery(new Term("untokfield", "20061212")), new MultiReaderHitCollector() {
+      private int docBase = -1;
+      private int lastMax; 
       public final void collect(int doc, float score) {
-        scores[doc] = score;
+        scores[doc + docBase] = score;
+      }
+      public void setNextReader(IndexReader reader, int docBase) {
+        this.docBase = docBase;
       }
     });
     searcher.close();

Modified: lucene/java/trunk/contrib/miscellaneous/src/test/org/apache/lucene/misc/TestLengthNormModifier.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/contrib/miscellaneous/src/test/org/apache/lucene/misc/TestLengthNormModifier.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/contrib/miscellaneous/src/test/org/apache/lucene/misc/TestLengthNormModifier.java (original)
+++ lucene/java/trunk/contrib/miscellaneous/src/test/org/apache/lucene/misc/TestLengthNormModifier.java Tue Jan 27 20:15:21 2009
@@ -23,10 +23,10 @@
 import org.apache.lucene.index.IndexWriter;
 import org.apache.lucene.index.IndexReader;
 import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.MultiReaderHitCollector;
 import org.apache.lucene.search.Similarity;
 import org.apache.lucene.search.DefaultSimilarity;
 import org.apache.lucene.search.TermQuery;
-import org.apache.lucene.search.HitCollector;
 import org.apache.lucene.store.RAMDirectory;
 import org.apache.lucene.store.Directory;
 import org.apache.lucene.analysis.SimpleAnalyzer;
@@ -60,8 +60,6 @@
 	IndexWriter writer = new
 	    IndexWriter(store, new SimpleAnalyzer(), true);
 	
-	IndexSearcher searcher;
-	
 	for (int i = 0; i < NUM_DOCS; i++) {
 	    Document d = new Document();
 	    d.add(new Field("field", "word",
@@ -130,15 +128,17 @@
 	float lastScore = 0.0f;
 	
 	// default similarity should put docs with shorter length first
-	searcher = new IndexSearcher(store);
-	searcher.search
-	    (new TermQuery(new Term("field", "word")),
-	     new HitCollector() {
-		 public final void collect(int doc, float score) {
-		     scores[doc] = score;
-		 }
-	     });
-	searcher.close();
+  searcher = new IndexSearcher(store);
+  searcher.search(new TermQuery(new Term("field", "word")), new MultiReaderHitCollector() {
+    private int docBase = -1;
+    public final void collect(int doc, float score) {
+      scores[doc + docBase] = score;
+    }
+    public void setNextReader(IndexReader reader, int docBase) {
+      this.docBase = docBase;
+    }
+  });
+  searcher.close();
 	
 	lastScore = Float.MAX_VALUE;
 	for (int i = 0; i < NUM_DOCS; i++) {
@@ -159,14 +159,16 @@
 
 	// new norm (with default similarity) should put longer docs first
 	searcher = new IndexSearcher(store);
-	searcher.search
-	    (new TermQuery(new Term("field", "word")),
-	     new HitCollector() {
-		 public final void collect(int doc, float score) {
-		     scores[doc] = score;
-		 }
-	     });
-	searcher.close();
+	searcher.search(new TermQuery(new Term("field", "word")), new MultiReaderHitCollector() {
+      private int docBase = -1;
+      public final void collect(int doc, float score) {
+        scores[doc + docBase] = score;
+      }
+      public void setNextReader(IndexReader reader, int docBase) {
+        this.docBase = docBase;
+      }
+    });
+    searcher.close();
 	
 	lastScore = 0.0f;
 	for (int i = 0; i < NUM_DOCS; i++) {

Modified: lucene/java/trunk/src/demo/org/apache/lucene/demo/SearchFiles.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/demo/org/apache/lucene/demo/SearchFiles.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/src/demo/org/apache/lucene/demo/SearchFiles.java (original)
+++ lucene/java/trunk/src/demo/org/apache/lucene/demo/SearchFiles.java Tue Jan 27 20:15:21 2009
@@ -34,7 +34,7 @@
 import org.apache.lucene.search.Query;
 import org.apache.lucene.search.ScoreDoc;
 import org.apache.lucene.search.Searcher;
-import org.apache.lucene.search.TopDocCollector;
+import org.apache.lucene.search.TopScoreDocCollector;
 
 /** Simple command-line based search demo. */
 public class SearchFiles {
@@ -193,7 +193,7 @@
                                      int hitsPerPage, boolean raw, boolean interactive) throws IOException {
  
     // Collect enough docs to show 5 pages
-    TopDocCollector collector = new TopDocCollector(5 * hitsPerPage);
+    TopScoreDocCollector collector = new TopScoreDocCollector(5 * hitsPerPage);
     searcher.search(query, collector);
     ScoreDoc[] hits = collector.topDocs().scoreDocs;
     
@@ -212,7 +212,7 @@
           break;
         }
 
-        collector = new TopDocCollector(numTotalHits);
+        collector = new TopScoreDocCollector(numTotalHits);
         searcher.search(query, collector);
         hits = collector.topDocs().scoreDocs;
       }

Modified: lucene/java/trunk/src/java/org/apache/lucene/index/FilterIndexReader.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/java/org/apache/lucene/index/FilterIndexReader.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/src/java/org/apache/lucene/index/FilterIndexReader.java (original)
+++ lucene/java/trunk/src/java/org/apache/lucene/index/FilterIndexReader.java Tue Jan 27 20:15:21 2009
@@ -232,4 +232,8 @@
     ensureOpen();
     return in.isOptimized();
   }
+  
+  public IndexReader[] getSequentialSubReaders() {
+    return in.getSequentialSubReaders();
+  }
 }

Modified: lucene/java/trunk/src/java/org/apache/lucene/index/IndexReader.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/java/org/apache/lucene/index/IndexReader.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/src/java/org/apache/lucene/index/IndexReader.java (original)
+++ lucene/java/trunk/src/java/org/apache/lucene/index/IndexReader.java Tue Jan 27 20:15:21 2009
@@ -1136,4 +1136,15 @@
   public static Collection listCommits(Directory dir) throws IOException {
     return DirectoryIndexReader.listCommits(dir);
   }
+
+  /** Returns the sequential sub readers that this reader is
+   *  logically composed of.  IndexSearcher uses this API to
+   *  drive searching by one sub reader at a time.  If this
+   *  reader is not composed of sequential child readers, it
+   *  should return null.  If this method returns an empty
+   *  array, that means this reader is a null reader (for
+   *  example a MultiReader that has no sub readers).*/
+  public IndexReader[] getSequentialSubReaders() {
+    return null;
+  }
 }

Modified: lucene/java/trunk/src/java/org/apache/lucene/index/MultiReader.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/java/org/apache/lucene/index/MultiReader.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/src/java/org/apache/lucene/index/MultiReader.java (original)
+++ lucene/java/trunk/src/java/org/apache/lucene/index/MultiReader.java Tue Jan 27 20:15:21 2009
@@ -364,8 +364,7 @@
     throw new UnsupportedOperationException("MultiReader does not support this method.");
   }
   
-  // for testing
-  IndexReader[] getSubReaders() {
+  public IndexReader[] getSequentialSubReaders() {
     return subReaders;
   }
 }

Modified: lucene/java/trunk/src/java/org/apache/lucene/index/MultiSegmentReader.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/java/org/apache/lucene/index/MultiSegmentReader.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/src/java/org/apache/lucene/index/MultiSegmentReader.java (original)
+++ lucene/java/trunk/src/java/org/apache/lucene/index/MultiSegmentReader.java Tue Jan 27 20:15:21 2009
@@ -431,8 +431,7 @@
     return fieldSet;
   } 
   
-  // for testing
-  SegmentReader[] getSubReaders() {
+  public IndexReader[] getSequentialSubReaders() {
     return subReaders;
   }
 

Modified: lucene/java/trunk/src/java/org/apache/lucene/search/BooleanScorer.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/java/org/apache/lucene/search/BooleanScorer.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/src/java/org/apache/lucene/search/BooleanScorer.java (original)
+++ lucene/java/trunk/src/java/org/apache/lucene/search/BooleanScorer.java Tue Jan 27 20:15:21 2009
@@ -19,6 +19,7 @@
 
 import java.io.IOException;
 
+import org.apache.lucene.index.IndexReader;
 /* Description from Doug Cutting (excerpted from
  * LUCENE-1483):
  *
@@ -79,11 +80,11 @@
     public boolean done;
     public boolean required = false;
     public boolean prohibited = false;
-    public HitCollector collector;
+    public MultiReaderHitCollector collector;
     public SubScorer next;
 
     public SubScorer(Scorer scorer, boolean required, boolean prohibited,
-                     HitCollector collector, SubScorer next)
+        MultiReaderHitCollector collector, SubScorer next)
       throws IOException {
       this.scorer = scorer;
       this.done = !scorer.next();
@@ -248,12 +249,12 @@
 
     public final int size() { return SIZE; }
 
-    public HitCollector newCollector(int mask) {
+    public MultiReaderHitCollector newCollector(int mask) {
       return new Collector(mask, this);
     }
   }
 
-  static final class Collector extends HitCollector {
+  static final class Collector extends MultiReaderHitCollector {
     private BucketTable bucketTable;
     private int mask;
     public Collector(int mask, BucketTable bucketTable) {
@@ -281,6 +282,9 @@
         bucket.coord++;                           // increment coord
       }
     }
+    public void setNextReader(IndexReader reader, int docBase) {
+      // not needed by this implementation
+    }
   }
 
   public boolean skipTo(int target) {

Added: lucene/java/trunk/src/java/org/apache/lucene/search/FieldComparator.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/java/org/apache/lucene/search/FieldComparator.java?rev=738219&view=auto
==============================================================================
--- lucene/java/trunk/src/java/org/apache/lucene/search/FieldComparator.java (added)
+++ lucene/java/trunk/src/java/org/apache/lucene/search/FieldComparator.java Tue Jan 27 20:15:21 2009
@@ -0,0 +1,869 @@
+package org.apache.lucene.search;
+
+/**
+ * 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.
+ */
+
+import java.io.IOException;
+import java.text.Collator;
+import java.util.Locale;
+
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.search.ExtendedFieldCache.DoubleParser;
+import org.apache.lucene.search.ExtendedFieldCache.LongParser;
+import org.apache.lucene.search.FieldCache.ByteParser;
+import org.apache.lucene.search.FieldCache.FloatParser;
+import org.apache.lucene.search.FieldCache.IntParser;
+import org.apache.lucene.search.FieldCache.ShortParser;
+import org.apache.lucene.search.FieldCache.StringIndex;
+
+/**
+ * A FieldComparator compares hits across multiple IndexReaders.
+ * 
+ * A comparator can compare a hit at hit 'slot a' with hit 'slot b',
+ * compare a hit on 'doc i' with hit 'slot a', or copy a hit at 'doc i'
+ * to 'slot a'. Each slot refers to a hit while each doc refers to the
+ * current IndexReader.
+ *
+ * <b>NOTE:</b> This API is experimental and might change in
+ * incompatible ways in the next release.
+ */
+public abstract class FieldComparator {
+
+  /** Parses field's values as byte (using {@link
+   *  FieldCache#getBytes} and sorts by ascending value */
+  public static final class ByteComparator extends FieldComparator {
+    private final byte[] values;
+    private byte[] currentReaderValues;
+    private final String field;
+    private ByteParser parser;
+    private byte bottom;
+
+    ByteComparator(int numHits, String field, FieldCache.Parser parser) {
+      values = new byte[numHits];
+      this.field = field;
+      this.parser = (ByteParser) parser;
+    }
+
+    public int compare(int slot1, int slot2) {
+      return values[slot1] - values[slot2];
+    }
+
+    public int compareBottom(int doc, float score) {
+      return bottom - currentReaderValues[doc];
+    }
+
+    public void copy(int slot, int doc, float score) {
+      values[slot] = currentReaderValues[doc];
+    }
+
+    public void setNextReader(IndexReader reader, int docBase,  int numSlotsFull) throws IOException {
+      currentReaderValues = parser != null ? ExtendedFieldCache.EXT_DEFAULT
+        .getBytes(reader, field, parser) : ExtendedFieldCache.EXT_DEFAULT
+        .getBytes(reader, field);
+    }
+    
+    public void setBottom(final int bottom) {
+      this.bottom = values[bottom];
+    }
+
+    public int sortType() {
+      return SortField.BYTE;
+    }
+
+    public Comparable value(int slot) {
+      return new Byte(values[slot]);
+    }
+  };
+
+  /** Sorts by ascending docID */
+  public static final class DocComparator extends FieldComparator {
+    private final int[] docIDs;
+    private int docBase;
+    private int bottom;
+
+    DocComparator(int numHits) {
+      docIDs = new int[numHits];
+    }
+
+    public int compare(int slot1, int slot2) {
+      // No overflow risk because docIDs are non-negative
+      return docIDs[slot1] - docIDs[slot2];
+    }
+
+    public int compareBottom(int doc, float score) {
+      // No overflow risk because docIDs are non-negative
+      return bottom - (docBase + doc);
+    }
+
+    public void copy(int slot, int doc, float score) {
+      docIDs[slot] = docBase + doc;
+    }
+
+    public void setNextReader(IndexReader reader, int docBase, int numSlotsFull) {
+      // TODO: can we "map" our docIDs to the current
+      // reader? saves having to then subtract on every
+      // compare call
+      this.docBase = docBase;
+    }
+    
+    public void setBottom(final int bottom) {
+      this.bottom = docIDs[bottom];
+    }
+
+    public int sortType() {
+      return SortField.DOC;
+    }
+
+    public Comparable value(int slot) {
+      return new Integer(docIDs[slot]);
+    }
+  };
+
+  /** Parses field's values as double (using {@link
+   *  ExtendedFieldCache#getDoubles} and sorts by ascending value */
+  public static final class DoubleComparator extends FieldComparator {
+    private final double[] values;
+    private double[] currentReaderValues;
+    private final String field;
+    private DoubleParser parser;
+    private double bottom;
+
+    DoubleComparator(int numHits, String field, FieldCache.Parser parser) {
+      values = new double[numHits];
+      this.field = field;
+      this.parser = (DoubleParser) parser;
+    }
+
+    public int compare(int slot1, int slot2) {
+      final double v1 = values[slot1];
+      final double v2 = values[slot2];
+      if (v1 > v2) {
+        return 1;
+      } else if (v1 < v2) {
+        return -1;
+      } else {
+        return 0;
+      }
+    }
+
+    public int compareBottom(int doc, float score) {
+      final double v2 = currentReaderValues[doc];
+      if (bottom > v2) {
+        return 1;
+      } else if (bottom < v2) {
+        return -1;
+      } else {
+        return 0;
+      }
+    }
+
+    public void copy(int slot, int doc, float score) {
+      values[slot] = currentReaderValues[doc];
+    }
+
+    public void setNextReader(IndexReader reader, int docBase, int numSlotsFull) throws IOException {
+      currentReaderValues = parser != null ? ExtendedFieldCache.EXT_DEFAULT
+          .getDoubles(reader, field, parser) : ExtendedFieldCache.EXT_DEFAULT
+          .getDoubles(reader, field);
+    }
+    
+    public void setBottom(final int bottom) {
+      this.bottom = values[bottom];
+    }
+
+    public int sortType() {
+      return SortField.DOUBLE;
+    }
+
+    public Comparable value(int slot) {
+      return new Double(values[slot]);
+    }
+  };
+
+  /** Parses field's values as float (using {@link
+   *  FieldCache#getFloats} and sorts by ascending value */
+  public static final class FloatComparator extends FieldComparator {
+    private final float[] values;
+    private float[] currentReaderValues;
+    private final String field;
+    private FloatParser parser;
+    private float bottom;
+
+    FloatComparator(int numHits, String field, FieldCache.Parser parser) {
+      values = new float[numHits];
+      this.field = field;
+      this.parser = (FloatParser) parser;
+    }
+
+    public int compare(int slot1, int slot2) {
+      // TODO: are there sneaky non-branch ways to compute
+      // sign of float?
+      final float v1 = values[slot1];
+      final float v2 = values[slot2];
+      if (v1 > v2) {
+        return 1;
+      } else if (v1 < v2) {
+        return -1;
+      } else {
+        return 0;
+      }
+    }
+
+    public int compareBottom(int doc, float score) {
+      // TODO: are there sneaky non-branch ways to compute
+      // sign of float?
+      final float v2 = currentReaderValues[doc];
+      if (bottom > v2) {
+        return 1;
+      } else if (bottom < v2) {
+        return -1;
+      } else {
+        return 0;
+      }
+    }
+
+    public void copy(int slot, int doc, float score) {
+      values[slot] = currentReaderValues[doc];
+    }
+
+    public void setNextReader(IndexReader reader, int docBase,  int numSlotsFull) throws IOException {
+      currentReaderValues = parser != null ? FieldCache.DEFAULT.getFloats(
+          reader, field, parser) : FieldCache.DEFAULT.getFloats(reader, field);
+    }
+    
+    public void setBottom(final int bottom) {
+      this.bottom = values[bottom];
+    }
+
+    public int sortType() {
+      return SortField.FLOAT;
+    }
+
+    public Comparable value(int slot) {
+      return new Float(values[slot]);
+    }
+  };
+
+  /** Parses field's values as int (using {@link
+   *  FieldCache#getInts} and sorts by ascending value */
+  public static final class IntComparator extends FieldComparator {
+    private final int[] values;
+    private int[] currentReaderValues;
+    private final String field;
+    private IntParser parser;
+    private int bottom;                           // Value of bottom of queue
+
+    IntComparator(int numHits, String field, FieldCache.Parser parser) {
+      values = new int[numHits];
+      this.field = field;
+      this.parser = (IntParser) parser;
+    }
+
+    public int compare(int slot1, int slot2) {
+      // TODO: there are sneaky non-branch ways to compute
+      // -1/+1/0 sign
+      // Cannot return values[slot1] - values[slot2] because that
+      // may overflow
+      final int v1 = values[slot1];
+      final int v2 = values[slot2];
+      if (v1 > v2) {
+        return 1;
+      } else if (v1 < v2) {
+        return -1;
+      } else {
+        return 0;
+      }
+    }
+
+    public int compareBottom(int doc, float score) {
+      // TODO: there are sneaky non-branch ways to compute
+      // -1/+1/0 sign
+      // Cannot return bottom - values[slot2] because that
+      // may overflow
+      final int v2 = currentReaderValues[doc];
+      if (bottom > v2) {
+        return 1;
+      } else if (bottom < v2) {
+        return -1;
+      } else {
+        return 0;
+      }
+    }
+
+    public void copy(int slot, int doc, float score) {
+      values[slot] = currentReaderValues[doc];
+    }
+
+    public void setNextReader(IndexReader reader, int docBase,  int numSlotsFull) throws IOException {
+      currentReaderValues = parser != null ? FieldCache.DEFAULT.getInts(reader,
+          field, parser) : FieldCache.DEFAULT.getInts(reader, field);
+    }
+    
+    public void setBottom(final int bottom) {
+      this.bottom = values[bottom];
+    }
+
+    public int sortType() {
+      return SortField.INT;
+    }
+
+    public Comparable value(int slot) {
+      return new Integer(values[slot]);
+    }
+  };
+
+  /** Parses field's values as long (using {@link
+   *  ExtendedFieldCache#getLongs} and sorts by ascending value */
+  public static final class LongComparator extends FieldComparator {
+    private final long[] values;
+    private long[] currentReaderValues;
+    private final String field;
+    private LongParser parser;
+    private long bottom;
+
+    LongComparator(int numHits, String field, FieldCache.Parser parser) {
+      values = new long[numHits];
+      this.field = field;
+      this.parser = (LongParser) parser;
+    }
+
+    public int compare(int slot1, int slot2) {
+      // TODO: there are sneaky non-branch ways to compute
+      // -1/+1/0 sign
+      final long v1 = values[slot1];
+      final long v2 = values[slot2];
+      if (v1 > v2) {
+        return 1;
+      } else if (v1 < v2) {
+        return -1;
+      } else {
+        return 0;
+      }
+    }
+
+    public int compareBottom(int doc, float score) {
+      // TODO: there are sneaky non-branch ways to compute
+      // -1/+1/0 sign
+      final long v2 = currentReaderValues[doc];
+      if (bottom > v2) {
+        return 1;
+      } else if (bottom < v2) {
+        return -1;
+      } else {
+        return 0;
+      }
+    }
+
+    public void copy(int slot, int doc, float score) {
+      values[slot] = currentReaderValues[doc];
+    }
+
+    public void setNextReader(IndexReader reader, int docBase,  int numSlotsFull) throws IOException {
+      currentReaderValues = parser != null ? ExtendedFieldCache.EXT_DEFAULT
+          .getLongs(reader, field, parser) : ExtendedFieldCache.EXT_DEFAULT
+          .getLongs(reader, field);
+    }
+    
+    public void setBottom(final int bottom) {
+      this.bottom = values[bottom];
+    }
+
+    public int sortType() {
+      return SortField.LONG;
+    }
+
+    public Comparable value(int slot) {
+      return new Long(values[slot]);
+    }
+  };
+
+  /** Sorts by descending relevance.  NOTE: if you are
+   *  sorting only by descending relevance and then
+   *  secondarily by ascending docID, peformance is faster
+   *  using {@link TopScoreDocCollector} directly (which {@link
+   *  IndexSearcher#search} uses when no {@link Sort} is
+   *  specified). */
+  public static final class RelevanceComparator extends FieldComparator {
+    private final float[] scores;
+    private float bottom;
+
+    RelevanceComparator(int numHits) {
+      scores = new float[numHits];
+    }
+
+    public int compare(int slot1, int slot2) {
+      final float score1 = scores[slot1];
+      final float score2 = scores[slot2];
+      if (score1 > score2) {
+        return -1;
+      } else if (score1 < score2) {
+        return 1;
+      } else {
+        return 0;
+      }
+    }
+
+    public int compareBottom(int doc, float score) {
+      if (bottom > score) {
+        return -1;
+      } else if (bottom < score) {
+        return 1;
+      } else {
+        return 0;
+      }
+    }
+
+    public void copy(int slot, int doc, float score) {
+      scores[slot] = score;
+    }
+
+    public void setNextReader(IndexReader reader, int docBase,  int numSlotsFull) {
+    }
+    
+    public void setBottom(final int bottom) {
+      this.bottom = scores[bottom];
+    }
+
+    public int sortType() {
+      return SortField.SCORE;
+    }
+
+    public Comparable value(int slot) {
+      return new Float(scores[slot]);
+    }
+  };
+
+  /** Parses field's values as short (using {@link
+   *  FieldCache#getShorts} and sorts by ascending value */
+  public static final class ShortComparator extends FieldComparator {
+    private final short[] values;
+    private short[] currentReaderValues;
+    private final String field;
+    private ShortParser parser;
+    private short bottom;
+
+    ShortComparator(int numHits, String field, FieldCache.Parser parser) {
+      values = new short[numHits];
+      this.field = field;
+      this.parser = (ShortParser) parser;
+    }
+
+    public int compare(int slot1, int slot2) {
+      return values[slot1] - values[slot2];
+    }
+
+    public int compareBottom(int doc, float score) {
+      return bottom - currentReaderValues[doc];
+    }
+
+    public void copy(int slot, int doc, float score) {
+      values[slot] = currentReaderValues[doc];
+    }
+
+    public void setNextReader(IndexReader reader, int docBase,  int numSlotsFull) throws IOException {
+      currentReaderValues = parser != null ? ExtendedFieldCache.EXT_DEFAULT
+          .getShorts(reader, field, parser) : ExtendedFieldCache.EXT_DEFAULT
+          .getShorts(reader, field);
+    }
+    
+    public void setBottom(final int bottom) {
+      this.bottom = values[bottom];
+    }
+
+    public int sortType() {
+      return SortField.BYTE;
+    }
+
+    public Comparable value(int slot) {
+      return new Short(values[slot]);
+    }
+  };
+
+  /** Sorts by a field's value using the Collator for a
+   *  given Locale.*/
+  public static final class StringComparatorLocale extends FieldComparator {
+
+    private final String[] values;
+    private String[] currentReaderValues;
+    private final String field;
+    final Collator collator;
+    private String bottom;
+
+    StringComparatorLocale(int numHits, String field, Locale locale) {
+      values = new String[numHits];
+      this.field = field;
+      collator = Collator.getInstance(locale);
+    }
+
+    public int compare(int slot1, int slot2) {
+      final String val1 = values[slot1];
+      final String val2 = values[slot2];
+      if (val1 == null) {
+        if (val2 == null) {
+          return 0;
+        }
+        return -1;
+      } else if (val2 == null) {
+        return 1;
+      }
+      return collator.compare(val1, val2);
+    }
+
+    public int compareBottom(int doc, float score) {
+      final String val2 = currentReaderValues[doc];
+      if (bottom == null) {
+        if (val2 == null) {
+          return 0;
+        }
+        return -1;
+      } else if (val2 == null) {
+        return 1;
+      }
+      return collator.compare(bottom, val2);
+    }
+
+    public void copy(int slot, int doc, float score) {
+      values[slot] = currentReaderValues[doc];
+    }
+
+    public void setNextReader(IndexReader reader, int docBase,  int numSlotsFull) throws IOException {
+      currentReaderValues = ExtendedFieldCache.EXT_DEFAULT.getStrings(reader,
+          field);
+    }
+    
+    public void setBottom(final int bottom) {
+      this.bottom = values[bottom];
+    }
+
+    public int sortType() {
+      return SortField.STRING;
+    }
+
+    public Comparable value(int slot) {
+      return values[slot];
+    }
+  };
+
+  // NOTE: there were a number of other interesting String
+  // comparators explored, but this one seemed to perform
+  // best all around.  See LUCENE-1483 for details.
+  public static final class StringOrdValComparator extends FieldComparator {
+
+    private final int[] ords;
+    private final String[] values;
+    private final int[] readerGen;
+
+    private int currentReaderGen = -1;
+    private String[] lookup;
+    private int[] order;
+    private final String field;
+
+    private int bottomSlot = -1;
+    private int bottomOrd;
+    private String bottomValue;
+    private final boolean reversed;
+    private final int sortPos;
+
+    public StringOrdValComparator(int numHits, String field, int sortPos, boolean reversed) {
+      ords = new int[numHits];
+      values = new String[numHits];
+      readerGen = new int[numHits];
+      this.sortPos = sortPos;
+      this.reversed = reversed;
+      this.field = field;
+    }
+
+    public int compare(int slot1, int slot2) {
+      if (readerGen[slot1] == readerGen[slot2]) {
+        int cmp = ords[slot1] - ords[slot2];
+        if (cmp != 0) {
+          return cmp;
+        }
+      }
+
+      final String val1 = values[slot1];
+      final String val2 = values[slot2];
+      if (val1 == null) {
+        if (val2 == null) {
+          return 0;
+        }
+        return -1;
+      } else if (val2 == null) {
+        return 1;
+      }
+      return val1.compareTo(val2);
+    }
+
+    public int compareBottom(int doc, float score) {
+      assert bottomSlot != -1;
+      int order = this.order[doc];
+      final int cmp = bottomOrd - order;
+      if (cmp != 0) {
+        return cmp;
+      }
+
+      final String val2 = lookup[order];
+      if (bottomValue == null) {
+        if (val2 == null) {
+          return 0;
+        }
+        // bottom wins
+        return -1;
+      } else if (val2 == null) {
+        // doc wins
+        return 1;
+      }
+      return bottomValue.compareTo(val2);
+    }
+
+    private void convert(int slot) {
+      readerGen[slot] = currentReaderGen;
+      int index = 0;
+      String value = values[slot];
+      if (value == null) {
+        ords[slot] = 0;
+        return;
+      }
+
+      if (sortPos == 0 && bottomSlot != -1 && bottomSlot != slot) {
+        // Since we are the primary sort, the entries in the
+        // queue are bounded by bottomOrd:
+        assert bottomOrd < lookup.length;
+        if (reversed) {
+          index = binarySearch(lookup, value, bottomOrd, lookup.length-1);
+        } else {
+          index = binarySearch(lookup, value, 0, bottomOrd);
+        }
+      } else {
+        // Full binary search
+        index = binarySearch(lookup, value);
+      }
+
+      if (index < 0) {
+        index = -index - 2;
+      }
+      ords[slot] = index;
+    }
+
+    public void copy(int slot, int doc, float score) {
+      final int ord = order[doc];
+      ords[slot] = ord;
+      assert ord >= 0;
+      values[slot] = lookup[ord];
+      readerGen[slot] = currentReaderGen;
+    }
+
+    public void setNextReader(IndexReader reader, int docBase,  int numSlotsFull) throws IOException {
+      StringIndex currentReaderValues = ExtendedFieldCache.EXT_DEFAULT.getStringIndex(reader, field);
+      currentReaderGen++;
+      order = currentReaderValues.order;
+      lookup = currentReaderValues.lookup;
+      assert lookup.length > 0;
+      if (bottomSlot != -1) {
+        convert(bottomSlot);
+        bottomOrd = ords[bottomSlot];
+      }
+    }
+    
+    public void setBottom(final int bottom) {
+      bottomSlot = bottom;
+      if (readerGen[bottom] != currentReaderGen) {
+        convert(bottomSlot);
+      }
+      bottomOrd = ords[bottom];
+      assert bottomOrd >= 0;
+      assert bottomOrd < lookup.length;
+      bottomValue = values[bottom];
+    }
+
+    public int sortType() {
+      return SortField.STRING;
+    }
+
+    public Comparable value(int slot) {
+      return values[slot];
+    }
+
+    public String[] getValues() {
+      return values;
+    }
+
+    public int getBottomSlot() {
+      return bottomSlot;
+    }
+
+    public String getField() {
+      return field;
+    }
+  };
+
+  /** Sorts by field's natural String sort order.  All
+   *  comparisons are done using String.compareTo, which is
+   *  slow for medium to large result sets but possibly
+   *  very fast for very small results sets. */
+  public static final class StringValComparator extends FieldComparator {
+
+    private String[] values;
+    private String[] currentReaderValues;
+    private final String field;
+    private String bottom;
+
+    StringValComparator(int numHits, String field) {
+      values = new String[numHits];
+      this.field = field;
+    }
+
+    public int compare(int slot1, int slot2) {
+      final String val1 = values[slot1];
+      final String val2 = values[slot2];
+      if (val1 == null) {
+        if (val2 == null) {
+          return 0;
+        }
+        return -1;
+      } else if (val2 == null) {
+        return 1;
+      }
+
+      return val1.compareTo(val2);
+    }
+
+    public int compareBottom(int doc, float score) {
+      final String val2 = currentReaderValues[doc];
+      if (bottom == null) {
+        if (val2 == null) {
+          return 0;
+        }
+        return -1;
+      } else if (val2 == null) {
+        return 1;
+      }
+      return bottom.compareTo(val2);
+    }
+
+    public void copy(int slot, int doc, float score) {
+      values[slot] = currentReaderValues[doc];
+    }
+
+    public void setNextReader(IndexReader reader, int docBase, int numSlotsFull) throws IOException {
+      currentReaderValues = ExtendedFieldCache.EXT_DEFAULT.getStrings(reader,
+          field);
+    }
+    
+    public void setBottom(final int bottom) {
+      this.bottom = values[bottom];
+    }
+
+    public int sortType() {
+      return SortField.STRING_VAL;
+    }
+
+    public Comparable value(int slot) {
+      return values[slot];
+    }
+  };
+
+  final protected static int binarySearch(String[] a, String key) {
+    return binarySearch(a, key, 0, a.length-1);
+  };
+
+  final protected static int binarySearch(String[] a, String key, int low, int high) {
+
+    while (low <= high) {
+      int mid = (low + high) >>> 1;
+      String midVal = a[mid];
+      int cmp;
+      if (midVal != null) {
+        cmp = midVal.compareTo(key);
+      } else {
+        cmp = -1;
+      }
+
+      if (cmp < 0)
+        low = mid + 1;
+      else if (cmp > 0)
+        high = mid - 1;
+      else
+        return mid;
+    }
+    return -(low + 1);
+  };
+
+  /**
+   * Compare hit at slot1 with hit at slot2.  Return 
+   * 
+   * @param slot1 first slot to compare
+   * @param slot2 second slot to compare
+   * @return any N < 0 if slot2's value is sorted after
+   * slot1, any N > 0 if the slot2's value is sorted before
+   * slot1 and 0 if they are equal
+   */
+  public abstract int compare(int slot1, int slot2);
+
+  /**
+   * Set the bottom queue slot, ie the "weakest" (sorted
+   * last) entry in the queue.
+   * 
+   * @param slot the currently weakest (sorted lost) slot in the queue
+   */
+  public abstract void setBottom(final int slot);
+
+  /**
+   * Compare the bottom of the queue with doc.  This will
+   * only invoked after setBottom has been called.  
+   * 
+   * @param doc that was hit
+   * @param score of the hit
+   * @return any N < 0 if the doc's value is sorted after
+   * the bottom entry (not competitive), any N > 0 if the
+   * doc's value is sorted before the bottom entry and 0 if
+   * they are equal.
+   */
+  public abstract int compareBottom(int doc, float score);
+
+  /**
+   * Copy hit (doc,score) to hit slot.
+   * 
+   * @param slot which slot to copy the hit to
+   * @param doc docID relative to current reader
+   * @param score hit score
+   */
+  public abstract void copy(int slot, int doc, float score);
+
+  /**
+   * Set a new Reader. All doc correspond to the current Reader.
+   * 
+   * @param reader current reader
+   * @param docBase docBase of this reader 
+   * @throws IOException
+   * @throws IOException
+   */
+  public abstract void setNextReader(IndexReader reader, int docBase, int numSlotsFull) throws IOException;
+
+  /**
+   * @return SortField.TYPE
+   */
+  public abstract int sortType();
+
+  /**
+   * Return the actual value at slot.
+   * 
+   * @param slot the value
+   * @return value in this slot upgraded to Comparable
+   */
+  public abstract Comparable value(int slot);
+}

Propchange: lucene/java/trunk/src/java/org/apache/lucene/search/FieldComparator.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: lucene/java/trunk/src/java/org/apache/lucene/search/FieldComparatorSource.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/java/org/apache/lucene/search/FieldComparatorSource.java?rev=738219&view=auto
==============================================================================
--- lucene/java/trunk/src/java/org/apache/lucene/search/FieldComparatorSource.java (added)
+++ lucene/java/trunk/src/java/org/apache/lucene/search/FieldComparatorSource.java Tue Jan 27 20:15:21 2009
@@ -0,0 +1,43 @@
+package org.apache.lucene.search;
+
+/**
+ * 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.
+ */
+
+import java.io.IOException;
+import org.apache.lucene.index.IndexReader;
+
+/**
+ * Provides a {@link FieldComparator} for custom field sorting.
+ *
+ * <b>NOTE:</b> This API is experimental and might change in
+ * incompatible ways in the next release.
+ *
+ */
+public abstract class FieldComparatorSource {
+
+  /**
+   * Creates a comparator for the field in the given index.
+   * 
+   * @param fieldname
+   *          Name of the field to create comparator for.
+   * @return FieldComparator.
+   * @throws IOException
+   *           If an error occurs reading the index.
+   */
+  abstract FieldComparator newComparator(String fieldname, IndexReader[] subReaders, int numHits, int sortPos, boolean reversed)
+      throws IOException;
+}

Propchange: lucene/java/trunk/src/java/org/apache/lucene/search/FieldComparatorSource.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: lucene/java/trunk/src/java/org/apache/lucene/search/FieldSortedHitQueue.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/java/org/apache/lucene/search/FieldSortedHitQueue.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/src/java/org/apache/lucene/search/FieldSortedHitQueue.java (original)
+++ lucene/java/trunk/src/java/org/apache/lucene/search/FieldSortedHitQueue.java Tue Jan 27 20:15:21 2009
@@ -34,6 +34,7 @@
  * @version $Id$
  * @see Searcher#search(Query,Filter,int,Sort)
  * @see FieldCache
+ * @deprecated see {@link FieldValueHitQueue}
  */
 public class FieldSortedHitQueue
 extends PriorityQueue {
@@ -52,18 +53,10 @@
     this.fields = new SortField[n];
     for (int i=0; i<n; ++i) {
       String fieldname = fields[i].getField();
+      // AUTO is resolved before we are called
+      assert fields[i].getType() != SortField.AUTO;
       comparators[i] = getCachedComparator (reader, fieldname, fields[i].getType(), fields[i].getParser(), fields[i].getLocale(), fields[i].getFactory());
-      // new SortField instances must only be created when auto-detection is in use
-      if (fields[i].getType() == SortField.AUTO) {
-        if (comparators[i].sortType() == SortField.STRING) {
-          this.fields[i] = new SortField (fieldname, fields[i].getLocale(), fields[i].getReverse());
-        } else {
-          this.fields[i] = new SortField (fieldname, comparators[i].sortType(), fields[i].getReverse());
-        }
-      } else {
-        assert comparators[i].sortType() == fields[i].getType();
-        this.fields[i] = fields[i];
-      }
+      this.fields[i] = fields[i];
     }
     initialize (size);
   }
@@ -194,9 +187,6 @@
       }
       ScoreDocComparator comparator;
       switch (type) {
-        case SortField.AUTO:
-          comparator = comparatorAuto (reader, fieldname);
-          break;
         case SortField.INT:
           comparator = comparatorInt (reader, fieldname, (FieldCache.IntParser)parser);
           break;
@@ -222,6 +212,8 @@
         case SortField.CUSTOM:
           comparator = factory.newComparator (reader, fieldname);
           break;
+        case SortField.AUTO:
+          throw new IllegalStateException("Auto should be resolved before now");
         default:
           throw new RuntimeException ("unknown field type: "+type);
       }
@@ -496,33 +488,4 @@
       }
     };
   }
-
-  /**
-   * Returns a comparator for sorting hits according to values in the given field.
-   * The terms in the field are looked at to determine whether they contain integers,
-   * floats or strings.  Once the type is determined, one of the other static methods
-   * in this class is called to get the comparator.
-   * @param reader  Index to use.
-   * @param fieldname  Fieldable containg values.
-   * @return  Comparator for sorting hits.
-   * @throws IOException If an error occurs reading the index.
-   */
-  static ScoreDocComparator comparatorAuto (final IndexReader reader, final String fieldname)
-  throws IOException {
-    final String field = fieldname.intern();
-    Object lookupArray = ExtendedFieldCache.EXT_DEFAULT.getAuto (reader, field);
-    if (lookupArray instanceof FieldCache.StringIndex) {
-      return comparatorString (reader, field);
-    } else if (lookupArray instanceof int[]) {
-      return comparatorInt (reader, field, null);
-    } else if (lookupArray instanceof long[]) {
-      return comparatorLong (reader, field, null);
-    } else if (lookupArray instanceof float[]) {
-      return comparatorFloat (reader, field, null);
-    } else if (lookupArray instanceof String[]) {
-      return comparatorString (reader, field);
-    } else {
-      throw new RuntimeException ("unknown data type in field '"+field+"'");
-    }
-  }
 }

Added: lucene/java/trunk/src/java/org/apache/lucene/search/FieldValueHitQueue.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/java/org/apache/lucene/search/FieldValueHitQueue.java?rev=738219&view=auto
==============================================================================
--- lucene/java/trunk/src/java/org/apache/lucene/search/FieldValueHitQueue.java (added)
+++ lucene/java/trunk/src/java/org/apache/lucene/search/FieldValueHitQueue.java Tue Jan 27 20:15:21 2009
@@ -0,0 +1,229 @@
+package org.apache.lucene.search;
+
+/**
+ * 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.
+ */
+
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.index.TermEnum;
+import org.apache.lucene.util.PriorityQueue;
+
+import java.io.IOException;;
+
+/**
+ * Expert: A hit queue for sorting by hits by terms in more than one field.
+ * Uses <code>FieldCache.DEFAULT</code> for maintaining
+ * internal term lookup tables.
+ *
+ * <b>NOTE:</b> This API is experimental and might change in
+ * incompatible ways in the next release.
+ *
+ * @since   lucene 2.9
+ * @version $Id:
+ * @see Searcher#search(Query,Filter,int,Sort)
+ * @see FieldCache
+ */
+public class FieldValueHitQueue extends PriorityQueue {
+
+  final static class Entry {
+    int slot;
+    int docID;
+    float score;
+
+    Entry(int slot, int docID, float score) {
+      this.slot = slot;
+      this.docID = docID;
+      this.score = score;
+    }
+    
+    public String toString() {
+      return "slot:" + slot + " docID:" + docID;
+    }
+  }
+
+  /**
+   * Creates a hit queue sorted by the given list of fields.
+   * @param fields SortField array we are sorting by in
+   *   priority order (highest priority first); cannot be <code>null</code> or empty
+   * @param size  The number of hits to retain.  Must be
+   *   greater than zero.
+   * @param subReaders Array of IndexReaders we will search,
+   *   in order that they will be searched
+   * @throws IOException
+   */
+  public FieldValueHitQueue(SortField[] fields, int size, IndexReader[] subReaders) throws IOException {
+    numComparators = fields.length;
+    comparators = new FieldComparator[numComparators];
+    reverseMul = new int[numComparators];
+
+    if (fields.length == 0) {
+      throw new IllegalArgumentException("Sort must contain at least one field");
+    }
+
+    this.fields = fields;
+    for (int i=0; i<numComparators; ++i) {
+      SortField field = fields[i];
+
+      // AUTO is resolved before we are called
+      assert field.getType() != SortField.AUTO;
+
+      reverseMul[i] = field.reverse ? -1 : 1;
+      comparators[i] = field.getComparator(subReaders, size, i, field.reverse);
+    }
+
+    if (numComparators == 1) {
+      comparator1 = comparators[0];
+      reverseMul1 = reverseMul[0];
+    } else {
+      comparator1 = null;
+      reverseMul1 = 0;
+    }
+
+    initialize(size);
+  }
+  
+  /** Stores a comparator corresponding to each field being sorted by */
+  private final FieldComparator[] comparators;
+  private final FieldComparator comparator1;
+  private final int numComparators;
+  private final int[] reverseMul;
+  private final int reverseMul1;
+
+  FieldComparator[] getComparators() {
+    return comparators;
+  }
+
+  int[] getReverseMul() {
+    return reverseMul;
+  }
+
+  /** Stores the sort criteria being used. */
+  private final SortField[] fields;
+
+  /**
+   * Returns whether <code>a</code> is less relevant than <code>b</code>.
+   * @param a ScoreDoc
+   * @param b ScoreDoc
+   * @return <code>true</code> if document <code>a</code> should be sorted after document <code>b</code>.
+   */
+  protected boolean lessThan (final Object a, final Object b) {
+    final Entry hitA = (Entry) a;
+    final Entry hitB = (Entry) b;
+
+    assert hitA != hitB;
+    assert hitA.slot != hitB.slot;
+
+    if (numComparators == 1) {
+      // Common case
+      final int c = reverseMul1 * comparator1.compare(hitA.slot, hitB.slot);
+      if (c != 0) {
+        return c > 0;
+      }
+    } else {
+      // run comparators
+      for (int i=0; i<numComparators; ++i) {
+        final int c = reverseMul[i] * comparators[i].compare(hitA.slot, hitB.slot);
+        if (c != 0) {
+          // Short circuit
+          return c > 0;
+        }
+      }
+    }
+
+    // avoid random sort order that could lead to duplicates (bug #31241):
+    return hitA.docID > hitB.docID;
+  }
+
+
+  /**
+   * Given a FieldDoc object, stores the values used
+   * to sort the given document.  These values are not the raw
+   * values out of the index, but the internal representation
+   * of them.  This is so the given search hit can be collated
+   * by a MultiSearcher with other search hits.
+   * @param  doc  The FieldDoc to store sort values into.
+   * @return  The same FieldDoc passed in.
+   * @see Searchable#search(Weight,Filter,int,Sort)
+   */
+  FieldDoc fillFields (final Entry entry) {
+    final int n = comparators.length;
+    final Comparable[] fields = new Comparable[n];
+    for (int i=0; i<n; ++i)
+      fields[i] = comparators[i].value(entry.slot);
+    //if (maxscore > 1.0f) doc.score /= maxscore;   // normalize scores
+    return new FieldDoc(entry.docID,
+                        entry.score,
+                        fields);
+  }
+
+
+  /** Returns the SortFields being used by this hit queue. */
+  SortField[] getFields() {
+    return fields;
+  }
+  
+  /**
+   * Attempts to detect the given field type for an IndexReader.
+   */
+  static int detectFieldType(IndexReader reader, String fieldKey) throws IOException {
+    String field = ((String)fieldKey).intern();
+    TermEnum enumerator = reader.terms (new Term (field));
+    try {
+      Term term = enumerator.term();
+      if (term == null) {
+        throw new RuntimeException ("no terms in field " + field + " - cannot determine sort type");
+      }
+      int ret = 0;
+      if (term.field() == field) {
+        String termtext = term.text().trim();
+
+        /**
+         * Java 1.4 level code:
+
+         if (pIntegers.matcher(termtext).matches())
+         return IntegerSortedHitQueue.comparator (reader, enumerator, field);
+
+         else if (pFloats.matcher(termtext).matches())
+         return FloatSortedHitQueue.comparator (reader, enumerator, field);
+         */
+
+        // Java 1.3 level code:
+        try {
+          Integer.parseInt (termtext);
+          ret = SortField.INT;
+        } catch (NumberFormatException nfe1) {
+          try {
+            Long.parseLong(termtext);
+            ret = SortField.LONG;
+          } catch (NumberFormatException nfe2) {
+            try {
+              Float.parseFloat (termtext);
+              ret = SortField.FLOAT;
+            } catch (NumberFormatException nfe3) {
+              ret = SortField.STRING;
+            }
+          }
+        }         
+      } else {
+        throw new RuntimeException ("field \"" + field + "\" does not appear to be indexed");
+      }
+      return ret;
+    } finally {
+      enumerator.close();
+    }
+  }
+}

Propchange: lucene/java/trunk/src/java/org/apache/lucene/search/FieldValueHitQueue.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: lucene/java/trunk/src/java/org/apache/lucene/search/Hit.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/java/org/apache/lucene/search/Hit.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/src/java/org/apache/lucene/search/Hit.java (original)
+++ lucene/java/trunk/src/java/org/apache/lucene/search/Hit.java Tue Jan 27 20:15:21 2009
@@ -26,7 +26,7 @@
  * Wrapper used by {@link HitIterator} to provide a lazily loaded hit
  * from {@link Hits}.
  *
- * @deprecated Hits will be removed in Lucene 3.0. Use {@link TopDocCollector} and {@link TopDocs} instead.
+ * @deprecated Hits will be removed in Lucene 3.0. Use {@link TopScoreDocCollector} and {@link TopDocs} instead.
  */
 public class Hit implements java.io.Serializable {
 

Modified: lucene/java/trunk/src/java/org/apache/lucene/search/HitCollector.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/java/org/apache/lucene/search/HitCollector.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/src/java/org/apache/lucene/search/HitCollector.java (original)
+++ lucene/java/trunk/src/java/org/apache/lucene/search/HitCollector.java Tue Jan 27 20:15:21 2009
@@ -19,7 +19,9 @@
 
 /** Lower-level search API.
  * <br>HitCollectors are primarily meant to be used to implement queries,
- * sorting and filtering.
+ * sorting and filtering.  See {@link
+ * MultiReaderHitCollector} for a lower level and
+ * higher performance (on a multi-segment index) API.
  * @see Searcher#search(Query,HitCollector)
  * @version $Id$
  */

Modified: lucene/java/trunk/src/java/org/apache/lucene/search/HitIterator.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/java/org/apache/lucene/search/HitIterator.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/src/java/org/apache/lucene/search/HitIterator.java (original)
+++ lucene/java/trunk/src/java/org/apache/lucene/search/HitIterator.java Tue Jan 27 20:15:21 2009
@@ -25,7 +25,7 @@
  * {@link Hits#iterator()} returns an instance of this class.  Calls to {@link #next()}
  * return a {@link Hit} instance.
  *
- * @deprecated Hits will be removed in Lucene 3.0. Use {@link TopDocCollector} and {@link TopDocs} instead.
+ * @deprecated Hits will be removed in Lucene 3.0. Use {@link TopScoreDocCollector} and {@link TopDocs} instead.
  */
 public class HitIterator implements Iterator {
   private Hits hits;

Modified: lucene/java/trunk/src/java/org/apache/lucene/search/Hits.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/java/org/apache/lucene/search/Hits.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/src/java/org/apache/lucene/search/Hits.java (original)
+++ lucene/java/trunk/src/java/org/apache/lucene/search/Hits.java Tue Jan 27 20:15:21 2009
@@ -40,9 +40,9 @@
  * (but <code>n</code> &lt; {@link #length()}_at_start). 
  * 
  * @deprecated Hits will be removed in Lucene 3.0. <p>
- * Instead e. g. {@link TopDocCollector} and {@link TopDocs} can be used:<br>
+ * Instead e. g. {@link TopScoreDocCollector} and {@link TopDocs} can be used:<br>
  * <pre>
- *   TopDocCollector collector = new TopDocCollector(hitsPerPage);
+ *   TopScoreDocCollector collector = new TopScoreDocCollector(hitsPerPage);
  *   searcher.search(query, collector);
  *   ScoreDoc[] hits = collector.topDocs().scoreDocs;
  *   for (int i = 0; i < hits.length; i++) {

Modified: lucene/java/trunk/src/java/org/apache/lucene/search/IndexSearcher.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/java/org/apache/lucene/search/IndexSearcher.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/src/java/org/apache/lucene/search/IndexSearcher.java (original)
+++ lucene/java/trunk/src/java/org/apache/lucene/search/IndexSearcher.java Tue Jan 27 20:15:21 2009
@@ -17,6 +17,10 @@
  * limitations under the License.
  */
 
+import java.io.IOException;
+import java.util.List;
+import java.util.ArrayList;
+import org.apache.lucene.util.SorterTemplate;
 import org.apache.lucene.document.Document;
 import org.apache.lucene.document.FieldSelector;
 import org.apache.lucene.index.CorruptIndexException;
@@ -24,8 +28,6 @@
 import org.apache.lucene.index.Term;
 import org.apache.lucene.store.Directory;
 
-import java.io.IOException;
-
 /** Implements search over a single IndexReader.
  *
  * <p>Applications usually need only call the inherited {@link #search(Query)}
@@ -38,6 +40,8 @@
 public class IndexSearcher extends Searcher {
   IndexReader reader;
   private boolean closeReader;
+  private IndexReader[] sortedSubReaders;
+  private int[] sortedStarts;
 
   /** Creates a searcher searching the index in the named directory.
    * @throws CorruptIndexException if the index is corrupt
@@ -63,8 +67,60 @@
   private IndexSearcher(IndexReader r, boolean closeReader) {
     reader = r;
     this.closeReader = closeReader;
+    sortSubReaders();
+  }
+
+  protected void gatherSubReaders(List allSubReaders, IndexReader r) {
+    IndexReader[] subReaders = r.getSequentialSubReaders();
+    if (subReaders == null) {
+      // Add the reader itself, and do not recurse
+      allSubReaders.add(r);
+    } else {
+      for(int i=0;i<subReaders.length;i++) {
+        gatherSubReaders(allSubReaders, subReaders[i]);
+      }
+    }
   }
 
+  static private final IndexReader[] indexReaderZeroArray = new IndexReader[0];
+
+  protected void sortSubReaders() {
+
+    List subReadersList = new ArrayList();
+    gatherSubReaders(subReadersList, reader);
+    sortedSubReaders = (IndexReader[]) subReadersList.toArray(indexReaderZeroArray);
+    final int length = sortedSubReaders.length;
+    sortedStarts = new int[length];
+    int maxDoc = 0;
+    for (int i = 0; i < sortedSubReaders.length; i++) {
+      sortedStarts[i] = maxDoc;
+      maxDoc += sortedSubReaders[i].maxDoc();          // compute maxDocs
+    }
+
+    // sort readers and starts
+    SorterTemplate sorter = new SorterTemplate() {
+        protected int compare(int i, int j) {
+          int num1 = sortedSubReaders[i].numDocs();
+          int num2 = sortedSubReaders[j].numDocs();
+          if (num1 > num2)
+            return -1;
+          if (num1 < num2)
+            return 1;
+          return 0;
+        }
+        protected void swap(int i, int j) {
+          IndexReader temp = sortedSubReaders[i];
+          sortedSubReaders[i] = sortedSubReaders[j];
+          sortedSubReaders[j] = temp;
+
+          int tempInt = sortedStarts[i];
+          sortedStarts[i] = sortedStarts[j];
+          sortedStarts[j] = tempInt;
+        }
+      };
+    sorter.quickSort(0, length - 1);
+  }
+  
   /** Return the {@link IndexReader} this searches. */
   public IndexReader getIndexReader() {
     return reader;
@@ -108,7 +164,7 @@
     if (nDocs <= 0)  // null might be returned from hq.top() below.
       throw new IllegalArgumentException("nDocs must be > 0");
 
-    TopDocCollector collector = new TopDocCollector(nDocs);
+    TopScoreDocCollector collector = new TopScoreDocCollector(nDocs);
     search(weight, filter, collector);
     return collector.topDocs();
   }
@@ -117,16 +173,73 @@
   public TopFieldDocs search(Weight weight, Filter filter, final int nDocs,
                              Sort sort)
       throws IOException {
+    return search(weight, filter, nDocs, sort, true);
+  }
+  
+  /** 
+   * Just like {@link #search(Weight, Filter, int, Sort)},
+   * but you choose whether or not the fields in the
+   * returned {@link FieldDoc} instances should be set by
+   * specifying fillFields.
+   */
+  public TopFieldDocs search(Weight weight, Filter filter, final int nDocs,
+                             Sort sort, boolean fillFields)
+      throws IOException {
+    
+    SortField[] fields = sort.fields;
+    boolean legacy = false;
+    for(int i = 0; i < fields.length; i++) {
+      SortField field = fields[i];
+      String fieldname = field.getField();
+      int type = field.getType();
+      // Resolve AUTO into its true type
+      if (type == SortField.AUTO) {
+        int autotype = FieldValueHitQueue.detectFieldType(reader, fieldname);
+        if (autotype == SortField.STRING) {
+          fields[i] = new SortField (fieldname, field.getLocale(), field.getReverse());
+        } else {
+          fields[i] = new SortField (fieldname, autotype, field.getReverse());
+        }
+      }
 
-    TopFieldDocCollector collector =
-      new TopFieldDocCollector(reader, sort, nDocs);
-    search(weight, filter, collector);
-    return (TopFieldDocs)collector.topDocs();
+      if (field.getUseLegacySearch()) {
+        legacy = true;
+      }
+    }
+    
+    if (legacy) {
+      // Search the single top-level reader
+      TopScoreDocCollector collector = new TopFieldDocCollector(reader, sort, nDocs);
+      collector.setNextReader(reader, 0);
+      doSearch(reader, weight, filter, collector);
+      return (TopFieldDocs) collector.topDocs();
+    } else {
+      // Search each sub-reader
+      TopFieldCollector collector = new TopFieldCollector(sort, nDocs, sortedSubReaders, fillFields);
+      search(weight, filter, collector);
+      return (TopFieldDocs) collector.topDocs();
+    }
   }
 
   // inherit javadoc
-  public void search(Weight weight, Filter filter,
-                     final HitCollector results) throws IOException {
+  public void search(Weight weight, Filter filter, HitCollector results)
+      throws IOException {
+
+    final MultiReaderHitCollector collector;
+    if (results instanceof MultiReaderHitCollector) {
+      collector = (MultiReaderHitCollector) results;
+    } else {
+      collector = new MultiReaderCollectorWrapper(results);
+    }
+
+    for (int i = 0; i < sortedSubReaders.length; i++) { // search each subreader
+      collector.setNextReader(sortedSubReaders[i], sortedStarts[i]);
+      doSearch(sortedSubReaders[i], weight, filter, collector);
+    }
+  }
+  
+  private void doSearch(IndexReader reader, Weight weight, Filter filter,
+      final HitCollector results) throws IOException {
 
     Scorer scorer = weight.scorer(reader);
     if (scorer == null)
@@ -169,4 +282,26 @@
   public Explanation explain(Weight weight, int doc) throws IOException {
     return weight.explain(reader, doc);
   }
+  
+  /**
+   * Wrapper for non expert ({@link HitCollector})
+   * implementations, which simply re-bases the incoming
+   * docID before calling {@link HitCollector#collect}.
+   */
+  static class MultiReaderCollectorWrapper extends MultiReaderHitCollector {
+    private HitCollector collector;
+    private int base = -1;
+
+    public MultiReaderCollectorWrapper(HitCollector collector) {
+      this.collector = collector;
+    }
+    
+    public void collect(int doc, float score) {
+      collector.collect(doc + base, score);
+    }
+
+    public void setNextReader(IndexReader reader, int docBase) {
+      base = docBase;
+    }
+  }
 }

Added: lucene/java/trunk/src/java/org/apache/lucene/search/MultiReaderHitCollector.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/java/org/apache/lucene/search/MultiReaderHitCollector.java?rev=738219&view=auto
==============================================================================
--- lucene/java/trunk/src/java/org/apache/lucene/search/MultiReaderHitCollector.java (added)
+++ lucene/java/trunk/src/java/org/apache/lucene/search/MultiReaderHitCollector.java Tue Jan 27 20:15:21 2009
@@ -0,0 +1,53 @@
+package org.apache.lucene.search;
+
+/**
+ * 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.
+ */
+
+import java.io.IOException;
+
+import org.apache.lucene.index.IndexReader;
+
+/**
+ * Expert: A HitCollector that can be used to collect hits
+ * across sequential IndexReaders.  For a Multi*Reader, this
+ * collector advances through each of the sub readers, in an
+ * arbitrary order. This results in a higher performance
+ * means of collection.
+ *
+ * <b>NOTE:</b> The doc that is passed to the collect method
+ * is relative to the current reader.  You must re-base the
+ * doc, by recording the docBase from the last setNextReader
+ * call, to map it to the docID space of the
+ * Multi*Reader.
+ *
+ * <b>NOTE:</b> This API is experimental and might change in
+ * incompatible ways in the next release.
+ */
+public abstract class MultiReaderHitCollector extends HitCollector {
+  /**
+   * Called before collecting from each IndexReader. All doc 
+   * ids in {@link #collect(int, float)} will correspond to reader.
+   * 
+   * Add docBase to the current IndexReaders internal document id to
+   * re-base ids in {@link #collect(int, float)}.
+   * 
+   * @param reader next IndexReader
+   * @param docBase
+   * @throws IOException
+   */
+  public abstract void setNextReader(IndexReader reader, int docBase) throws IOException;
+}

Propchange: lucene/java/trunk/src/java/org/apache/lucene/search/MultiReaderHitCollector.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: lucene/java/trunk/src/java/org/apache/lucene/search/MultiSearcher.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/java/org/apache/lucene/search/MultiSearcher.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/src/java/org/apache/lucene/search/MultiSearcher.java (original)
+++ lucene/java/trunk/src/java/org/apache/lucene/search/MultiSearcher.java Tue Jan 27 20:15:21 2009
@@ -21,6 +21,7 @@
 import org.apache.lucene.document.FieldSelector;
 import org.apache.lucene.index.CorruptIndexException;
 import org.apache.lucene.index.Term;
+import org.apache.lucene.index.IndexReader;
 
 import java.io.IOException;
 import java.util.HashMap;
@@ -258,12 +259,34 @@
 
       final int start = starts[i];
 
-      searchables[i].search(weight, filter, new HitCollector() {
-	  public void collect(int doc, float score) {
-	    results.collect(doc + start, score);
-	  }
-	});
-
+      final MultiReaderHitCollector hc;
+      if (results instanceof MultiReaderHitCollector) {
+        // results can shift
+        final MultiReaderHitCollector resultsMulti = (MultiReaderHitCollector) results;
+        hc = new MultiReaderHitCollector() {
+            public void collect(int doc, float score) {
+              resultsMulti.collect(doc, score);
+            }
+
+            public void setNextReader(IndexReader reader, int docBase) throws IOException {
+              resultsMulti.setNextReader(reader, start+docBase);
+            }
+          };
+      } else {
+        // We must shift the docIDs
+        hc = new MultiReaderHitCollector() {
+            private int docBase;
+            public void collect(int doc, float score) {
+              results.collect(doc + docBase + start, score);
+            }
+
+            public void setNextReader(IndexReader reader, int docBase) {
+              this.docBase = docBase;
+            }
+          };
+      }
+      
+      searchables[i].search(weight, filter, hc);
     }
   }
 

Modified: lucene/java/trunk/src/java/org/apache/lucene/search/ParallelMultiSearcher.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/java/org/apache/lucene/search/ParallelMultiSearcher.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/src/java/org/apache/lucene/search/ParallelMultiSearcher.java (original)
+++ lucene/java/trunk/src/java/org/apache/lucene/search/ParallelMultiSearcher.java Tue Jan 27 20:15:21 2009
@@ -20,6 +20,7 @@
 import java.io.IOException;
 
 import org.apache.lucene.index.Term;
+import org.apache.lucene.index.IndexReader;
 import org.apache.lucene.util.PriorityQueue;
 
 /** Implements parallel search over a set of <code>Searchables</code>.
@@ -170,12 +171,34 @@
 
       final int start = starts[i];
 
-      searchables[i].search(weight, filter, new HitCollector() {
-          public void collect(int doc, float score) {
-            results.collect(doc + start, score);
-          }
-        });
-
+      final MultiReaderHitCollector hc;
+      if (results instanceof MultiReaderHitCollector) {
+        // results can shift
+        final MultiReaderHitCollector resultsMulti = (MultiReaderHitCollector) results;
+        hc = new MultiReaderHitCollector() {
+            public void collect(int doc, float score) {
+              resultsMulti.collect(doc, score);
+            }
+
+            public void setNextReader(IndexReader reader, int docBase) throws IOException {
+              resultsMulti.setNextReader(reader, start+docBase);
+            }
+          };
+      } else {
+        // We must shift the docIDs
+        hc = new MultiReaderHitCollector() {
+            private int docBase;
+            public void collect(int doc, float score) {
+              results.collect(doc + docBase + start, score);
+            }
+
+            public void setNextReader(IndexReader reader, int docBase) {
+              this.docBase = docBase;
+            }
+          };
+      }
+      
+      searchables[i].search(weight, filter, hc);
     }
   }
 

Modified: lucene/java/trunk/src/java/org/apache/lucene/search/QueryWrapperFilter.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/java/org/apache/lucene/search/QueryWrapperFilter.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/src/java/org/apache/lucene/search/QueryWrapperFilter.java (original)
+++ lucene/java/trunk/src/java/org/apache/lucene/search/QueryWrapperFilter.java Tue Jan 27 20:15:21 2009
@@ -21,7 +21,6 @@
 import java.util.BitSet;
 
 import org.apache.lucene.index.IndexReader;
-import org.apache.lucene.util.OpenBitSet;
 
 /** 
  * Constrains search results to only match those which also match a provided
@@ -51,9 +50,13 @@
   public BitSet bits(IndexReader reader) throws IOException {
     final BitSet bits = new BitSet(reader.maxDoc());
 
-    new IndexSearcher(reader).search(query, new HitCollector() {
+    new IndexSearcher(reader).search(query, new MultiReaderHitCollector() {
+      private int base = -1;
       public final void collect(int doc, float score) {
-        bits.set(doc);  // set bit for hit
+        bits.set(doc + base);  // set bit for hit
+      }
+      public void setNextReader(IndexReader reader, int docBase) {
+        base = docBase;
       }
     });
     return bits;

Modified: lucene/java/trunk/src/java/org/apache/lucene/search/ScoreDocComparator.java
URL: http://svn.apache.org/viewvc/lucene/java/trunk/src/java/org/apache/lucene/search/ScoreDocComparator.java?rev=738219&r1=738218&r2=738219&view=diff
==============================================================================
--- lucene/java/trunk/src/java/org/apache/lucene/search/ScoreDocComparator.java (original)
+++ lucene/java/trunk/src/java/org/apache/lucene/search/ScoreDocComparator.java Tue Jan 27 20:15:21 2009
@@ -25,6 +25,7 @@
  *
  * @since   lucene 1.4
  * @version $Id$
+ * @deprecated use {@link FieldComparator}
  */
 public interface ScoreDocComparator {
 



Mime
View raw message