1 package org.apache.lucene.search.spans; 2 3 18 19 import java.io.IOException ; 20 21 import java.util.Collection ; 22 import java.util.ArrayList ; 23 24 import org.apache.lucene.index.IndexReader; 25 import org.apache.lucene.index.Term; 26 import org.apache.lucene.index.TermPositions; 27 import org.apache.lucene.util.ToStringUtils; 28 29 30 public class SpanTermQuery extends SpanQuery { 31 private Term term; 32 33 34 public SpanTermQuery(Term term) { this.term = term; } 35 36 37 public Term getTerm() { return term; } 38 39 public String getField() { return term.field(); } 40 41 public Collection getTerms() { 42 Collection terms = new ArrayList (); 43 terms.add(term); 44 return terms; 45 } 46 47 public String toString(String field) { 48 StringBuffer buffer = new StringBuffer (); 49 if (term.field().equals(field)) 50 buffer.append(term.text()); 51 else 52 buffer.append(term.toString()); 53 buffer.append(ToStringUtils.boost(getBoost())); 54 return buffer.toString(); 55 } 56 57 58 public boolean equals(Object o) { 59 if (!(o instanceof SpanTermQuery)) 60 return false; 61 SpanTermQuery other = (SpanTermQuery)o; 62 return (this.getBoost() == other.getBoost()) 63 && this.term.equals(other.term); 64 } 65 66 67 public int hashCode() { 68 return Float.floatToIntBits(getBoost()) ^ term.hashCode() ^ 0xD23FE494; 69 } 70 71 public Spans getSpans(final IndexReader reader) throws IOException { 72 return new Spans() { 73 private TermPositions positions = reader.termPositions(term); 74 75 private int doc = -1; 76 private int freq; 77 private int count; 78 private int position; 79 80 public boolean next() throws IOException { 81 if (count == freq) { 82 if (!positions.next()) { 83 doc = Integer.MAX_VALUE; 84 return false; 85 } 86 doc = positions.doc(); 87 freq = positions.freq(); 88 count = 0; 89 } 90 position = positions.nextPosition(); 91 count++; 92 return true; 93 } 94 95 public boolean skipTo(int target) throws IOException { 96 if (doc >= target) { 98 return true; 99 } 100 101 if (!positions.skipTo(target)) { 102 doc = Integer.MAX_VALUE; 103 return false; 104 } 105 106 doc = positions.doc(); 107 freq = positions.freq(); 108 count = 0; 109 110 position = positions.nextPosition(); 111 count++; 112 113 return true; 114 } 115 116 public int doc() { return doc; } 117 public int start() { return position; } 118 public int end() { return position + 1; } 119 120 public String toString() { 121 return "spans(" + SpanTermQuery.this.toString() + ")@"+ 122 (doc==-1?"START":(doc==Integer.MAX_VALUE)?"END":doc+"-"+position); 123 } 124 125 }; 126 } 127 128 } 129 | Popular Tags |