1 package org.apache.lucene.search; 2 3 18 19 import org.apache.lucene.index.IndexReader; 20 import org.apache.lucene.index.Term; 21 import org.apache.lucene.index.TermDocs; 22 import org.apache.lucene.index.TermEnum; 23 24 import java.io.IOException ; 25 import java.io.Serializable ; 26 27 48 public class SampleComparable 49 implements Comparable , Serializable { 50 51 String string_part; 52 Integer int_part; 53 54 public SampleComparable (String s) { 55 int i = s.indexOf ("-"); 56 string_part = s.substring (0, i); 57 int_part = new Integer (s.substring (i + 1)); 58 } 59 60 public int compareTo (Object o) { 61 SampleComparable otherid = (SampleComparable) o; 62 int i = string_part.compareTo (otherid.string_part); 63 if (i == 0) return int_part.compareTo (otherid.int_part); 64 return i; 65 } 66 67 public static SortComparatorSource getComparatorSource () { 68 return new SortComparatorSource () { 69 public ScoreDocComparator newComparator (final IndexReader reader, String fieldname) 70 throws IOException { 71 final String field = fieldname.intern (); 72 final TermEnum enumerator = reader.terms (new Term (fieldname, "")); 73 try { 74 return new ScoreDocComparator () { 75 protected Comparable [] cachedValues = fillCache (reader, enumerator, field); 76 77 public int compare (ScoreDoc i, ScoreDoc j) { 78 return cachedValues[i.doc].compareTo (cachedValues[j.doc]); 79 } 80 81 public Comparable sortValue (ScoreDoc i) { 82 return cachedValues[i.doc]; 83 } 84 85 public int sortType () { 86 return SortField.CUSTOM; 87 } 88 }; 89 } finally { 90 enumerator.close (); 91 } 92 } 93 94 104 protected Comparable [] fillCache (IndexReader reader, TermEnum enumerator, String fieldname) 105 throws IOException { 106 final String field = fieldname.intern (); 107 Comparable [] retArray = new Comparable [reader.maxDoc ()]; 108 if (retArray.length > 0) { 109 TermDocs termDocs = reader.termDocs (); 110 try { 111 if (enumerator.term () == null) { 112 throw new RuntimeException ("no terms in field " + field); 113 } 114 do { 115 Term term = enumerator.term (); 116 if (term.field () != field) break; 117 Comparable termval = getComparable (term.text ()); 118 termDocs.seek (enumerator); 119 while (termDocs.next ()) { 120 retArray[termDocs.doc ()] = termval; 121 } 122 } while (enumerator.next ()); 123 } finally { 124 termDocs.close (); 125 } 126 } 127 return retArray; 128 } 129 130 Comparable getComparable (String termtext) { 131 return new SampleComparable (termtext); 132 } 133 }; 134 } 135 136 public static SortComparator getComparator() { 137 return new SortComparator() { 138 protected Comparable getComparable (String termtext) { 139 return new SampleComparable (termtext); 140 } 141 }; 142 } 143 } | Popular Tags |