01: /**
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */package org.apache.solr.search;
17:
18: import org.apache.lucene.search.Filter;
19: import org.apache.lucene.index.Term;
20: import org.apache.lucene.index.IndexReader;
21: import org.apache.lucene.index.TermEnum;
22: import org.apache.lucene.index.TermDocs;
23:
24: import java.util.BitSet;
25: import java.io.IOException;
26:
27: /**
28: * @author yonik
29: * @version $Id: PrefixFilter.java 473066 2006-11-09 20:34:19Z yonik $
30: */
31: public class PrefixFilter extends Filter {
32: protected final Term prefix;
33:
34: PrefixFilter(Term prefix) {
35: this .prefix = prefix;
36: }
37:
38: Term getPrefix() {
39: return prefix;
40: }
41:
42: public BitSet bits(IndexReader reader) throws IOException {
43: final BitSet bitSet = new BitSet(reader.maxDoc());
44: new PrefixGenerator(prefix) {
45: public void handleDoc(int doc) {
46: bitSet.set(doc);
47: }
48: }.generate(reader);
49: return bitSet;
50: }
51: }
52:
53: // keep this protected until I decide if it's a good way
54: // to separate id generation from collection (or should
55: // I just reuse hitcollector???)
56: interface IdGenerator {
57: public void generate(IndexReader reader) throws IOException;
58:
59: public void handleDoc(int doc);
60: }
61:
62: abstract class PrefixGenerator implements IdGenerator {
63: protected final Term prefix;
64:
65: PrefixGenerator(Term prefix) {
66: this .prefix = prefix;
67: }
68:
69: public void generate(IndexReader reader) throws IOException {
70: TermEnum enumerator = reader.terms(prefix);
71: TermDocs termDocs = reader.termDocs();
72:
73: try {
74:
75: String prefixText = prefix.text();
76: String prefixField = prefix.field();
77: do {
78: Term term = enumerator.term();
79: if (term != null && term.text().startsWith(prefixText)
80: && term.field() == prefixField) {
81: termDocs.seek(term);
82: while (termDocs.next()) {
83: handleDoc(termDocs.doc());
84: }
85: } else {
86: break;
87: }
88: } while (enumerator.next());
89: } finally {
90: termDocs.close();
91: enumerator.close();
92: }
93: }
94: }
|