KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > lucene > search > Query


1 package org.apache.lucene.search;
2
3 /**
4  * Copyright 2002-2004 The Apache Software Foundation
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18
19 import java.io.IOException JavaDoc;
20
21 import java.util.HashSet JavaDoc;
22 import java.util.Iterator JavaDoc;
23 import java.util.Set JavaDoc;
24
25 import org.apache.lucene.index.IndexReader;
26
27 /** The abstract base class for queries.
28     <p>Instantiable subclasses are:
29     <ul>
30     <li> {@link TermQuery}
31     <li> {@link MultiTermQuery}
32     <li> {@link BooleanQuery}
33     <li> {@link WildcardQuery}
34     <li> {@link PhraseQuery}
35     <li> {@link PrefixQuery}
36     <li> {@link MultiPhraseQuery}
37     <li> {@link FuzzyQuery}
38     <li> {@link RangeQuery}
39     <li> {@link org.apache.lucene.search.spans.SpanQuery}
40     </ul>
41     <p>A parser for queries is contained in:
42     <ul>
43     <li>{@link org.apache.lucene.queryParser.QueryParser QueryParser}
44     </ul>
45 */

46 public abstract class Query implements java.io.Serializable JavaDoc, Cloneable JavaDoc {
47   private float boost = 1.0f; // query boost factor
48

49   /** Sets the boost for this query clause to <code>b</code>. Documents
50    * matching this clause will (in addition to the normal weightings) have
51    * their score multiplied by <code>b</code>.
52    */

53   public void setBoost(float b) { boost = b; }
54
55   /** Gets the boost for this clause. Documents matching
56    * this clause will (in addition to the normal weightings) have their score
57    * multiplied by <code>b</code>. The boost is 1.0 by default.
58    */

59   public float getBoost() { return boost; }
60
61   /** Prints a query to a string, with <code>field</code> as the default field
62    * for terms. <p>The representation used is one that is supposed to be readable
63    * by {@link org.apache.lucene.queryParser.QueryParser QueryParser}. However,
64    * there are the following limitations:
65    * <ul>
66    * <li>If the query was created by the parser, the printed
67    * representation may not be exactly what was parsed. For example,
68    * characters that need to be escaped will be represented without
69    * the required backslash.</li>
70    * <li>Some of the more complicated queries (e.g. span queries)
71    * don't have a representation that can be parsed by QueryParser.</li>
72    * </ul>
73    */

74   public abstract String JavaDoc toString(String JavaDoc field);
75
76   /** Prints a query to a string. */
77   public String JavaDoc toString() {
78     return toString("");
79   }
80
81   /** Expert: Constructs an appropriate Weight implementation for this query.
82    *
83    * <p>Only implemented by primitive queries, which re-write to themselves.
84    */

85   protected Weight createWeight(Searcher searcher) throws IOException JavaDoc {
86     throw new UnsupportedOperationException JavaDoc();
87   }
88
89   /** Expert: Constructs and initializes a Weight for a top-level query. */
90   public Weight weight(Searcher searcher)
91     throws IOException JavaDoc {
92     Query query = searcher.rewrite(this);
93     Weight weight = query.createWeight(searcher);
94     float sum = weight.sumOfSquaredWeights();
95     float norm = getSimilarity(searcher).queryNorm(sum);
96     weight.normalize(norm);
97     return weight;
98   }
99
100   /** Expert: called to re-write queries into primitive queries. For example,
101    * a PrefixQuery will be rewritten into a BooleanQuery that consists
102    * of TermQuerys.
103    */

104   public Query rewrite(IndexReader reader) throws IOException JavaDoc {
105     return this;
106   }
107
108   /** Expert: called when re-writing queries under MultiSearcher.
109    *
110    * Create a single query suitable for use by all subsearchers (in 1-1
111    * correspondence with queries). This is an optimization of the OR of
112    * all queries. We handle the common optimization cases of equal
113    * queries and overlapping clauses of boolean OR queries (as generated
114    * by MultiTermQuery.rewrite() and RangeQuery.rewrite()).
115    * Be careful overriding this method as queries[0] determines which
116    * method will be called and is not necessarily of the same type as
117    * the other queries.
118   */

119   public Query combine(Query[] queries) {
120     HashSet JavaDoc uniques = new HashSet JavaDoc();
121     for (int i = 0; i < queries.length; i++) {
122       Query query = queries[i];
123       BooleanClause[] clauses = null;
124       // check if we can split the query into clauses
125
boolean splittable = (query instanceof BooleanQuery);
126       if(splittable){
127         BooleanQuery bq = (BooleanQuery) query;
128         splittable = bq.isCoordDisabled();
129         clauses = bq.getClauses();
130         for (int j = 0; splittable && j < clauses.length; j++) {
131           splittable = (clauses[j].getOccur() == BooleanClause.Occur.SHOULD);
132         }
133       }
134       if(splittable){
135         for (int j = 0; j < clauses.length; j++) {
136           uniques.add(clauses[j].getQuery());
137         }
138       } else {
139         uniques.add(query);
140       }
141     }
142     // optimization: if we have just one query, just return it
143
if(uniques.size() == 1){
144         return (Query)uniques.iterator().next();
145     }
146     Iterator JavaDoc it = uniques.iterator();
147     BooleanQuery result = new BooleanQuery(true);
148     while (it.hasNext())
149       result.add((Query) it.next(), BooleanClause.Occur.SHOULD);
150     return result;
151   }
152
153   /**
154    * Expert: adds all terms occuring in this query to the terms set. Only
155    * works if this query is in its {@link #rewrite rewritten} form.
156    *
157    * @throws UnsupportedOperationException if this query is not yet rewritten
158    */

159   public void extractTerms(Set JavaDoc terms) {
160     // needs to be implemented by query subclasses
161
throw new UnsupportedOperationException JavaDoc();
162   }
163
164
165   /** Expert: merges the clauses of a set of BooleanQuery's into a single
166    * BooleanQuery.
167    *
168    *<p>A utility for use by {@link #combine(Query[])} implementations.
169    */

170   public static Query mergeBooleanQueries(Query[] queries) {
171     HashSet JavaDoc allClauses = new HashSet JavaDoc();
172     for (int i = 0; i < queries.length; i++) {
173       BooleanClause[] clauses = ((BooleanQuery)queries[i]).getClauses();
174       for (int j = 0; j < clauses.length; j++) {
175         allClauses.add(clauses[j]);
176       }
177     }
178
179     boolean coordDisabled =
180       queries.length==0? false : ((BooleanQuery)queries[0]).isCoordDisabled();
181     BooleanQuery result = new BooleanQuery(coordDisabled);
182     Iterator JavaDoc i = allClauses.iterator();
183     while (i.hasNext()) {
184       result.add((BooleanClause)i.next());
185     }
186     return result;
187   }
188
189   /** Expert: Returns the Similarity implementation to be used for this query.
190    * Subclasses may override this method to specify their own Similarity
191    * implementation, perhaps one that delegates through that of the Searcher.
192    * By default the Searcher's Similarity implementation is returned.*/

193   public Similarity getSimilarity(Searcher searcher) {
194     return searcher.getSimilarity();
195   }
196
197   /** Returns a clone of this query. */
198   public Object JavaDoc clone() {
199     try {
200       return (Query)super.clone();
201     } catch (CloneNotSupportedException JavaDoc e) {
202       throw new RuntimeException JavaDoc("Clone not supported: " + e.getMessage());
203     }
204   }
205 }
206
Popular Tags