1 package org.apache.lucene.search; 2 3 18 19 import java.io.IOException ; 20 21 import org.apache.lucene.index.Term; 22 import org.apache.lucene.index.TermEnum; 23 import org.apache.lucene.index.IndexReader; 24 import org.apache.lucene.util.ToStringUtils; 25 26 28 public class PrefixQuery extends Query { 29 private Term prefix; 30 31 32 public PrefixQuery(Term prefix) { 33 this.prefix = prefix; 34 } 35 36 37 public Term getPrefix() { return prefix; } 38 39 public Query rewrite(IndexReader reader) throws IOException { 40 BooleanQuery query = new BooleanQuery(true); 41 TermEnum enumerator = reader.terms(prefix); 42 try { 43 String prefixText = prefix.text(); 44 String prefixField = prefix.field(); 45 do { 46 Term term = enumerator.term(); 47 if (term != null && 48 term.text().startsWith(prefixText) && 49 term.field() == prefixField) { 50 TermQuery tq = new TermQuery(term); tq.setBoost(getBoost()); query.add(tq, BooleanClause.Occur.SHOULD); } else { 55 break; 56 } 57 } while (enumerator.next()); 58 } finally { 59 enumerator.close(); 60 } 61 return query; 62 } 63 64 65 public String toString(String field) { 66 StringBuffer buffer = new StringBuffer (); 67 if (!prefix.field().equals(field)) { 68 buffer.append(prefix.field()); 69 buffer.append(":"); 70 } 71 buffer.append(prefix.text()); 72 buffer.append('*'); 73 buffer.append(ToStringUtils.boost(getBoost())); 74 return buffer.toString(); 75 } 76 77 78 public boolean equals(Object o) { 79 if (!(o instanceof PrefixQuery)) 80 return false; 81 PrefixQuery other = (PrefixQuery)o; 82 return (this.getBoost() == other.getBoost()) 83 && this.prefix.equals(other.prefix); 84 } 85 86 87 public int hashCode() { 88 return Float.floatToIntBits(getBoost()) ^ prefix.hashCode() ^ 0x6634D93C; 89 } 90 } 91 | Popular Tags |