Custom sorting: inherits the FieldComparatorSource class and returns a subclass of the FieldComparator class in the newComparator method of this class.
Note: You can refer to the source code of the org. apache. Lucene. search. FieldComparator. StringValComparator class of lucene to complete the experiment by yourself!
Background: When initializing a custom sorting class, the constructor has two parameters: numHits and field.
Parameter description:
NumHits is the total number of rows used to initialize the values array. NumHits is set by ourselves. We set the third parameter in TopDocs topDocs = indexSearcher. search (query, filter, 1000, sort. If the total number of result sets is less than the total number we set, it is determined by the total number of result sets.
Field is the sorting field and the field attribute in the Custom sorting class is initialized. lucene is used to obtain the relevant dataset.
1. setNextReader: Lucene will first call this Method for Data initialization. Here we use a String array currentReaderValues to receive the data.
2. copy: take out the two values in currentReaderValues for the first time and put them all at the specified position in values (note that the values in this array are both null at the beginning.
3. compare: Custom sorting. We can write our code here to see the API description "Compare hit at sort1 with hit at sort2 .", sort2 and sort1 are the index numbers in the index file. Note that the sort1 value is greater than the sort2 value, that is, val1 is the next value and val2 is the previous value, see the API description "Compare hit at sort1 with hit at sort2 ."
4. compareBottom: Check the API description "Compare the bottom of the queue with doc. "This method is called in Lucene. From the description, it is the end of the doc sequence. Haha, the bottom attribute value in the Custom sorting column is the last one in the sequence we want to take out.
The process is: if the priority queue is full, it is first compared with the lowest layer. If it is larger than the lowest layer, it replaces the lowest layer and then sorts the priority queue again, the maximum value of the queue is through ndexSearcher. this can be set in the search method. Of course, the maximum length of the Lucene queue is more than 0.2 billion. So don't worry. When is the column full? What is the maximum queue value? The answer is: the maximum queue value is set by the user. TopDocs topDocs = indexSearcher. search (query, filter, 1000, sort); the third parameter in this sentence is.
Code:
1. DateValComparator class
Package com. meiya. comparator; import java. io. IOException; import java. text. simpleDateFormat; import java. util. date; import org. apache. lucene. index. indexReader; import org. apache. lucene. search. fieldCache; import org. apache. lucene. search. fieldComparator;/*** implement custom date sorting ** @ author Lin ji qin * @ version 1.0 08:57:54 */@ SuppressWarnings ("unchecked") public class DateValComparator extends FieldComparator {/** Stores the sorted dataset */private String [] values;/** receives the String array read from IndexReader, that is, the result set before sorting */private String [] currentReaderValues; /** sort field */private final String field;/** tail sequence of doc */private String bottom; SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss ");/*** default constructor ** @ param numHits total number of rows * @ param field sorting field */DateValComparator (int numHits, String field) {this. values = new String [NumHits]; this. field = field;}/*** Step 3: Customize date sorting, if the query result does not exceed the set total number of rows, this method is called to compare <br/> ** if sort1 is smaller than sort2, a negative number is returned; <br/> If sort1 is greater than sort2, a positive number is returned. <br/> if they are equal, 0 is returned; <br/> ** note that the sort1 value is greater than the sort2 value */@ Override public int compare (int sort1, int sort2) {try {Date after = format. parse (this. values [sort1]); Date before = format. parse (this. values [sort2]); if (null = after) {if (null = before) {r Eturn 0;} return-1;} if (null = before) {return 1;} if (after. after (before) {return 1;} if (before. after (after) {return-1 ;}} catch (Exception e) {e. printStackTrace ();} return 0;}/*** the Lucene query result is placed in the priority queue, and the priority object is compared through compare, if the query result exceeds the set total number of rows, this method will be called in the second step */@ Override public int compareBottom (int doc) throws IOException {try {Date before = format. parse (this. currentReaderValues [d Oc]); Date tempBottom = format. parse (this. bottom); if (tempBottom = null) {if (before = null) {return 0;} return-1;} if (before = null) {return 1 ;} if (before. after (tempBottom) {return 1;} if (tempBottom. after (before) {return-1 ;}} catch (Exception e) {e. printStackTrace ();} return 0;}/*** Step 2: copy the first value in the currentReaderValues array to the corresponding position in the values, note that this method is called twice for the first time. * // @ Override public void copy (int sort, int doc) throws IOException {this. values [sort] = this. currentReaderValues [doc];}/*** if the query result exceeds the total number of rows we set, this method will be called in the First Step */@ Override public void setBottom (int bottom) {this. bottom = this. values [bottom];}/*** Step 1: Lucene first calls this method to initialize the data. Here, the currentReaderValues array parameter is used to receive the data. * // @ Override public void setNextReader (IndexReader reader, int docBase) throws IOException {this. currentReaderValues = FieldCache. DEFAULT. getStrings (reader, this. field);}/*** output the sorted result set */@ Override public String value (int sort) {return this. values [sort] ;}}
2. DateValComparatorSource class
Package com. meiya. comparator; import java. io. IOException; import org. apache. log4j. logger; import org. apache. lucene. search. fieldComparator; import org. apache. lucene. search. fieldComparatorSource;/*** custom date sorting calling portal class ** @ author Lin ji qin * @ version 1.0 10:07:58 */@ SuppressWarnings ("serial ") public class DateValComparatorSource extends FieldComparatorSource {private static final Logger LOG = Logger. getLog Ger (DateValComparatorSource. class); @ SuppressWarnings ("unchecked") @ Override public FieldComparator newComparator (String field, int numHits, int newCount, boolean reversed) throws IOException {LOG.info (String. format ("Total number of rows: % s, sorting field: % s, sorting method: % s. ", NumHits, field, reversed = true? "Descending": "ASCENDING"); return new DateValComparator (numHits, field );}}
3. unit test code
/*** Custom date sorting unit Test ** @ throws Exception */@ Test public void sort () throws Exception {IndexReader reader = IndexReader. open (FSDirectory. open (new File (XMLPropertyConfig. getConfigXML (). getString ("meiya_movice_index"), true); IndexSearcher searcher = new IndexSearcher (reader); TermRangeQuery timeQuery = new TermRangeQuery (MyMovieSource. UPDATE_TIME, "1988-03-09", "2014-01-07", true, true); // true reverse, false ascending // Sort sort = new Sort (new SortField ("update_time ", new DateValComparatorSource (), false); // ascending Sort sort = new Sort (new SortField ("update_time", new DateValComparatorSource (), true )); // TopDocs topDocs = searcher in descending order. search (timeQuery, 1000, sort); System. out. println ("Total retrieved" + topDocs. totalHits + "record"); System. out. println (); ScoreDoc [] scoreDocs = topDocs. scoreDocs; for (ScoreDoc scDoc: scoreDocs) {Document document = searcher.doc(scDoc.doc); System. out. println ("updated at:" + document. get (MyMovieSource. UPDATE_TIME);} searcher. close (); reader. close ();}
4. The test results are as follows:
[INFO] [11:46:19 187]-com. meiya. util. XMLPropertyConfig.61 [main]-Prepare to load the configuration file [AppConfig. xml ]. [INFO] [11:46:19 265]-com. meiya. util. XMLPropertyConfig.63 [main]-the configuration file AppConfig. xml is loaded completely. [INFO] [11:46:19 406]-com. meiya. comparator. DateValComparatorSource.25 [main]-Total number of rows: 1000, sorting field: update_time, sorting method: ascending. 11997 records updated: 23:43:11 Update Time: 10:22:09 Update Time: 17:35:45 Update Time: 00:24:32 Update Time: 17:52:09 Update Time: 01:29:00 Update Time: 18:51:37 updated on: 22:26:40
Sort from http://javastudyeye.iteye.com/blog/893921