1 package org.apache.lucene.search;
4 * Licensed to the Apache Software Foundation (ASF) under one or more
5 * contributor license agreements. See the NOTICE file distributed with
6 * this work for additional information regarding copyright ownership.
7 * The ASF licenses this file to You under the Apache License, Version 2.0
8 * (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
20 import java.io.IOException;
21 import java.io.Serializable;
22 import java.text.Collator;
23 import java.util.ArrayList;
24 import java.util.BitSet;
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.Locale;
28 import java.util.concurrent.ExecutorService;
29 import java.util.concurrent.Executors;
30 import java.util.concurrent.TimeUnit;
32 import org.apache.lucene.analysis.MockAnalyzer;
33 import org.apache.lucene.document.Document;
34 import org.apache.lucene.document.Field;
35 import org.apache.lucene.index.CorruptIndexException;
36 import org.apache.lucene.index.IndexReader;
37 import org.apache.lucene.index.IndexWriter;
38 import org.apache.lucene.index.IndexWriterConfig;
39 import org.apache.lucene.index.RandomIndexWriter;
40 import org.apache.lucene.index.Term;
41 import org.apache.lucene.queryParser.ParseException;
42 import org.apache.lucene.search.BooleanClause.Occur;
43 import org.apache.lucene.search.FieldValueHitQueue.Entry;
44 import org.apache.lucene.store.LockObtainFailedException;
45 import org.apache.lucene.store.Directory;
46 import org.apache.lucene.util.DocIdBitSet;
47 import org.apache.lucene.util.LuceneTestCase;
48 import org.apache.lucene.util._TestUtil;
49 import org.junit.BeforeClass;
52 * Unit tests for sorting code.
54 * <p>Created: Feb 17, 2004 4:55:10 PM
59 public class TestSort extends LuceneTestCase implements Serializable {
61 private static int NUM_STRINGS;
62 private IndexSearcher full;
63 private IndexSearcher searchX;
64 private IndexSearcher searchY;
75 public static void beforeClass() throws Exception {
76 NUM_STRINGS = atLeast(6000);
79 // the tracer field is used to determine which document was hit
80 // the contents field is used to search and sort by relevance
81 // the int field to sort by int
82 // the float field to sort by float
83 // the string field to sort by string
84 // the i18n field includes accented characters for testing locale-specific sorting
85 private String[][] data = new String[][] {
86 // tracer contents int float string custom i18n long double, short, byte, 'custom parser encoding'
87 { "A", "x a", "5", "4f", "c", "A-3", "p\u00EAche", "10", "-4.0", "3", "126", "J"},//A, x
88 { "B", "y a", "5", "3.4028235E38", "i", "B-10", "HAT", "1000000000", "40.0", "24", "1", "I"},//B, y
89 { "C", "x a b c", "2147483647", "1.0", "j", "A-2", "p\u00E9ch\u00E9", "99999999","40.00002343", "125", "15", "H"},//C, x
90 { "D", "y a b c", "-1", "0.0f", "a", "C-0", "HUT", String.valueOf(Long.MAX_VALUE),String.valueOf(Double.MIN_VALUE), String.valueOf(Short.MIN_VALUE), String.valueOf(Byte.MIN_VALUE), "G"},//D, y
91 { "E", "x a b c d", "5", "2f", "h", "B-8", "peach", String.valueOf(Long.MIN_VALUE),String.valueOf(Double.MAX_VALUE), String.valueOf(Short.MAX_VALUE), String.valueOf(Byte.MAX_VALUE), "F"},//E,x
92 { "F", "y a b c d", "2", "3.14159f", "g", "B-1", "H\u00C5T", "-44", "343.034435444", "-3", "0", "E"},//F,y
93 { "G", "x a b c d", "3", "-1.0", "f", "C-100", "sin", "323254543543", "4.043544", "5", "100", "D"},//G,x
94 { "H", "y a b c d", "0", "1.4E-45", "e", "C-88", "H\u00D8T", "1023423423005","4.043545", "10", "-50", "C"},//H,y
95 { "I", "x a b c d e f", "-2147483648", "1.0e+0", "d", "A-10", "s\u00EDn", "332422459999", "4.043546", "-340", "51", "B"},//I,x
96 { "J", "y a b c d e f", "4", ".5", "b", "C-7", "HOT", "34334543543", "4.0000220343", "300", "2", "A"},//J,y
97 { "W", "g", "1", null, null, null, null, null, null, null, null, null},
98 { "X", "g", "1", "0.1", null, null, null, null, null, null, null, null},
99 { "Y", "g", "1", "0.2", null, null, null, null, null, null, null, null},
100 { "Z", "f g", null, null, null, null, null, null, null, null, null, null},
102 // Sort Missing first/last
103 { "a", "m", null, null, null, null, null, null, null, null, null, null},
104 { "b", "m", "4", "4.0", "4", null, null, "4", "4", "4", "4", null},
105 { "c", "m", "5", "5.0", "5", null, null, "5", "5", "5", "5", null},
106 { "d", "m", null, null, null, null, null, null, null, null, null, null}
109 // the sort order of Ø versus U depends on the version of the rules being used
110 // for the inherited root locale: Ø's order isnt specified in Locale.US since
111 // its not used in english.
112 private boolean oStrokeFirst = Collator.getInstance(new Locale("")).compare("Ø", "U") < 0;
114 // create an index of all the documents, or just the x, or just the y documents
115 private IndexSearcher getIndex (boolean even, boolean odd)
117 Directory indexStore = newDirectory();
118 dirs.add(indexStore);
119 RandomIndexWriter writer = new RandomIndexWriter(random, indexStore, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).setMergePolicy(newLogMergePolicy()));
121 for (int i=0; i<data.length; ++i) {
122 if (((i%2)==0 && even) || ((i%2)==1 && odd)) {
123 Document doc = new Document();
124 doc.add (new Field ("tracer", data[i][0], Field.Store.YES, Field.Index.NO));
125 doc.add (new Field ("contents", data[i][1], Field.Store.NO, Field.Index.ANALYZED));
126 if (data[i][2] != null) doc.add (new Field ("int", data[i][2], Field.Store.NO, Field.Index.NOT_ANALYZED));
127 if (data[i][3] != null) doc.add (new Field ("float", data[i][3], Field.Store.NO, Field.Index.NOT_ANALYZED));
128 if (data[i][4] != null) doc.add (new Field ("string", data[i][4], Field.Store.NO, Field.Index.NOT_ANALYZED));
129 if (data[i][5] != null) doc.add (new Field ("custom", data[i][5], Field.Store.NO, Field.Index.NOT_ANALYZED));
130 if (data[i][6] != null) doc.add (new Field ("i18n", data[i][6], Field.Store.NO, Field.Index.NOT_ANALYZED));
131 if (data[i][7] != null) doc.add (new Field ("long", data[i][7], Field.Store.NO, Field.Index.NOT_ANALYZED));
132 if (data[i][8] != null) doc.add (new Field ("double", data[i][8], Field.Store.NO, Field.Index.NOT_ANALYZED));
133 if (data[i][9] != null) doc.add (new Field ("short", data[i][9], Field.Store.NO, Field.Index.NOT_ANALYZED));
134 if (data[i][10] != null) doc.add (new Field ("byte", data[i][10], Field.Store.NO, Field.Index.NOT_ANALYZED));
135 if (data[i][11] != null) doc.add (new Field ("parser", data[i][11], Field.Store.NO, Field.Index.NOT_ANALYZED));
136 doc.setBoost(2); // produce some scores above 1.0
137 writer.addDocument (doc);
140 IndexReader reader = writer.getReader();
142 IndexSearcher s = newSearcher(reader);
143 s.setDefaultFieldSortScoring(true, true);
147 private IndexSearcher getFullIndex()
149 return getIndex (true, true);
152 private IndexSearcher getFullStrings() throws CorruptIndexException, LockObtainFailedException, IOException {
153 Directory indexStore = newDirectory();
154 dirs.add(indexStore);
155 IndexWriter writer = new IndexWriter(
157 new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).
158 setMaxBufferedDocs(4).
159 setMergePolicy(newLogMergePolicy(97))
161 for (int i=0; i<NUM_STRINGS; i++) {
162 Document doc = new Document();
163 String num = getRandomCharString(getRandomNumber(2, 8), 48, 52);
164 doc.add (new Field ("tracer", num, Field.Store.YES, Field.Index.NO));
165 //doc.add (new Field ("contents", Integer.toString(i), Field.Store.NO, Field.Index.ANALYZED));
166 doc.add (new Field ("string", num, Field.Store.NO, Field.Index.NOT_ANALYZED));
167 String num2 = getRandomCharString(getRandomNumber(1, 4), 48, 50);
168 doc.add (new Field ("string2", num2, Field.Store.NO, Field.Index.NOT_ANALYZED));
169 doc.add (new Field ("tracer2", num2, Field.Store.YES, Field.Index.NO));
170 doc.setBoost(2); // produce some scores above 1.0
171 writer.addDocument (doc);
174 //writer.optimize ();
175 //System.out.println(writer.getSegmentCount());
177 return new IndexSearcher (indexStore, true);
180 public String getRandomNumberString(int num, int low, int high) {
181 StringBuilder sb = new StringBuilder();
182 for (int i = 0; i < num; i++) {
183 sb.append(getRandomNumber(low, high));
185 return sb.toString();
188 public String getRandomCharString(int num) {
189 return getRandomCharString(num, 48, 122);
192 public String getRandomCharString(int num, int start, int end) {
193 StringBuilder sb = new StringBuilder();
194 for (int i = 0; i < num; i++) {
195 sb.append(new Character((char) getRandomNumber(start, end)));
197 return sb.toString();
200 public int getRandomNumber(final int low, final int high) {
202 int randInt = (Math.abs(random.nextInt()) % (high - low)) + low;
207 private IndexSearcher getXIndex()
209 return getIndex (true, false);
212 private IndexSearcher getYIndex()
214 return getIndex (false, true);
217 private IndexSearcher getEmptyIndex()
219 return getIndex (false, false);
223 public void setUp() throws Exception {
225 full = getFullIndex();
226 searchX = getXIndex();
227 searchY = getYIndex();
228 queryX = new TermQuery (new Term ("contents", "x"));
229 queryY = new TermQuery (new Term ("contents", "y"));
230 queryA = new TermQuery (new Term ("contents", "a"));
231 queryE = new TermQuery (new Term ("contents", "e"));
232 queryF = new TermQuery (new Term ("contents", "f"));
233 queryG = new TermQuery (new Term ("contents", "g"));
234 queryM = new TermQuery (new Term ("contents", "m"));
238 private ArrayList<Directory> dirs = new ArrayList<Directory>();
241 public void tearDown() throws Exception {
243 searchX.reader.close();
244 searchY.reader.close();
248 for (Directory dir : dirs)
253 // test the sorts by score and document number
254 public void testBuiltInSorts() throws Exception {
256 assertMatches (full, queryX, sort, "ACEGI");
257 assertMatches (full, queryY, sort, "BDFHJ");
259 sort.setSort(SortField.FIELD_DOC);
260 assertMatches (full, queryX, sort, "ACEGI");
261 assertMatches (full, queryY, sort, "BDFHJ");
264 // test sorts where the type of field is specified
265 public void testTypedSort() throws Exception {
266 sort.setSort (new SortField ("int", SortField.INT), SortField.FIELD_DOC );
267 assertMatches (full, queryX, sort, "IGAEC");
268 assertMatches (full, queryY, sort, "DHFJB");
270 sort.setSort (new SortField ("float", SortField.FLOAT), SortField.FIELD_DOC );
271 assertMatches (full, queryX, sort, "GCIEA");
272 assertMatches (full, queryY, sort, "DHJFB");
274 sort.setSort (new SortField ("long", SortField.LONG), SortField.FIELD_DOC );
275 assertMatches (full, queryX, sort, "EACGI");
276 assertMatches (full, queryY, sort, "FBJHD");
278 sort.setSort (new SortField ("double", SortField.DOUBLE), SortField.FIELD_DOC );
279 assertMatches (full, queryX, sort, "AGICE");
280 assertMatches (full, queryY, sort, "DJHBF");
282 sort.setSort (new SortField ("byte", SortField.BYTE), SortField.FIELD_DOC );
283 assertMatches (full, queryX, sort, "CIGAE");
284 assertMatches (full, queryY, sort, "DHFBJ");
286 sort.setSort (new SortField ("short", SortField.SHORT), SortField.FIELD_DOC );
287 assertMatches (full, queryX, sort, "IAGCE");
288 assertMatches (full, queryY, sort, "DFHBJ");
290 sort.setSort (new SortField ("string", SortField.STRING), SortField.FIELD_DOC );
291 assertMatches (full, queryX, sort, "AIGEC");
292 assertMatches (full, queryY, sort, "DJHFB");
295 private static class SortMissingLastTestHelper {
296 final SortField sortField;
300 SortMissingLastTestHelper( SortField sortField, Object min, Object max ) {
301 this.sortField = sortField;
307 // test sorts where the type of field is specified
308 public void testSortMissingLast() throws Exception {
310 @SuppressWarnings("boxing")
311 SortMissingLastTestHelper[] ascendTesters = new SortMissingLastTestHelper[] {
312 new SortMissingLastTestHelper( new SortField( "byte", SortField.BYTE ), Byte.MIN_VALUE, Byte.MAX_VALUE ),
313 new SortMissingLastTestHelper( new SortField( "short", SortField.SHORT ), Short.MIN_VALUE, Short.MAX_VALUE ),
314 new SortMissingLastTestHelper( new SortField( "int", SortField.INT ), Integer.MIN_VALUE, Integer.MAX_VALUE ),
315 new SortMissingLastTestHelper( new SortField( "long", SortField.LONG ), Long.MIN_VALUE, Long.MAX_VALUE ),
316 new SortMissingLastTestHelper( new SortField( "float", SortField.FLOAT ), Float.MIN_VALUE, Float.MAX_VALUE ),
317 new SortMissingLastTestHelper( new SortField( "double", SortField.DOUBLE ), Double.MIN_VALUE, Double.MAX_VALUE ),
320 @SuppressWarnings("boxing")
321 SortMissingLastTestHelper[] descendTesters = new SortMissingLastTestHelper[] {
322 new SortMissingLastTestHelper( new SortField( "byte", SortField.BYTE, true ), Byte.MIN_VALUE, Byte.MAX_VALUE ),
323 new SortMissingLastTestHelper( new SortField( "short", SortField.SHORT, true ), Short.MIN_VALUE, Short.MAX_VALUE ),
324 new SortMissingLastTestHelper( new SortField( "int", SortField.INT, true ), Integer.MIN_VALUE, Integer.MAX_VALUE ),
325 new SortMissingLastTestHelper( new SortField( "long", SortField.LONG, true ), Long.MIN_VALUE, Long.MAX_VALUE ),
326 new SortMissingLastTestHelper( new SortField( "float", SortField.FLOAT, true ), Float.MIN_VALUE, Float.MAX_VALUE ),
327 new SortMissingLastTestHelper( new SortField( "double", SortField.DOUBLE, true ), Double.MIN_VALUE, Double.MAX_VALUE ),
330 // Default order: ascending
331 for( SortMissingLastTestHelper t : ascendTesters ) {
332 sort.setSort (t.sortField, SortField.FIELD_DOC );
333 assertMatches("sortField:"+t.sortField, full, queryM, sort, "adbc" );
335 sort.setSort (t.sortField.setMissingValue( t.max ), SortField.FIELD_DOC );
336 assertMatches("sortField:"+t.sortField, full, queryM, sort, "bcad" );
338 sort.setSort (t.sortField.setMissingValue( t.min ), SortField.FIELD_DOC );
339 assertMatches("sortField:"+t.sortField, full, queryM, sort, "adbc" );
342 // Reverse order: descending (Note: Order for un-valued documents remains the same due to tie breaker: a,d)
343 for( SortMissingLastTestHelper t : descendTesters ) {
344 sort.setSort (t.sortField, SortField.FIELD_DOC );
345 assertMatches("sortField:"+t.sortField, full, queryM, sort, "cbad" );
347 sort.setSort (t.sortField.setMissingValue( t.max ), SortField.FIELD_DOC );
348 assertMatches("sortField:"+t.sortField, full, queryM, sort, "adcb" );
350 sort.setSort (t.sortField.setMissingValue( t.min ), SortField.FIELD_DOC );
351 assertMatches("sortField:"+t.sortField, full, queryM, sort, "cbad" );
358 * Test String sorting: small queue to many matches, multi field sort, reverse sort
360 public void testStringSort() throws IOException, ParseException {
361 ScoreDoc[] result = null;
362 IndexSearcher searcher = getFullStrings();
364 new SortField("string", SortField.STRING),
365 new SortField("string2", SortField.STRING, true),
366 SortField.FIELD_DOC );
368 result = searcher.search(new MatchAllDocsQuery(), null, 500, sort).scoreDocs;
370 StringBuilder buff = new StringBuilder();
371 int n = result.length;
373 String lastSub = null;
375 boolean fail = false;
376 for (int x = 0; x < n; ++x) {
377 Document doc2 = searcher.doc(result[x].doc);
378 String[] v = doc2.getValues("tracer");
379 String[] v2 = doc2.getValues("tracer2");
380 for (int j = 0; j < v.length; ++j) {
382 int cmp = v[j].compareTo(last);
383 if (!(cmp >= 0)) { // ensure first field is in order
385 System.out.println("fail:" + v[j] + " < " + last);
387 if (cmp == 0) { // ensure second field is in reverse order
388 cmp = v2[j].compareTo(lastSub);
391 System.out.println("rev field fail:" + v2[j] + " > " + lastSub);
392 } else if(cmp == 0) { // ensure docid is in order
393 if (result[x].doc < lastDocId) {
395 System.out.println("doc fail:" + result[x].doc + " > " + lastDocId);
402 lastDocId = result[x].doc;
403 buff.append(v[j] + "(" + v2[j] + ")(" + result[x].doc+") ");
407 System.out.println("topn field1(field2)(docID):" + buff);
409 assertFalse("Found sort results out of order", fail);
414 * test sorts where the type of field is specified and a custom field parser
415 * is used, that uses a simple char encoding. The sorted string contains a
416 * character beginning from 'A' that is mapped to a numeric value using some
417 * "funny" algorithm to be different for each data type.
419 public void testCustomFieldParserSort() throws Exception {
420 // since tests explicilty uses different parsers on the same fieldname
421 // we explicitly check/purge the FieldCache between each assertMatch
422 FieldCache fc = FieldCache.DEFAULT;
425 sort.setSort (new SortField ("parser", new FieldCache.IntParser(){
426 public final int parseInt(final String val) {
427 return (val.charAt(0)-'A') * 123456;
429 }), SortField.FIELD_DOC );
430 assertMatches (full, queryA, sort, "JIHGFEDCBA");
431 assertSaneFieldCaches(getName() + " IntParser");
434 sort.setSort (new SortField ("parser", new FieldCache.FloatParser(){
435 public final float parseFloat(final String val) {
436 return (float) Math.sqrt( val.charAt(0) );
438 }), SortField.FIELD_DOC );
439 assertMatches (full, queryA, sort, "JIHGFEDCBA");
440 assertSaneFieldCaches(getName() + " FloatParser");
443 sort.setSort (new SortField ("parser", new FieldCache.LongParser(){
444 public final long parseLong(final String val) {
445 return (val.charAt(0)-'A') * 1234567890L;
447 }), SortField.FIELD_DOC );
448 assertMatches (full, queryA, sort, "JIHGFEDCBA");
449 assertSaneFieldCaches(getName() + " LongParser");
452 sort.setSort (new SortField ("parser", new FieldCache.DoubleParser(){
453 public final double parseDouble(final String val) {
454 return Math.pow( val.charAt(0), (val.charAt(0)-'A') );
456 }), SortField.FIELD_DOC );
457 assertMatches (full, queryA, sort, "JIHGFEDCBA");
458 assertSaneFieldCaches(getName() + " DoubleParser");
461 sort.setSort (new SortField ("parser", new FieldCache.ByteParser(){
462 public final byte parseByte(final String val) {
463 return (byte) (val.charAt(0)-'A');
465 }), SortField.FIELD_DOC );
466 assertMatches (full, queryA, sort, "JIHGFEDCBA");
467 assertSaneFieldCaches(getName() + " ByteParser");
470 sort.setSort (new SortField ("parser", new FieldCache.ShortParser(){
471 public final short parseShort(final String val) {
472 return (short) (val.charAt(0)-'A');
474 }), SortField.FIELD_DOC );
475 assertMatches (full, queryA, sort, "JIHGFEDCBA");
476 assertSaneFieldCaches(getName() + " ShortParser");
480 // test sorts when there's nothing in the index
481 public void testEmptyIndex() throws Exception {
482 Searcher empty = getEmptyIndex();
485 assertMatches (empty, queryX, sort, "");
487 sort.setSort(SortField.FIELD_DOC);
488 assertMatches (empty, queryX, sort, "");
490 sort.setSort (new SortField ("int", SortField.INT), SortField.FIELD_DOC );
491 assertMatches (empty, queryX, sort, "");
493 sort.setSort (new SortField ("string", SortField.STRING, true), SortField.FIELD_DOC );
494 assertMatches (empty, queryX, sort, "");
496 sort.setSort (new SortField ("float", SortField.FLOAT), new SortField ("string", SortField.STRING) );
497 assertMatches (empty, queryX, sort, "");
500 static class MyFieldComparator extends FieldComparator<Integer> {
505 MyFieldComparator(int numHits) {
506 slotValues = new int[numHits];
510 public void copy(int slot, int doc) {
511 slotValues[slot] = docValues[doc];
515 public int compare(int slot1, int slot2) {
516 // values are small enough that overflow won't happen
517 return slotValues[slot1] - slotValues[slot2];
521 public int compareBottom(int doc) {
522 return bottomValue - docValues[doc];
526 public void setBottom(int bottom) {
527 bottomValue = slotValues[bottom];
530 private static final FieldCache.IntParser testIntParser = new FieldCache.IntParser() {
531 public final int parseInt(final String val) {
532 return (val.charAt(0)-'A') * 123456;
537 public void setNextReader(IndexReader reader, int docBase) throws IOException {
538 docValues = FieldCache.DEFAULT.getInts(reader, "parser", testIntParser);
542 public Integer value(int slot) {
543 return Integer.valueOf(slotValues[slot]);
547 static class MyFieldComparatorSource extends FieldComparatorSource {
549 public FieldComparator newComparator(String fieldname, int numHits, int sortPos, boolean reversed) {
550 return new MyFieldComparator(numHits);
554 // Test sorting w/ custom FieldComparator
555 public void testNewCustomFieldParserSort() throws Exception {
556 sort.setSort (new SortField ("parser", new MyFieldComparatorSource()));
557 assertMatches (full, queryA, sort, "JIHGFEDCBA");
560 // test sorts in reverse
561 public void testReverseSort() throws Exception {
562 sort.setSort (new SortField (null, SortField.SCORE, true), SortField.FIELD_DOC );
563 assertMatches (full, queryX, sort, "IEGCA");
564 assertMatches (full, queryY, sort, "JFHDB");
566 sort.setSort (new SortField (null, SortField.DOC, true));
567 assertMatches (full, queryX, sort, "IGECA");
568 assertMatches (full, queryY, sort, "JHFDB");
570 sort.setSort (new SortField ("int", SortField.INT, true) );
571 assertMatches (full, queryX, sort, "CAEGI");
572 assertMatches (full, queryY, sort, "BJFHD");
574 sort.setSort (new SortField ("float", SortField.FLOAT, true) );
575 assertMatches (full, queryX, sort, "AECIG");
576 assertMatches (full, queryY, sort, "BFJHD");
578 sort.setSort (new SortField ("string", SortField.STRING, true) );
579 assertMatches (full, queryX, sort, "CEGIA");
580 assertMatches (full, queryY, sort, "BFHJD");
583 // test sorting when the sort field is empty (undefined) for some of the documents
584 public void testEmptyFieldSort() throws Exception {
585 sort.setSort (new SortField ("string", SortField.STRING) );
586 assertMatches (full, queryF, sort, "ZJI");
588 sort.setSort (new SortField ("string", SortField.STRING, true) );
589 assertMatches (full, queryF, sort, "IJZ");
591 sort.setSort (new SortField ("i18n", Locale.ENGLISH));
592 assertMatches (full, queryF, sort, "ZJI");
594 sort.setSort (new SortField ("i18n", Locale.ENGLISH, true));
595 assertMatches (full, queryF, sort, "IJZ");
597 sort.setSort (new SortField ("int", SortField.INT) );
598 assertMatches (full, queryF, sort, "IZJ");
600 sort.setSort (new SortField ("int", SortField.INT, true) );
601 assertMatches (full, queryF, sort, "JZI");
603 sort.setSort (new SortField ("float", SortField.FLOAT) );
604 assertMatches (full, queryF, sort, "ZJI");
606 // using a nonexisting field as first sort key shouldn't make a difference:
607 sort.setSort (new SortField ("nosuchfield", SortField.STRING),
608 new SortField ("float", SortField.FLOAT) );
609 assertMatches (full, queryF, sort, "ZJI");
611 sort.setSort (new SortField ("float", SortField.FLOAT, true) );
612 assertMatches (full, queryF, sort, "IJZ");
614 // When a field is null for both documents, the next SortField should be used.
616 sort.setSort (new SortField ("int", SortField.INT),
617 new SortField ("string", SortField.STRING),
618 new SortField ("float", SortField.FLOAT) );
619 assertMatches (full, queryG, sort, "ZWXY");
621 // Reverse the last criterium to make sure the test didn't pass by chance
622 sort.setSort (new SortField ("int", SortField.INT),
623 new SortField ("string", SortField.STRING),
624 new SortField ("float", SortField.FLOAT, true) );
625 assertMatches (full, queryG, sort, "ZYXW");
627 // Do the same for a MultiSearcher
628 Searcher multiSearcher=new MultiSearcher (new Searchable[] { full });
630 sort.setSort (new SortField ("int", SortField.INT),
631 new SortField ("string", SortField.STRING),
632 new SortField ("float", SortField.FLOAT) );
633 assertMatches (multiSearcher, queryG, sort, "ZWXY");
635 sort.setSort (new SortField ("int", SortField.INT),
636 new SortField ("string", SortField.STRING),
637 new SortField ("float", SortField.FLOAT, true) );
638 assertMatches (multiSearcher, queryG, sort, "ZYXW");
639 // Don't close the multiSearcher. it would close the full searcher too!
641 // Do the same for a ParallelMultiSearcher
642 ExecutorService exec = Executors.newFixedThreadPool(_TestUtil.nextInt(random, 2, 8));
643 Searcher parallelSearcher=new ParallelMultiSearcher (exec, full);
645 sort.setSort (new SortField ("int", SortField.INT),
646 new SortField ("string", SortField.STRING),
647 new SortField ("float", SortField.FLOAT) );
648 assertMatches (parallelSearcher, queryG, sort, "ZWXY");
650 sort.setSort (new SortField ("int", SortField.INT),
651 new SortField ("string", SortField.STRING),
652 new SortField ("float", SortField.FLOAT, true) );
653 assertMatches (parallelSearcher, queryG, sort, "ZYXW");
654 parallelSearcher.close();
655 exec.awaitTermination(1000, TimeUnit.MILLISECONDS);
658 // test sorts using a series of fields
659 public void testSortCombos() throws Exception {
660 sort.setSort (new SortField ("int", SortField.INT), new SortField ("float", SortField.FLOAT) );
661 assertMatches (full, queryX, sort, "IGEAC");
663 sort.setSort (new SortField ("int", SortField.INT, true), new SortField (null, SortField.DOC, true) );
664 assertMatches (full, queryX, sort, "CEAGI");
666 sort.setSort (new SortField ("float", SortField.FLOAT), new SortField ("string", SortField.STRING) );
667 assertMatches (full, queryX, sort, "GICEA");
670 // test using a Locale for sorting strings
671 public void testLocaleSort() throws Exception {
672 sort.setSort (new SortField ("string", Locale.US) );
673 assertMatches (full, queryX, sort, "AIGEC");
674 assertMatches (full, queryY, sort, "DJHFB");
676 sort.setSort (new SortField ("string", Locale.US, true) );
677 assertMatches (full, queryX, sort, "CEGIA");
678 assertMatches (full, queryY, sort, "BFHJD");
681 // test using various international locales with accented characters
682 // (which sort differently depending on locale)
683 public void testInternationalSort() throws Exception {
684 sort.setSort (new SortField ("i18n", Locale.US));
685 assertMatches (full, queryY, sort, oStrokeFirst ? "BFJHD" : "BFJDH");
687 sort.setSort (new SortField ("i18n", new Locale("sv", "se")));
688 assertMatches (full, queryY, sort, "BJDFH");
690 sort.setSort (new SortField ("i18n", new Locale("da", "dk")));
691 assertMatches (full, queryY, sort, "BJDHF");
693 sort.setSort (new SortField ("i18n", Locale.US));
694 assertMatches (full, queryX, sort, "ECAGI");
696 sort.setSort (new SortField ("i18n", Locale.FRANCE));
697 assertMatches (full, queryX, sort, "EACGI");
700 // Test the MultiSearcher's ability to preserve locale-sensitive ordering
701 // by wrapping it around a single searcher
702 public void testInternationalMultiSearcherSort() throws Exception {
703 Searcher multiSearcher = new MultiSearcher (new Searchable[] { full });
705 sort.setSort (new SortField ("i18n", new Locale("sv", "se")));
706 assertMatches (multiSearcher, queryY, sort, "BJDFH");
708 sort.setSort (new SortField ("i18n", Locale.US));
709 assertMatches (multiSearcher, queryY, sort, oStrokeFirst ? "BFJHD" : "BFJDH");
711 sort.setSort (new SortField ("i18n", new Locale("da", "dk")));
712 assertMatches (multiSearcher, queryY, sort, "BJDHF");
715 // test a variety of sorts using more than one searcher
716 public void testMultiSort() throws Exception {
717 MultiSearcher searcher = new MultiSearcher (new Searchable[] { searchX, searchY });
718 runMultiSorts(searcher, false);
721 // test a variety of sorts using a parallel multisearcher
722 public void testParallelMultiSort() throws Exception {
723 ExecutorService exec = Executors.newFixedThreadPool(_TestUtil.nextInt(random, 2, 8));
724 Searcher searcher = new ParallelMultiSearcher (exec, searchX, searchY);
725 runMultiSorts(searcher, false);
727 exec.awaitTermination(1000, TimeUnit.MILLISECONDS);
730 // test that the relevancy scores are the same even if
732 public void testNormalizedScores() throws Exception {
734 // capture relevancy scores
735 HashMap<String,Float> scoresX = getScores (full.search (queryX, null, 1000).scoreDocs, full);
736 HashMap<String,Float> scoresY = getScores (full.search (queryY, null, 1000).scoreDocs, full);
737 HashMap<String,Float> scoresA = getScores (full.search (queryA, null, 1000).scoreDocs, full);
739 // we'll test searching locally, remote and multi
741 MultiSearcher multi = new MultiSearcher (new Searchable[] { searchX, searchY });
743 // change sorting and make sure relevancy stays the same
746 assertSameValues (scoresX, getScores (full.search (queryX, null, 1000, sort).scoreDocs, full));
747 assertSameValues (scoresX, getScores (multi.search (queryX, null, 1000, sort).scoreDocs, multi));
748 assertSameValues (scoresY, getScores (full.search (queryY, null, 1000, sort).scoreDocs, full));
749 assertSameValues (scoresY, getScores (multi.search (queryY, null, 1000, sort).scoreDocs, multi));
750 assertSameValues (scoresA, getScores (full.search (queryA, null, 1000, sort).scoreDocs, full));
751 assertSameValues (scoresA, getScores (multi.search (queryA, null, 1000, sort).scoreDocs, multi));
753 sort.setSort(SortField.FIELD_DOC);
754 assertSameValues (scoresX, getScores (full.search (queryX, null, 1000, sort).scoreDocs, full));
755 assertSameValues (scoresX, getScores (multi.search (queryX, null, 1000, sort).scoreDocs, multi));
756 assertSameValues (scoresY, getScores (full.search (queryY, null, 1000, sort).scoreDocs, full));
757 assertSameValues (scoresY, getScores (multi.search (queryY, null, 1000, sort).scoreDocs, multi));
758 assertSameValues (scoresA, getScores (full.search (queryA, null, 1000, sort).scoreDocs, full));
759 assertSameValues (scoresA, getScores (multi.search (queryA, null, 1000, sort).scoreDocs, multi));
761 sort.setSort (new SortField("int", SortField.INT));
762 assertSameValues (scoresX, getScores (full.search (queryX, null, 1000, sort).scoreDocs, full));
763 assertSameValues (scoresX, getScores (multi.search (queryX, null, 1000, sort).scoreDocs, multi));
764 assertSameValues (scoresY, getScores (full.search (queryY, null, 1000, sort).scoreDocs, full));
765 assertSameValues (scoresY, getScores (multi.search (queryY, null, 1000, sort).scoreDocs, multi));
766 assertSameValues (scoresA, getScores (full.search (queryA, null, 1000, sort).scoreDocs, full));
767 assertSameValues (scoresA, getScores (multi.search (queryA, null, 1000, sort).scoreDocs, multi));
769 sort.setSort (new SortField("float", SortField.FLOAT));
770 assertSameValues (scoresX, getScores (full.search (queryX, null, 1000, sort).scoreDocs, full));
771 assertSameValues (scoresX, getScores (multi.search (queryX, null, 1000, sort).scoreDocs, multi));
772 assertSameValues (scoresY, getScores (full.search (queryY, null, 1000, sort).scoreDocs, full));
773 assertSameValues (scoresY, getScores (multi.search (queryY, null, 1000, sort).scoreDocs, multi));
774 assertSameValues (scoresA, getScores (full.search (queryA, null, 1000, sort).scoreDocs, full));
775 assertSameValues (scoresA, getScores (multi.search (queryA, null, 1000, sort).scoreDocs, multi));
777 sort.setSort (new SortField("string", SortField.STRING));
778 assertSameValues (scoresX, getScores (full.search (queryX, null, 1000, sort).scoreDocs, full));
779 assertSameValues (scoresX, getScores (multi.search (queryX, null, 1000, sort).scoreDocs, multi));
780 assertSameValues (scoresY, getScores (full.search (queryY, null, 1000, sort).scoreDocs, full));
781 assertSameValues (scoresY, getScores (multi.search (queryY, null, 1000, sort).scoreDocs, multi));
782 assertSameValues (scoresA, getScores (full.search (queryA, null, 1000, sort).scoreDocs, full));
783 assertSameValues (scoresA, getScores (multi.search (queryA, null, 1000, sort).scoreDocs, multi));
785 sort.setSort (new SortField("int", SortField.INT),new SortField("float", SortField.FLOAT));
786 assertSameValues (scoresX, getScores (full.search (queryX, null, 1000, sort).scoreDocs, full));
787 assertSameValues (scoresX, getScores (multi.search (queryX, null, 1000, sort).scoreDocs, multi));
788 assertSameValues (scoresY, getScores (full.search (queryY, null, 1000, sort).scoreDocs, full));
789 assertSameValues (scoresY, getScores (multi.search (queryY, null, 1000, sort).scoreDocs, multi));
790 assertSameValues (scoresA, getScores (full.search (queryA, null, 1000, sort).scoreDocs, full));
791 assertSameValues (scoresA, getScores (multi.search (queryA, null, 1000, sort).scoreDocs, multi));
793 sort.setSort (new SortField ("int", SortField.INT, true), new SortField (null, SortField.DOC, true) );
794 assertSameValues (scoresX, getScores (full.search (queryX, null, 1000, sort).scoreDocs, full));
795 assertSameValues (scoresX, getScores (multi.search (queryX, null, 1000, sort).scoreDocs, multi));
796 assertSameValues (scoresY, getScores (full.search (queryY, null, 1000, sort).scoreDocs, full));
797 assertSameValues (scoresY, getScores (multi.search (queryY, null, 1000, sort).scoreDocs, multi));
798 assertSameValues (scoresA, getScores (full.search (queryA, null, 1000, sort).scoreDocs, full));
799 assertSameValues (scoresA, getScores (multi.search (queryA, null, 1000, sort).scoreDocs, multi));
801 sort.setSort (new SortField("int", SortField.INT),new SortField("string", SortField.STRING));
802 assertSameValues (scoresX, getScores (full.search (queryX, null, 1000, sort).scoreDocs, full));
803 assertSameValues (scoresX, getScores (multi.search (queryX, null, 1000, sort).scoreDocs, multi));
804 assertSameValues (scoresY, getScores (full.search (queryY, null, 1000, sort).scoreDocs, full));
805 assertSameValues (scoresY, getScores (multi.search (queryY, null, 1000, sort).scoreDocs, multi));
806 assertSameValues (scoresA, getScores (full.search (queryA, null, 1000, sort).scoreDocs, full));
807 assertSameValues (scoresA, getScores (multi.search (queryA, null, 1000, sort).scoreDocs, multi));
811 public void testTopDocsScores() throws Exception {
813 // There was previously a bug in FieldSortedHitQueue.maxscore when only a single
814 // doc was added. That is what the following tests for.
815 Sort sort = new Sort();
818 // try to pick a query that will result in an unnormalized
819 // score greater than 1 to test for correct normalization
820 final TopDocs docs1 = full.search(queryE,null,nDocs,sort);
822 // a filter that only allows through the first hit
823 Filter filt = new Filter() {
825 public DocIdSet getDocIdSet(IndexReader reader) throws IOException {
826 BitSet bs = new BitSet(reader.maxDoc());
827 bs.set(0, reader.maxDoc());
828 bs.set(docs1.scoreDocs[0].doc);
829 return new DocIdBitSet(bs);
833 TopDocs docs2 = full.search(queryE, filt, nDocs, sort);
835 assertEquals(docs1.scoreDocs[0].score, docs2.scoreDocs[0].score, 1e-6);
838 public void testSortWithoutFillFields() throws Exception {
840 // There was previously a bug in TopFieldCollector when fillFields was set
841 // to false - the same doc and score was set in ScoreDoc[] array. This test
842 // asserts that if fillFields is false, the documents are set properly. It
843 // does not use Searcher's default search methods (with Sort) since all set
844 // fillFields to true.
845 Sort[] sort = new Sort[] { new Sort(SortField.FIELD_DOC), new Sort() };
846 for (int i = 0; i < sort.length; i++) {
847 Query q = new MatchAllDocsQuery();
848 TopDocsCollector<Entry> tdc = TopFieldCollector.create(sort[i], 10, false,
853 ScoreDoc[] sd = tdc.topDocs().scoreDocs;
854 for (int j = 1; j < sd.length; j++) {
855 assertTrue(sd[j].doc != sd[j - 1].doc);
861 public void testSortWithoutScoreTracking() throws Exception {
863 // Two Sort criteria to instantiate the multi/single comparators.
864 Sort[] sort = new Sort[] {new Sort(SortField.FIELD_DOC), new Sort() };
865 for (int i = 0; i < sort.length; i++) {
866 Query q = new MatchAllDocsQuery();
867 TopDocsCollector<Entry> tdc = TopFieldCollector.create(sort[i], 10, true, false,
872 TopDocs td = tdc.topDocs();
873 ScoreDoc[] sd = td.scoreDocs;
874 for (int j = 0; j < sd.length; j++) {
875 assertTrue(Float.isNaN(sd[j].score));
877 assertTrue(Float.isNaN(td.getMaxScore()));
881 public void testSortWithScoreNoMaxScoreTracking() throws Exception {
883 // Two Sort criteria to instantiate the multi/single comparators.
884 Sort[] sort = new Sort[] {new Sort(SortField.FIELD_DOC), new Sort() };
885 for (int i = 0; i < sort.length; i++) {
886 Query q = new MatchAllDocsQuery();
887 TopDocsCollector<Entry> tdc = TopFieldCollector.create(sort[i], 10, true, true,
892 TopDocs td = tdc.topDocs();
893 ScoreDoc[] sd = td.scoreDocs;
894 for (int j = 0; j < sd.length; j++) {
895 assertTrue(!Float.isNaN(sd[j].score));
897 assertTrue(Float.isNaN(td.getMaxScore()));
901 // MultiComparatorScoringNoMaxScoreCollector
902 public void testSortWithScoreNoMaxScoreTrackingMulti() throws Exception {
904 // Two Sort criteria to instantiate the multi/single comparators.
905 Sort[] sort = new Sort[] {new Sort(SortField.FIELD_DOC, SortField.FIELD_SCORE) };
906 for (int i = 0; i < sort.length; i++) {
907 Query q = new MatchAllDocsQuery();
908 TopDocsCollector<Entry> tdc = TopFieldCollector.create(sort[i], 10, true, true,
913 TopDocs td = tdc.topDocs();
914 ScoreDoc[] sd = td.scoreDocs;
915 for (int j = 0; j < sd.length; j++) {
916 assertTrue(!Float.isNaN(sd[j].score));
918 assertTrue(Float.isNaN(td.getMaxScore()));
922 public void testSortWithScoreAndMaxScoreTracking() throws Exception {
924 // Two Sort criteria to instantiate the multi/single comparators.
925 Sort[] sort = new Sort[] {new Sort(SortField.FIELD_DOC), new Sort() };
926 for (int i = 0; i < sort.length; i++) {
927 Query q = new MatchAllDocsQuery();
928 TopDocsCollector<Entry> tdc = TopFieldCollector.create(sort[i], 10, true, true,
933 TopDocs td = tdc.topDocs();
934 ScoreDoc[] sd = td.scoreDocs;
935 for (int j = 0; j < sd.length; j++) {
936 assertTrue(!Float.isNaN(sd[j].score));
938 assertTrue(!Float.isNaN(td.getMaxScore()));
942 public void testOutOfOrderDocsScoringSort() throws Exception {
944 // Two Sort criteria to instantiate the multi/single comparators.
945 Sort[] sort = new Sort[] {new Sort(SortField.FIELD_DOC), new Sort() };
946 boolean[][] tfcOptions = new boolean[][] {
947 new boolean[] { false, false, false },
948 new boolean[] { false, false, true },
949 new boolean[] { false, true, false },
950 new boolean[] { false, true, true },
951 new boolean[] { true, false, false },
952 new boolean[] { true, false, true },
953 new boolean[] { true, true, false },
954 new boolean[] { true, true, true },
956 String[] actualTFCClasses = new String[] {
957 "OutOfOrderOneComparatorNonScoringCollector",
958 "OutOfOrderOneComparatorScoringMaxScoreCollector",
959 "OutOfOrderOneComparatorScoringNoMaxScoreCollector",
960 "OutOfOrderOneComparatorScoringMaxScoreCollector",
961 "OutOfOrderOneComparatorNonScoringCollector",
962 "OutOfOrderOneComparatorScoringMaxScoreCollector",
963 "OutOfOrderOneComparatorScoringNoMaxScoreCollector",
964 "OutOfOrderOneComparatorScoringMaxScoreCollector"
967 BooleanQuery bq = new BooleanQuery();
968 // Add a Query with SHOULD, since bw.scorer() returns BooleanScorer2
969 // which delegates to BS if there are no mandatory clauses.
970 bq.add(new MatchAllDocsQuery(), Occur.SHOULD);
971 // Set minNrShouldMatch to 1 so that BQ will not optimize rewrite to return
972 // the clause instead of BQ.
973 bq.setMinimumNumberShouldMatch(1);
974 for (int i = 0; i < sort.length; i++) {
975 for (int j = 0; j < tfcOptions.length; j++) {
976 TopDocsCollector<Entry> tdc = TopFieldCollector.create(sort[i], 10,
977 tfcOptions[j][0], tfcOptions[j][1], tfcOptions[j][2], false);
979 assertTrue(tdc.getClass().getName().endsWith("$"+actualTFCClasses[j]));
981 full.search(bq, tdc);
983 TopDocs td = tdc.topDocs();
984 ScoreDoc[] sd = td.scoreDocs;
985 assertEquals(10, sd.length);
990 // OutOfOrderMulti*Collector
991 public void testOutOfOrderDocsScoringSortMulti() throws Exception {
993 // Two Sort criteria to instantiate the multi/single comparators.
994 Sort[] sort = new Sort[] {new Sort(SortField.FIELD_DOC, SortField.FIELD_SCORE) };
995 boolean[][] tfcOptions = new boolean[][] {
996 new boolean[] { false, false, false },
997 new boolean[] { false, false, true },
998 new boolean[] { false, true, false },
999 new boolean[] { false, true, true },
1000 new boolean[] { true, false, false },
1001 new boolean[] { true, false, true },
1002 new boolean[] { true, true, false },
1003 new boolean[] { true, true, true },
1005 String[] actualTFCClasses = new String[] {
1006 "OutOfOrderMultiComparatorNonScoringCollector",
1007 "OutOfOrderMultiComparatorScoringMaxScoreCollector",
1008 "OutOfOrderMultiComparatorScoringNoMaxScoreCollector",
1009 "OutOfOrderMultiComparatorScoringMaxScoreCollector",
1010 "OutOfOrderMultiComparatorNonScoringCollector",
1011 "OutOfOrderMultiComparatorScoringMaxScoreCollector",
1012 "OutOfOrderMultiComparatorScoringNoMaxScoreCollector",
1013 "OutOfOrderMultiComparatorScoringMaxScoreCollector"
1016 BooleanQuery bq = new BooleanQuery();
1017 // Add a Query with SHOULD, since bw.scorer() returns BooleanScorer2
1018 // which delegates to BS if there are no mandatory clauses.
1019 bq.add(new MatchAllDocsQuery(), Occur.SHOULD);
1020 // Set minNrShouldMatch to 1 so that BQ will not optimize rewrite to return
1021 // the clause instead of BQ.
1022 bq.setMinimumNumberShouldMatch(1);
1023 for (int i = 0; i < sort.length; i++) {
1024 for (int j = 0; j < tfcOptions.length; j++) {
1025 TopDocsCollector<Entry> tdc = TopFieldCollector.create(sort[i], 10,
1026 tfcOptions[j][0], tfcOptions[j][1], tfcOptions[j][2], false);
1028 assertTrue(tdc.getClass().getName().endsWith("$"+actualTFCClasses[j]));
1030 full.search(bq, tdc);
1032 TopDocs td = tdc.topDocs();
1033 ScoreDoc[] sd = td.scoreDocs;
1034 assertEquals(10, sd.length);
1039 public void testSortWithScoreAndMaxScoreTrackingNoResults() throws Exception {
1041 // Two Sort criteria to instantiate the multi/single comparators.
1042 Sort[] sort = new Sort[] {new Sort(SortField.FIELD_DOC), new Sort() };
1043 for (int i = 0; i < sort.length; i++) {
1044 TopDocsCollector<Entry> tdc = TopFieldCollector.create(sort[i], 10, true, true, true, true);
1045 TopDocs td = tdc.topDocs();
1046 assertEquals(0, td.totalHits);
1047 assertTrue(Float.isNaN(td.getMaxScore()));
1051 // runs a variety of sorts useful for multisearchers
1052 private void runMultiSorts(Searcher multi, boolean isFull) throws Exception {
1053 sort.setSort(SortField.FIELD_DOC);
1054 String expected = isFull ? "ABCDEFGHIJ" : "ACEGIBDFHJ";
1055 assertMatches(multi, queryA, sort, expected);
1057 sort.setSort(new SortField ("int", SortField.INT));
1058 expected = isFull ? "IDHFGJABEC" : "IDHFGJAEBC";
1059 assertMatches(multi, queryA, sort, expected);
1061 sort.setSort(new SortField ("int", SortField.INT), SortField.FIELD_DOC);
1062 expected = isFull ? "IDHFGJABEC" : "IDHFGJAEBC";
1063 assertMatches(multi, queryA, sort, expected);
1065 sort.setSort(new SortField("int", SortField.INT));
1066 expected = isFull ? "IDHFGJABEC" : "IDHFGJAEBC";
1067 assertMatches(multi, queryA, sort, expected);
1069 sort.setSort(new SortField ("float", SortField.FLOAT), SortField.FIELD_DOC);
1070 assertMatches(multi, queryA, sort, "GDHJCIEFAB");
1072 sort.setSort(new SortField("float", SortField.FLOAT));
1073 assertMatches(multi, queryA, sort, "GDHJCIEFAB");
1075 sort.setSort(new SortField("string", SortField.STRING));
1076 assertMatches(multi, queryA, sort, "DJAIHGFEBC");
1078 sort.setSort(new SortField("int", SortField.INT, true));
1079 expected = isFull ? "CABEJGFHDI" : "CAEBJGFHDI";
1080 assertMatches(multi, queryA, sort, expected);
1082 sort.setSort(new SortField("float", SortField.FLOAT, true));
1083 assertMatches(multi, queryA, sort, "BAFECIJHDG");
1085 sort.setSort(new SortField("string", SortField.STRING, true));
1086 assertMatches(multi, queryA, sort, "CBEFGHIAJD");
1088 sort.setSort(new SortField("int", SortField.INT),new SortField("float", SortField.FLOAT));
1089 assertMatches(multi, queryA, sort, "IDHFGJEABC");
1091 sort.setSort(new SortField("float", SortField.FLOAT),new SortField("string", SortField.STRING));
1092 assertMatches(multi, queryA, sort, "GDHJICEFAB");
1094 sort.setSort(new SortField ("int", SortField.INT));
1095 assertMatches(multi, queryF, sort, "IZJ");
1097 sort.setSort(new SortField ("int", SortField.INT, true));
1098 assertMatches(multi, queryF, sort, "JZI");
1100 sort.setSort(new SortField ("float", SortField.FLOAT));
1101 assertMatches(multi, queryF, sort, "ZJI");
1103 sort.setSort(new SortField ("string", SortField.STRING));
1104 assertMatches(multi, queryF, sort, "ZJI");
1106 sort.setSort(new SortField ("string", SortField.STRING, true));
1107 assertMatches(multi, queryF, sort, "IJZ");
1109 // up to this point, all of the searches should have "sane"
1110 // FieldCache behavior, and should have reused hte cache in several cases
1111 assertSaneFieldCaches(getName() + " various");
1112 // next we'll check Locale based (String[]) for 'string', so purge first
1113 FieldCache.DEFAULT.purgeAllCaches();
1115 sort.setSort(new SortField ("string", Locale.US) );
1116 assertMatches(multi, queryA, sort, "DJAIHGFEBC");
1118 sort.setSort(new SortField ("string", Locale.US, true) );
1119 assertMatches(multi, queryA, sort, "CBEFGHIAJD");
1121 sort.setSort(new SortField ("string", Locale.UK) );
1122 assertMatches(multi, queryA, sort, "DJAIHGFEBC");
1124 assertSaneFieldCaches(getName() + " Locale.US + Locale.UK");
1125 FieldCache.DEFAULT.purgeAllCaches();
1129 private void assertMatches(Searcher searcher, Query query, Sort sort, String expectedResult) throws IOException {
1130 assertMatches( null, searcher, query, sort, expectedResult );
1133 // make sure the documents returned by the search match the expected list
1134 private void assertMatches(String msg, Searcher searcher, Query query, Sort sort,
1135 String expectedResult) throws IOException {
1136 //ScoreDoc[] result = searcher.search (query, null, 1000, sort).scoreDocs;
1137 TopDocs hits = searcher.search (query, null, Math.max(1, expectedResult.length()), sort);
1138 ScoreDoc[] result = hits.scoreDocs;
1139 assertEquals(expectedResult.length(),hits.totalHits);
1140 StringBuilder buff = new StringBuilder(10);
1141 int n = result.length;
1142 for (int i=0; i<n; ++i) {
1143 Document doc = searcher.doc(result[i].doc);
1144 String[] v = doc.getValues("tracer");
1145 for (int j=0; j<v.length; ++j) {
1149 assertEquals (msg, expectedResult, buff.toString());
1152 private HashMap<String,Float> getScores (ScoreDoc[] hits, Searcher searcher)
1153 throws IOException {
1154 HashMap<String,Float> scoreMap = new HashMap<String,Float>();
1155 int n = hits.length;
1156 for (int i=0; i<n; ++i) {
1157 Document doc = searcher.doc(hits[i].doc);
1158 String[] v = doc.getValues("tracer");
1159 assertEquals (v.length, 1);
1160 scoreMap.put (v[0], Float.valueOf(hits[i].score));
1165 // make sure all the values in the maps match
1166 private <K, V> void assertSameValues (HashMap<K,V> m1, HashMap<K,V> m2) {
1169 assertEquals (n, m);
1170 Iterator<K> iter = m1.keySet().iterator();
1171 while (iter.hasNext()) {
1172 K key = iter.next();
1175 if (o1 instanceof Float) {
1176 assertEquals(((Float)o1).floatValue(), ((Float)o2).floatValue(), 1e-6);
1178 assertEquals (m1.get(key), m2.get(key));
1183 public void testEmptyStringVsNullStringSort() throws Exception {
1184 Directory dir = newDirectory();
1185 IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(
1186 TEST_VERSION_CURRENT, new MockAnalyzer(random)));
1187 Document doc = new Document();
1188 doc.add(newField("f", "", Field.Store.NO, Field.Index.NOT_ANALYZED));
1189 doc.add(newField("t", "1", Field.Store.NO, Field.Index.NOT_ANALYZED));
1192 doc = new Document();
1193 doc.add(newField("t", "1", Field.Store.NO, Field.Index.NOT_ANALYZED));
1196 IndexReader r = IndexReader.open(w, true);
1198 IndexSearcher s = newSearcher(r);
1199 TopDocs hits = s.search(new TermQuery(new Term("t", "1")), null, 10, new Sort(new SortField("f", SortField.STRING)));
1200 assertEquals(2, hits.totalHits);
1202 assertEquals(1, hits.scoreDocs[0].doc);
1203 assertEquals(0, hits.scoreDocs[1].doc);
1209 public void testLUCENE2142() throws IOException {
1210 Directory indexStore = newDirectory();
1211 IndexWriter writer = new IndexWriter(indexStore, newIndexWriterConfig(
1212 TEST_VERSION_CURRENT, new MockAnalyzer(random)));
1213 for (int i=0; i<5; i++) {
1214 Document doc = new Document();
1215 doc.add (new Field ("string", "a"+i, Field.Store.NO, Field.Index.NOT_ANALYZED));
1216 doc.add (new Field ("string", "b"+i, Field.Store.NO, Field.Index.NOT_ANALYZED));
1217 writer.addDocument (doc);
1219 writer.optimize(); // enforce one segment to have a higher unique term count in all cases
1222 new SortField("string", SortField.STRING),
1223 SortField.FIELD_DOC );
1224 // this should not throw AIOOBE or RuntimeEx
1225 IndexSearcher searcher = new IndexSearcher(indexStore, true);
1226 searcher.search(new MatchAllDocsQuery(), null, 500, sort);
1231 public void testCountingCollector() throws Exception {
1232 Directory indexStore = newDirectory();
1233 RandomIndexWriter writer = new RandomIndexWriter(random, indexStore);
1234 for (int i=0; i<5; i++) {
1235 Document doc = new Document();
1236 doc.add (new Field ("string", "a"+i, Field.Store.NO, Field.Index.NOT_ANALYZED));
1237 doc.add (new Field ("string", "b"+i, Field.Store.NO, Field.Index.NOT_ANALYZED));
1238 writer.addDocument (doc);
1240 IndexReader reader = writer.getReader();
1243 IndexSearcher searcher = newSearcher(reader);
1244 TotalHitCountCollector c = new TotalHitCountCollector();
1245 searcher.search(new MatchAllDocsQuery(), null, c);
1246 assertEquals(5, c.getTotalHits());