~slub.team/goobi-indexserver/3.x

« back to all changes in this revision

Viewing changes to lucene/backwards/src/test/org/apache/lucene/search/TestSort.java

  • Committer: Sebastian Meyer
  • Date: 2012-08-03 09:12:40 UTC
  • Revision ID: sebastian.meyer@slub-dresden.de-20120803091240-x6861b0vabq1xror
Remove Lucene and Solr source code and add patches instead
Fix Bug #985487: Auto-suggestion for the search interface

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
package org.apache.lucene.search;
2
 
 
3
 
/**
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
10
 
 *
11
 
 *     http://www.apache.org/licenses/LICENSE-2.0
12
 
 *
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.
18
 
 */
19
 
 
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;
31
 
 
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;
50
 
 
51
 
/**
52
 
 * Unit tests for sorting code.
53
 
 *
54
 
 * <p>Created: Feb 17, 2004 4:55:10 PM
55
 
 *
56
 
 * @since   lucene 1.4
57
 
 */
58
 
 
59
 
public class TestSort extends LuceneTestCase implements Serializable {
60
 
 
61
 
  private static int NUM_STRINGS;
62
 
  private IndexSearcher full;
63
 
  private IndexSearcher searchX;
64
 
  private IndexSearcher searchY;
65
 
  private Query queryX;
66
 
  private Query queryY;
67
 
  private Query queryA;
68
 
  private Query queryE;
69
 
  private Query queryF;
70
 
  private Query queryG;
71
 
  private Query queryM;
72
 
  private Sort sort;
73
 
 
74
 
  @BeforeClass
75
 
  public static void beforeClass() throws Exception {
76
 
    NUM_STRINGS = atLeast(6000);
77
 
  }
78
 
  // document data:
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},
101
 
  
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}
107
 
  }; 
108
 
  
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;
113
 
  
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)
116
 
  throws IOException {
117
 
    Directory indexStore = newDirectory();
118
 
    dirs.add(indexStore);
119
 
    RandomIndexWriter writer = new RandomIndexWriter(random, indexStore, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).setMergePolicy(newLogMergePolicy()));
120
 
 
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);
138
 
      }
139
 
    }
140
 
    IndexReader reader = writer.getReader();
141
 
    writer.close ();
142
 
    IndexSearcher s = newSearcher(reader);
143
 
    s.setDefaultFieldSortScoring(true, true);
144
 
    return s;
145
 
  }
146
 
 
147
 
  private IndexSearcher getFullIndex()
148
 
  throws IOException {
149
 
    return getIndex (true, true);
150
 
  }
151
 
  
152
 
  private IndexSearcher getFullStrings() throws CorruptIndexException, LockObtainFailedException, IOException {
153
 
    Directory indexStore = newDirectory();
154
 
    dirs.add(indexStore);
155
 
    IndexWriter writer = new IndexWriter(
156
 
        indexStore,
157
 
        new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).
158
 
            setMaxBufferedDocs(4).
159
 
            setMergePolicy(newLogMergePolicy(97))
160
 
    );
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);
172
 
      
173
 
    }
174
 
    //writer.optimize ();
175
 
    //System.out.println(writer.getSegmentCount());
176
 
    writer.close ();
177
 
    return new IndexSearcher (indexStore, true);
178
 
  }
179
 
  
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));
184
 
    }
185
 
    return sb.toString();
186
 
  }
187
 
  
188
 
  public String getRandomCharString(int num) {
189
 
    return getRandomCharString(num, 48, 122);
190
 
  }
191
 
  
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)));
196
 
    }
197
 
    return sb.toString();
198
 
  }
199
 
  
200
 
  public int getRandomNumber(final int low, final int high) {
201
 
  
202
 
    int randInt = (Math.abs(random.nextInt()) % (high - low)) + low;
203
 
 
204
 
    return randInt;
205
 
  }
206
 
 
207
 
  private IndexSearcher getXIndex()
208
 
  throws IOException {
209
 
    return getIndex (true, false);
210
 
  }
211
 
 
212
 
  private IndexSearcher getYIndex()
213
 
  throws IOException {
214
 
    return getIndex (false, true);
215
 
  }
216
 
 
217
 
  private IndexSearcher getEmptyIndex()
218
 
  throws IOException {
219
 
    return getIndex (false, false);
220
 
  }
221
 
 
222
 
  @Override
223
 
  public void setUp() throws Exception {
224
 
    super.setUp();
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"));
235
 
    sort = new Sort();
236
 
  }
237
 
  
238
 
  private ArrayList<Directory> dirs = new ArrayList<Directory>();
239
 
  
240
 
  @Override
241
 
  public void tearDown() throws Exception {
242
 
    full.reader.close();
243
 
    searchX.reader.close();
244
 
    searchY.reader.close();
245
 
    full.close();
246
 
    searchX.close();
247
 
    searchY.close();
248
 
    for (Directory dir : dirs)
249
 
      dir.close();
250
 
    super.tearDown();
251
 
  }
252
 
 
253
 
  // test the sorts by score and document number
254
 
  public void testBuiltInSorts() throws Exception {
255
 
    sort = new Sort();
256
 
    assertMatches (full, queryX, sort, "ACEGI");
257
 
    assertMatches (full, queryY, sort, "BDFHJ");
258
 
 
259
 
    sort.setSort(SortField.FIELD_DOC);
260
 
    assertMatches (full, queryX, sort, "ACEGI");
261
 
    assertMatches (full, queryY, sort, "BDFHJ");
262
 
  }
263
 
 
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");
269
 
 
270
 
    sort.setSort (new SortField ("float", SortField.FLOAT), SortField.FIELD_DOC );
271
 
    assertMatches (full, queryX, sort, "GCIEA");
272
 
    assertMatches (full, queryY, sort, "DHJFB");
273
 
 
274
 
    sort.setSort (new SortField ("long", SortField.LONG), SortField.FIELD_DOC );
275
 
    assertMatches (full, queryX, sort, "EACGI");
276
 
    assertMatches (full, queryY, sort, "FBJHD");
277
 
 
278
 
    sort.setSort (new SortField ("double", SortField.DOUBLE), SortField.FIELD_DOC );
279
 
    assertMatches (full, queryX, sort, "AGICE");
280
 
    assertMatches (full, queryY, sort, "DJHBF");
281
 
 
282
 
    sort.setSort (new SortField ("byte", SortField.BYTE), SortField.FIELD_DOC );
283
 
    assertMatches (full, queryX, sort, "CIGAE");
284
 
    assertMatches (full, queryY, sort, "DHFBJ");
285
 
 
286
 
    sort.setSort (new SortField ("short", SortField.SHORT), SortField.FIELD_DOC );
287
 
    assertMatches (full, queryX, sort, "IAGCE");
288
 
    assertMatches (full, queryY, sort, "DFHBJ");
289
 
 
290
 
    sort.setSort (new SortField ("string", SortField.STRING), SortField.FIELD_DOC );
291
 
    assertMatches (full, queryX, sort, "AIGEC");
292
 
    assertMatches (full, queryY, sort, "DJHFB");
293
 
  }
294
 
  
295
 
  private static class SortMissingLastTestHelper {
296
 
    final SortField sortField;
297
 
    final Object min;
298
 
    final Object max;
299
 
    
300
 
    SortMissingLastTestHelper( SortField sortField, Object min, Object max ) {
301
 
      this.sortField = sortField;
302
 
      this.min = min;
303
 
      this.max = max;
304
 
    }
305
 
  }
306
 
 
307
 
  // test sorts where the type of field is specified
308
 
  public void testSortMissingLast() throws Exception {
309
 
    
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 ),
318
 
    };
319
 
    
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 ),
328
 
    };
329
 
    
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" );
334
 
 
335
 
      sort.setSort (t.sortField.setMissingValue( t.max ), SortField.FIELD_DOC );
336
 
      assertMatches("sortField:"+t.sortField, full, queryM, sort, "bcad" );
337
 
 
338
 
      sort.setSort (t.sortField.setMissingValue( t.min ), SortField.FIELD_DOC );
339
 
      assertMatches("sortField:"+t.sortField, full, queryM, sort, "adbc" );
340
 
    }
341
 
    
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" );
346
 
      
347
 
      sort.setSort (t.sortField.setMissingValue( t.max ), SortField.FIELD_DOC );
348
 
      assertMatches("sortField:"+t.sortField, full, queryM, sort, "adcb" );
349
 
      
350
 
      sort.setSort (t.sortField.setMissingValue( t.min ), SortField.FIELD_DOC );
351
 
      assertMatches("sortField:"+t.sortField, full, queryM, sort, "cbad" );
352
 
    }
353
 
    
354
 
    
355
 
  }
356
 
  
357
 
  /**
358
 
   * Test String sorting: small queue to many matches, multi field sort, reverse sort
359
 
   */
360
 
  public void testStringSort() throws IOException, ParseException {
361
 
    ScoreDoc[] result = null;
362
 
    IndexSearcher searcher = getFullStrings();
363
 
    sort.setSort(
364
 
        new SortField("string", SortField.STRING),
365
 
        new SortField("string2", SortField.STRING, true),
366
 
        SortField.FIELD_DOC );
367
 
 
368
 
    result = searcher.search(new MatchAllDocsQuery(), null, 500, sort).scoreDocs;
369
 
 
370
 
    StringBuilder buff = new StringBuilder();
371
 
    int n = result.length;
372
 
    String last = null;
373
 
    String lastSub = null;
374
 
    int lastDocId = 0;
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) {
381
 
        if (last != null) {
382
 
          int cmp = v[j].compareTo(last);
383
 
          if (!(cmp >= 0)) { // ensure first field is in order
384
 
            fail = true;
385
 
            System.out.println("fail:" + v[j] + " < " + last);
386
 
          }
387
 
          if (cmp == 0) { // ensure second field is in reverse order
388
 
            cmp = v2[j].compareTo(lastSub);
389
 
            if (cmp > 0) {
390
 
              fail = true;
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) {
394
 
                fail = true;
395
 
                System.out.println("doc fail:" + result[x].doc + " > " + lastDocId);
396
 
              }
397
 
            }
398
 
          }
399
 
        }
400
 
        last = v[j];
401
 
        lastSub = v2[j];
402
 
        lastDocId = result[x].doc;
403
 
        buff.append(v[j] + "(" + v2[j] + ")(" + result[x].doc+") ");
404
 
      }
405
 
    }
406
 
    if(fail) {
407
 
      System.out.println("topn field1(field2)(docID):" + buff);
408
 
    }
409
 
    assertFalse("Found sort results out of order", fail);
410
 
    searcher.close();
411
 
  }
412
 
  
413
 
  /** 
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.
418
 
   */
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;
423
 
 
424
 
 
425
 
    sort.setSort (new SortField ("parser", new FieldCache.IntParser(){
426
 
      public final int parseInt(final String val) {
427
 
        return (val.charAt(0)-'A') * 123456;
428
 
      }
429
 
    }), SortField.FIELD_DOC );
430
 
    assertMatches (full, queryA, sort, "JIHGFEDCBA");
431
 
    assertSaneFieldCaches(getName() + " IntParser");
432
 
    fc.purgeAllCaches();
433
 
 
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) );
437
 
      }
438
 
    }), SortField.FIELD_DOC );
439
 
    assertMatches (full, queryA, sort, "JIHGFEDCBA");
440
 
    assertSaneFieldCaches(getName() + " FloatParser");
441
 
    fc.purgeAllCaches();
442
 
 
443
 
    sort.setSort (new SortField ("parser", new FieldCache.LongParser(){
444
 
      public final long parseLong(final String val) {
445
 
        return (val.charAt(0)-'A') * 1234567890L;
446
 
      }
447
 
    }), SortField.FIELD_DOC );
448
 
    assertMatches (full, queryA, sort, "JIHGFEDCBA");
449
 
    assertSaneFieldCaches(getName() + " LongParser");
450
 
    fc.purgeAllCaches();
451
 
 
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') );
455
 
      }
456
 
    }), SortField.FIELD_DOC );
457
 
    assertMatches (full, queryA, sort, "JIHGFEDCBA");
458
 
    assertSaneFieldCaches(getName() + " DoubleParser");
459
 
    fc.purgeAllCaches();
460
 
 
461
 
    sort.setSort (new SortField ("parser", new FieldCache.ByteParser(){
462
 
      public final byte parseByte(final String val) {
463
 
        return (byte) (val.charAt(0)-'A');
464
 
      }
465
 
    }), SortField.FIELD_DOC );
466
 
    assertMatches (full, queryA, sort, "JIHGFEDCBA");
467
 
    assertSaneFieldCaches(getName() + " ByteParser");
468
 
    fc.purgeAllCaches();
469
 
 
470
 
    sort.setSort (new SortField ("parser", new FieldCache.ShortParser(){
471
 
      public final short parseShort(final String val) {
472
 
        return (short) (val.charAt(0)-'A');
473
 
      }
474
 
    }), SortField.FIELD_DOC );
475
 
    assertMatches (full, queryA, sort, "JIHGFEDCBA");
476
 
    assertSaneFieldCaches(getName() + " ShortParser");
477
 
    fc.purgeAllCaches();
478
 
  }
479
 
 
480
 
  // test sorts when there's nothing in the index
481
 
  public void testEmptyIndex() throws Exception {
482
 
    Searcher empty = getEmptyIndex();
483
 
 
484
 
    sort = new Sort();
485
 
    assertMatches (empty, queryX, sort, "");
486
 
 
487
 
    sort.setSort(SortField.FIELD_DOC);
488
 
    assertMatches (empty, queryX, sort, "");
489
 
 
490
 
    sort.setSort (new SortField ("int", SortField.INT), SortField.FIELD_DOC );
491
 
    assertMatches (empty, queryX, sort, "");
492
 
 
493
 
    sort.setSort (new SortField ("string", SortField.STRING, true), SortField.FIELD_DOC );
494
 
    assertMatches (empty, queryX, sort, "");
495
 
 
496
 
    sort.setSort (new SortField ("float", SortField.FLOAT), new SortField ("string", SortField.STRING) );
497
 
    assertMatches (empty, queryX, sort, "");
498
 
  }
499
 
 
500
 
  static class MyFieldComparator extends FieldComparator<Integer> {
501
 
    int[] docValues;
502
 
    int[] slotValues;
503
 
    int bottomValue;
504
 
 
505
 
    MyFieldComparator(int numHits) {
506
 
      slotValues = new int[numHits];
507
 
    }
508
 
 
509
 
    @Override
510
 
    public void copy(int slot, int doc) {
511
 
      slotValues[slot] = docValues[doc];
512
 
    }
513
 
 
514
 
    @Override
515
 
    public int compare(int slot1, int slot2) {
516
 
      // values are small enough that overflow won't happen
517
 
      return slotValues[slot1] - slotValues[slot2];
518
 
    }
519
 
 
520
 
    @Override
521
 
    public int compareBottom(int doc) {
522
 
      return bottomValue - docValues[doc];
523
 
    }
524
 
 
525
 
    @Override
526
 
    public void setBottom(int bottom) {
527
 
      bottomValue = slotValues[bottom];
528
 
    }
529
 
 
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;
533
 
      }
534
 
    };
535
 
 
536
 
    @Override
537
 
    public void setNextReader(IndexReader reader, int docBase) throws IOException {
538
 
      docValues = FieldCache.DEFAULT.getInts(reader, "parser", testIntParser);
539
 
    }
540
 
 
541
 
    @Override
542
 
    public Integer value(int slot) {
543
 
      return Integer.valueOf(slotValues[slot]);
544
 
    }
545
 
  }
546
 
 
547
 
  static class MyFieldComparatorSource extends FieldComparatorSource {
548
 
    @Override
549
 
    public FieldComparator newComparator(String fieldname, int numHits, int sortPos, boolean reversed) {
550
 
      return new MyFieldComparator(numHits);
551
 
    }
552
 
  }
553
 
 
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");
558
 
  }
559
 
 
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");
565
 
 
566
 
    sort.setSort (new SortField (null, SortField.DOC, true));
567
 
    assertMatches (full, queryX, sort, "IGECA");
568
 
    assertMatches (full, queryY, sort, "JHFDB");
569
 
 
570
 
    sort.setSort (new SortField ("int", SortField.INT, true) );
571
 
    assertMatches (full, queryX, sort, "CAEGI");
572
 
    assertMatches (full, queryY, sort, "BJFHD");
573
 
 
574
 
    sort.setSort (new SortField ("float", SortField.FLOAT, true) );
575
 
    assertMatches (full, queryX, sort, "AECIG");
576
 
    assertMatches (full, queryY, sort, "BFJHD");
577
 
 
578
 
    sort.setSort (new SortField ("string", SortField.STRING, true) );
579
 
    assertMatches (full, queryX, sort, "CEGIA");
580
 
    assertMatches (full, queryY, sort, "BFHJD");
581
 
  }
582
 
 
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");
587
 
 
588
 
    sort.setSort (new SortField ("string", SortField.STRING, true) );
589
 
    assertMatches (full, queryF, sort, "IJZ");
590
 
    
591
 
    sort.setSort (new SortField ("i18n", Locale.ENGLISH));
592
 
    assertMatches (full, queryF, sort, "ZJI");
593
 
    
594
 
    sort.setSort (new SortField ("i18n", Locale.ENGLISH, true));
595
 
    assertMatches (full, queryF, sort, "IJZ");
596
 
 
597
 
    sort.setSort (new SortField ("int", SortField.INT) );
598
 
    assertMatches (full, queryF, sort, "IZJ");
599
 
 
600
 
    sort.setSort (new SortField ("int", SortField.INT, true) );
601
 
    assertMatches (full, queryF, sort, "JZI");
602
 
 
603
 
    sort.setSort (new SortField ("float", SortField.FLOAT) );
604
 
    assertMatches (full, queryF, sort, "ZJI");
605
 
 
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");
610
 
 
611
 
    sort.setSort (new SortField ("float", SortField.FLOAT, true) );
612
 
    assertMatches (full, queryF, sort, "IJZ");
613
 
 
614
 
    // When a field is null for both documents, the next SortField should be used.
615
 
                // Works for
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");
620
 
 
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");
626
 
 
627
 
    // Do the same for a MultiSearcher
628
 
    Searcher multiSearcher=new MultiSearcher (new Searchable[] { full });
629
 
 
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");
634
 
 
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!
640
 
 
641
 
    // Do the same for a ParallelMultiSearcher
642
 
    ExecutorService exec = Executors.newFixedThreadPool(_TestUtil.nextInt(random, 2, 8));
643
 
    Searcher parallelSearcher=new ParallelMultiSearcher (exec, full);
644
 
 
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");
649
 
 
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);
656
 
  }
657
 
 
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");
662
 
 
663
 
    sort.setSort (new SortField ("int", SortField.INT, true), new SortField (null, SortField.DOC, true) );
664
 
    assertMatches (full, queryX, sort, "CEAGI");
665
 
 
666
 
    sort.setSort (new SortField ("float", SortField.FLOAT), new SortField ("string", SortField.STRING) );
667
 
    assertMatches (full, queryX, sort, "GICEA");
668
 
  }
669
 
 
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");
675
 
 
676
 
    sort.setSort (new SortField ("string", Locale.US, true) );
677
 
    assertMatches (full, queryX, sort, "CEGIA");
678
 
    assertMatches (full, queryY, sort, "BFHJD");
679
 
  }
680
 
 
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");
686
 
 
687
 
    sort.setSort (new SortField ("i18n", new Locale("sv", "se")));
688
 
    assertMatches (full, queryY, sort, "BJDFH");
689
 
 
690
 
    sort.setSort (new SortField ("i18n", new Locale("da", "dk")));
691
 
    assertMatches (full, queryY, sort, "BJDHF");
692
 
 
693
 
    sort.setSort (new SortField ("i18n", Locale.US));
694
 
    assertMatches (full, queryX, sort, "ECAGI");
695
 
 
696
 
    sort.setSort (new SortField ("i18n", Locale.FRANCE));
697
 
    assertMatches (full, queryX, sort, "EACGI");
698
 
  }
699
 
    
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 });
704
 
    
705
 
    sort.setSort (new SortField ("i18n", new Locale("sv", "se")));
706
 
    assertMatches (multiSearcher, queryY, sort, "BJDFH");
707
 
    
708
 
    sort.setSort (new SortField ("i18n", Locale.US));
709
 
    assertMatches (multiSearcher, queryY, sort, oStrokeFirst ? "BFJHD" : "BFJDH");
710
 
    
711
 
    sort.setSort (new SortField ("i18n", new Locale("da", "dk")));
712
 
    assertMatches (multiSearcher, queryY, sort, "BJDHF");
713
 
  } 
714
 
 
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);
719
 
  }
720
 
 
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);
726
 
    searcher.close();
727
 
    exec.awaitTermination(1000, TimeUnit.MILLISECONDS);
728
 
  }
729
 
 
730
 
  // test that the relevancy scores are the same even if
731
 
  // hits are sorted
732
 
  public void testNormalizedScores() throws Exception {
733
 
 
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);
738
 
 
739
 
    // we'll test searching locally, remote and multi
740
 
    
741
 
    MultiSearcher multi  = new MultiSearcher (new Searchable[] { searchX, searchY });
742
 
 
743
 
    // change sorting and make sure relevancy stays the same
744
 
 
745
 
    sort = new Sort();
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));
752
 
 
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));
760
 
 
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));
768
 
 
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));
776
 
 
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));
784
 
 
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));
792
 
 
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));
800
 
 
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));
808
 
 
809
 
  }
810
 
 
811
 
  public void testTopDocsScores() throws Exception {
812
 
 
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();
816
 
    int nDocs=10;
817
 
 
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);
821
 
 
822
 
    // a filter that only allows through the first hit
823
 
    Filter filt = new Filter() {
824
 
      @Override
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);
830
 
      }
831
 
    };
832
 
 
833
 
    TopDocs docs2 = full.search(queryE, filt, nDocs, sort);
834
 
    
835
 
    assertEquals(docs1.scoreDocs[0].score, docs2.scoreDocs[0].score, 1e-6);
836
 
  }
837
 
  
838
 
  public void testSortWithoutFillFields() throws Exception {
839
 
    
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,
849
 
          false, false, true);
850
 
      
851
 
      full.search(q, tdc);
852
 
      
853
 
      ScoreDoc[] sd = tdc.topDocs().scoreDocs;
854
 
      for (int j = 1; j < sd.length; j++) {
855
 
        assertTrue(sd[j].doc != sd[j - 1].doc);
856
 
      }
857
 
      
858
 
    }
859
 
  }
860
 
 
861
 
  public void testSortWithoutScoreTracking() throws Exception {
862
 
 
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,
868
 
          false, true);
869
 
      
870
 
      full.search(q, tdc);
871
 
      
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));
876
 
      }
877
 
      assertTrue(Float.isNaN(td.getMaxScore()));
878
 
    }
879
 
  }
880
 
  
881
 
  public void testSortWithScoreNoMaxScoreTracking() throws Exception {
882
 
    
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,
888
 
          false, true);
889
 
      
890
 
      full.search(q, tdc);
891
 
      
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));
896
 
      }
897
 
      assertTrue(Float.isNaN(td.getMaxScore()));
898
 
    }
899
 
  }
900
 
  
901
 
  // MultiComparatorScoringNoMaxScoreCollector
902
 
  public void testSortWithScoreNoMaxScoreTrackingMulti() throws Exception {
903
 
    
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,
909
 
          false, true);
910
 
 
911
 
      full.search(q, tdc);
912
 
      
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));
917
 
      }
918
 
      assertTrue(Float.isNaN(td.getMaxScore()));
919
 
    }
920
 
  }
921
 
  
922
 
  public void testSortWithScoreAndMaxScoreTracking() throws Exception {
923
 
    
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,
929
 
          true, true);
930
 
      
931
 
      full.search(q, tdc);
932
 
      
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));
937
 
      }
938
 
      assertTrue(!Float.isNaN(td.getMaxScore()));
939
 
    }
940
 
  }
941
 
  
942
 
  public void testOutOfOrderDocsScoringSort() throws Exception {
943
 
 
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 },
955
 
    };
956
 
    String[] actualTFCClasses = new String[] {
957
 
        "OutOfOrderOneComparatorNonScoringCollector", 
958
 
        "OutOfOrderOneComparatorScoringMaxScoreCollector", 
959
 
        "OutOfOrderOneComparatorScoringNoMaxScoreCollector", 
960
 
        "OutOfOrderOneComparatorScoringMaxScoreCollector", 
961
 
        "OutOfOrderOneComparatorNonScoringCollector", 
962
 
        "OutOfOrderOneComparatorScoringMaxScoreCollector", 
963
 
        "OutOfOrderOneComparatorScoringNoMaxScoreCollector", 
964
 
        "OutOfOrderOneComparatorScoringMaxScoreCollector" 
965
 
    };
966
 
    
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);
978
 
 
979
 
        assertTrue(tdc.getClass().getName().endsWith("$"+actualTFCClasses[j]));
980
 
        
981
 
        full.search(bq, tdc);
982
 
        
983
 
        TopDocs td = tdc.topDocs();
984
 
        ScoreDoc[] sd = td.scoreDocs;
985
 
        assertEquals(10, sd.length);
986
 
      }
987
 
    }
988
 
  }
989
 
  
990
 
  // OutOfOrderMulti*Collector
991
 
  public void testOutOfOrderDocsScoringSortMulti() throws Exception {
992
 
 
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 },
1004
 
    };
1005
 
    String[] actualTFCClasses = new String[] {
1006
 
        "OutOfOrderMultiComparatorNonScoringCollector", 
1007
 
        "OutOfOrderMultiComparatorScoringMaxScoreCollector", 
1008
 
        "OutOfOrderMultiComparatorScoringNoMaxScoreCollector", 
1009
 
        "OutOfOrderMultiComparatorScoringMaxScoreCollector", 
1010
 
        "OutOfOrderMultiComparatorNonScoringCollector", 
1011
 
        "OutOfOrderMultiComparatorScoringMaxScoreCollector", 
1012
 
        "OutOfOrderMultiComparatorScoringNoMaxScoreCollector", 
1013
 
        "OutOfOrderMultiComparatorScoringMaxScoreCollector" 
1014
 
    };
1015
 
    
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);
1027
 
 
1028
 
        assertTrue(tdc.getClass().getName().endsWith("$"+actualTFCClasses[j]));
1029
 
        
1030
 
        full.search(bq, tdc);
1031
 
        
1032
 
        TopDocs td = tdc.topDocs();
1033
 
        ScoreDoc[] sd = td.scoreDocs;
1034
 
        assertEquals(10, sd.length);
1035
 
      }
1036
 
    }
1037
 
  }
1038
 
  
1039
 
  public void testSortWithScoreAndMaxScoreTrackingNoResults() throws Exception {
1040
 
    
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()));
1048
 
    }
1049
 
  }
1050
 
  
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);
1056
 
 
1057
 
    sort.setSort(new SortField ("int", SortField.INT));
1058
 
    expected = isFull ? "IDHFGJABEC" : "IDHFGJAEBC";
1059
 
    assertMatches(multi, queryA, sort, expected);
1060
 
 
1061
 
    sort.setSort(new SortField ("int", SortField.INT), SortField.FIELD_DOC);
1062
 
    expected = isFull ? "IDHFGJABEC" : "IDHFGJAEBC";
1063
 
    assertMatches(multi, queryA, sort, expected);
1064
 
 
1065
 
    sort.setSort(new SortField("int", SortField.INT));
1066
 
    expected = isFull ? "IDHFGJABEC" : "IDHFGJAEBC";
1067
 
    assertMatches(multi, queryA, sort, expected);
1068
 
 
1069
 
    sort.setSort(new SortField ("float", SortField.FLOAT), SortField.FIELD_DOC);
1070
 
    assertMatches(multi, queryA, sort, "GDHJCIEFAB");
1071
 
 
1072
 
    sort.setSort(new SortField("float", SortField.FLOAT));
1073
 
    assertMatches(multi, queryA, sort, "GDHJCIEFAB");
1074
 
 
1075
 
    sort.setSort(new SortField("string", SortField.STRING));
1076
 
    assertMatches(multi, queryA, sort, "DJAIHGFEBC");
1077
 
 
1078
 
    sort.setSort(new SortField("int", SortField.INT, true));
1079
 
    expected = isFull ? "CABEJGFHDI" : "CAEBJGFHDI";
1080
 
    assertMatches(multi, queryA, sort, expected);
1081
 
 
1082
 
    sort.setSort(new SortField("float", SortField.FLOAT, true));
1083
 
    assertMatches(multi, queryA, sort, "BAFECIJHDG");
1084
 
 
1085
 
    sort.setSort(new SortField("string", SortField.STRING, true));
1086
 
    assertMatches(multi, queryA, sort, "CBEFGHIAJD");
1087
 
 
1088
 
    sort.setSort(new SortField("int", SortField.INT),new SortField("float", SortField.FLOAT));
1089
 
    assertMatches(multi, queryA, sort, "IDHFGJEABC");
1090
 
 
1091
 
    sort.setSort(new SortField("float", SortField.FLOAT),new SortField("string", SortField.STRING));
1092
 
    assertMatches(multi, queryA, sort, "GDHJICEFAB");
1093
 
 
1094
 
    sort.setSort(new SortField ("int", SortField.INT));
1095
 
    assertMatches(multi, queryF, sort, "IZJ");
1096
 
 
1097
 
    sort.setSort(new SortField ("int", SortField.INT, true));
1098
 
    assertMatches(multi, queryF, sort, "JZI");
1099
 
 
1100
 
    sort.setSort(new SortField ("float", SortField.FLOAT));
1101
 
    assertMatches(multi, queryF, sort, "ZJI");
1102
 
 
1103
 
    sort.setSort(new SortField ("string", SortField.STRING));
1104
 
    assertMatches(multi, queryF, sort, "ZJI");
1105
 
 
1106
 
    sort.setSort(new SortField ("string", SortField.STRING, true));
1107
 
    assertMatches(multi, queryF, sort, "IJZ");
1108
 
 
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();
1114
 
 
1115
 
    sort.setSort(new SortField ("string", Locale.US) );
1116
 
    assertMatches(multi, queryA, sort, "DJAIHGFEBC");
1117
 
 
1118
 
    sort.setSort(new SortField ("string", Locale.US, true) );
1119
 
    assertMatches(multi, queryA, sort, "CBEFGHIAJD");
1120
 
 
1121
 
    sort.setSort(new SortField ("string", Locale.UK) );
1122
 
    assertMatches(multi, queryA, sort, "DJAIHGFEBC");
1123
 
 
1124
 
    assertSaneFieldCaches(getName() + " Locale.US + Locale.UK");
1125
 
    FieldCache.DEFAULT.purgeAllCaches();
1126
 
 
1127
 
  }
1128
 
 
1129
 
  private void assertMatches(Searcher searcher, Query query, Sort sort, String expectedResult) throws IOException {
1130
 
    assertMatches( null, searcher, query, sort, expectedResult );
1131
 
  }
1132
 
 
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) {
1146
 
        buff.append (v[j]);
1147
 
      }
1148
 
    }
1149
 
    assertEquals (msg, expectedResult, buff.toString());
1150
 
  }
1151
 
 
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));
1161
 
    }
1162
 
    return scoreMap;
1163
 
  }
1164
 
 
1165
 
  // make sure all the values in the maps match
1166
 
  private <K, V> void assertSameValues (HashMap<K,V> m1, HashMap<K,V> m2) {
1167
 
    int n = m1.size();
1168
 
    int m = m2.size();
1169
 
    assertEquals (n, m);
1170
 
    Iterator<K> iter = m1.keySet().iterator();
1171
 
    while (iter.hasNext()) {
1172
 
      K key = iter.next();
1173
 
      V o1 = m1.get(key);
1174
 
      V o2 = m2.get(key);
1175
 
      if (o1 instanceof Float) {
1176
 
        assertEquals(((Float)o1).floatValue(), ((Float)o2).floatValue(), 1e-6);
1177
 
      } else {
1178
 
        assertEquals (m1.get(key), m2.get(key));
1179
 
      }
1180
 
    }
1181
 
  }
1182
 
 
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));
1190
 
    w.addDocument(doc);
1191
 
    w.commit();
1192
 
    doc = new Document();
1193
 
    doc.add(newField("t", "1", Field.Store.NO, Field.Index.NOT_ANALYZED));
1194
 
    w.addDocument(doc);
1195
 
 
1196
 
    IndexReader r = IndexReader.open(w, true);
1197
 
    w.close();
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);
1201
 
    // null sorts first
1202
 
    assertEquals(1, hits.scoreDocs[0].doc);
1203
 
    assertEquals(0, hits.scoreDocs[1].doc);
1204
 
    s.close();
1205
 
    r.close();
1206
 
    dir.close();
1207
 
  }
1208
 
 
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);
1218
 
    }
1219
 
    writer.optimize(); // enforce one segment to have a higher unique term count in all cases
1220
 
    writer.close();
1221
 
    sort.setSort(
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);
1227
 
    searcher.close();
1228
 
    indexStore.close();
1229
 
  }
1230
 
 
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);
1239
 
    }
1240
 
    IndexReader reader = writer.getReader();
1241
 
    writer.close();
1242
 
 
1243
 
    IndexSearcher searcher = newSearcher(reader);
1244
 
    TotalHitCountCollector c = new TotalHitCountCollector();
1245
 
    searcher.search(new MatchAllDocsQuery(), null, c);
1246
 
    assertEquals(5, c.getTotalHits());
1247
 
    searcher.close();
1248
 
    reader.close();
1249
 
    indexStore.close();
1250
 
  }
1251
 
}