1 package org.apache.lucene.search; 2 3 18 19 import java.util.BitSet ; 20 import java.util.Date ; 21 import java.io.IOException ; 22 23 import org.apache.lucene.document.DateField; 24 import org.apache.lucene.index.Term; 25 import org.apache.lucene.index.TermDocs; 26 import org.apache.lucene.index.TermEnum; 27 import org.apache.lucene.index.IndexReader; 28 29 38 public class DateFilter extends Filter { 39 String field; 40 41 String start = DateField.MIN_DATE_STRING(); 42 String end = DateField.MAX_DATE_STRING(); 43 44 private DateFilter(String f) { 45 field = f; 46 } 47 48 52 public DateFilter(String f, Date from, Date to) { 53 field = f; 54 start = DateField.dateToString(from); 55 end = DateField.dateToString(to); 56 } 57 58 62 public DateFilter(String f, long from, long to) { 63 field = f; 64 start = DateField.timeToString(from); 65 end = DateField.timeToString(to); 66 } 67 68 72 public static DateFilter Before(String field, Date date) { 73 DateFilter result = new DateFilter(field); 74 result.end = DateField.dateToString(date); 75 return result; 76 } 77 78 82 public static DateFilter Before(String field, long time) { 83 DateFilter result = new DateFilter(field); 84 result.end = DateField.timeToString(time); 85 return result; 86 } 87 88 92 public static DateFilter After(String field, Date date) { 93 DateFilter result = new DateFilter(field); 94 result.start = DateField.dateToString(date); 95 return result; 96 } 97 98 102 public static DateFilter After(String field, long time) { 103 DateFilter result = new DateFilter(field); 104 result.start = DateField.timeToString(time); 105 return result; 106 } 107 108 113 public BitSet bits(IndexReader reader) throws IOException { 114 BitSet bits = new BitSet (reader.maxDoc()); 115 TermEnum enumerator = reader.terms(new Term(field, start)); 116 TermDocs termDocs = reader.termDocs(); 117 if (enumerator.term() == null) { 118 return bits; 119 } 120 121 try { 122 Term stop = new Term(field, end); 123 while (enumerator.term().compareTo(stop) <= 0) { 124 termDocs.seek(enumerator.term()); 125 while (termDocs.next()) { 126 bits.set(termDocs.doc()); 127 } 128 if (!enumerator.next()) { 129 break; 130 } 131 } 132 } finally { 133 enumerator.close(); 134 termDocs.close(); 135 } 136 return bits; 137 } 138 139 public String toString() { 140 StringBuffer buffer = new StringBuffer (); 141 buffer.append(field); 142 buffer.append(":"); 143 buffer.append(DateField.stringToDate(start).toString()); 144 buffer.append("-"); 145 buffer.append(DateField.stringToDate(end).toString()); 146 return buffer.toString(); 147 } 148 } 149 | Popular Tags |