1 package org.apache.lucene.search;
2
3 /**
4 * Licensed to the Apache Software Foundation (ASF) under one or more
5 * contributor license agreements. See the NOTICE file distributed with
6 * this work for additional information regarding copyright ownership.
7 * The ASF licenses this file to You under the Apache License, Version 2.0
8 * (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 */
19
20 import java.io.IOException;
21
22 import java.util.HashSet;
23 import java.util.Iterator;
24 import java.util.Set;
25
26 import org.apache.lucene.index.IndexReader;
27
28 /** The abstract base class for queries.
29 <p>Instantiable subclasses are:
30 <ul>
31 <li> {@link TermQuery}
32 <li> {@link MultiTermQuery}
33 <li> {@link BooleanQuery}
34 <li> {@link WildcardQuery}
35 <li> {@link PhraseQuery}
36 <li> {@link PrefixQuery}
37 <li> {@link MultiPhraseQuery}
38 <li> {@link FuzzyQuery}
39 <li> {@link RangeQuery}
40 <li> {@link org.apache.lucene.search.spans.SpanQuery}
41 </ul>
42 <p>A parser for queries is contained in:
43 <ul>
44 <li>{@link org.apache.lucene.queryParser.QueryParser QueryParser}
45 </ul>
46 */
47 public abstract class Query implements java.io.Serializable, Cloneable {
48 private float boost = 1.0f; // query boost factor
49
50 /** Sets the boost for this query clause to <code>b</code>. Documents
51 * matching this clause will (in addition to the normal weightings) have
52 * their score multiplied by <code>b</code>.
53 */
54 public void setBoost(float b) { boost = b; }
55
56 /** Gets the boost for this clause. Documents matching
57 * this clause will (in addition to the normal weightings) have their score
58 * multiplied by <code>b</code>. The boost is 1.0 by default.
59 */
60 public float getBoost() { return boost; }
61
62 /** Prints a query to a string, with <code>field</code> assumed to be the
63 * default field and omitted.
64 * <p>The representation used is one that is supposed to be readable
65 * by {@link org.apache.lucene.queryParser.QueryParser QueryParser}. However,
66 * there are the following limitations:
67 * <ul>
68 * <li>If the query was created by the parser, the printed
69 * representation may not be exactly what was parsed. For example,
70 * characters that need to be escaped will be represented without
71 * the required backslash.</li>
72 * <li>Some of the more complicated queries (e.g. span queries)
73 * don't have a representation that can be parsed by QueryParser.</li>
74 * </ul>
75 */
76 public abstract String toString(String field);
77
78 /** Prints a query to a string. */
79 public String toString() {
80 return toString("");
81 }
82
83 /** Expert: Constructs an appropriate Weight implementation for this query.
84 *
85 * <p>Only implemented by primitive queries, which re-write to themselves.
86 */
87 protected Weight createWeight(Searcher searcher) throws IOException {
88 throw new UnsupportedOperationException();
89 }
90
91 /** Expert: Constructs and initializes a Weight for a top-level query. */
92 public Weight weight(Searcher searcher)
93 throws IOException {
94 Query query = searcher.rewrite(this);
95 Weight weight = query.createWeight(searcher);
96 float sum = weight.sumOfSquaredWeights();
97 float norm = getSimilarity(searcher).queryNorm(sum);
98 weight.normalize(norm);
99 return weight;
100 }
101
102 /** Expert: called to re-write queries into primitive queries. For example,
103 * a PrefixQuery will be rewritten into a BooleanQuery that consists
104 * of TermQuerys.
105 */
106 public Query rewrite(IndexReader reader) throws IOException {
107 return this;
108 }
109
110 /** Expert: called when re-writing queries under MultiSearcher.
111 *
112 * Create a single query suitable for use by all subsearchers (in 1-1
113 * correspondence with queries). This is an optimization of the OR of
114 * all queries. We handle the common optimization cases of equal
115 * queries and overlapping clauses of boolean OR queries (as generated
116 * by MultiTermQuery.rewrite() and RangeQuery.rewrite()).
117 * Be careful overriding this method as queries[0] determines which
118 * method will be called and is not necessarily of the same type as
119 * the other queries.
120 */
121 public Query combine(Query[] queries) {
122 HashSet uniques = new HashSet();
123 for (int i = 0; i < queries.length; i++) {
124 Query query = queries[i];
125 BooleanClause[] clauses = null;
126 // check if we can split the query into clauses
127 boolean splittable = (query instanceof BooleanQuery);
128 if(splittable){
129 BooleanQuery bq = (BooleanQuery) query;
130 splittable = bq.isCoordDisabled();
131 clauses = bq.getClauses();
132 for (int j = 0; splittable && j < clauses.length; j++) {
133 splittable = (clauses[j].getOccur() == BooleanClause.Occur.SHOULD);
134 }
135 }
136 if(splittable){
137 for (int j = 0; j < clauses.length; j++) {
138 uniques.add(clauses[j].getQuery());
139 }
140 } else {
141 uniques.add(query);
142 }
143 }
144 // optimization: if we have just one query, just return it
145 if(uniques.size() == 1){
146 return (Query)uniques.iterator().next();
147 }
148 Iterator it = uniques.iterator();
149 BooleanQuery result = new BooleanQuery(true);
150 while (it.hasNext())
151 result.add((Query) it.next(), BooleanClause.Occur.SHOULD);
152 return result;
153 }
154
155 /**
156 * Expert: adds all terms occuring in this query to the terms set. Only
157 * works if this query is in its {@link #rewrite rewritten} form.
158 *
159 * @throws UnsupportedOperationException if this query is not yet rewritten
160 */
161 public void extractTerms(Set terms) {
162 // needs to be implemented by query subclasses
163 throw new UnsupportedOperationException();
164 }
165
166
167 /** Expert: merges the clauses of a set of BooleanQuery's into a single
168 * BooleanQuery.
169 *
170 *<p>A utility for use by {@link #combine(Query[])} implementations.
171 */
172 public static Query mergeBooleanQueries(Query[] queries) {
173 HashSet allClauses = new HashSet();
174 for (int i = 0; i < queries.length; i++) {
175 BooleanClause[] clauses = ((BooleanQuery)queries[i]).getClauses();
176 for (int j = 0; j < clauses.length; j++) {
177 allClauses.add(clauses[j]);
178 }
179 }
180
181 boolean coordDisabled =
182 queries.length==0? false : ((BooleanQuery)queries[0]).isCoordDisabled();
183 BooleanQuery result = new BooleanQuery(coordDisabled);
184 Iterator i = allClauses.iterator();
185 while (i.hasNext()) {
186 result.add((BooleanClause)i.next());
187 }
188 return result;
189 }
190
191 /** Expert: Returns the Similarity implementation to be used for this query.
192 * Subclasses may override this method to specify their own Similarity
193 * implementation, perhaps one that delegates through that of the Searcher.
194 * By default the Searcher's Similarity implementation is returned.*/
195 public Similarity getSimilarity(Searcher searcher) {
196 return searcher.getSimilarity();
197 }
198
199 /** Returns a clone of this query. */
200 public Object clone() {
201 try {
202 return (Query)super.clone();
203 } catch (CloneNotSupportedException e) {
204 throw new RuntimeException("Clone not supported: " + e.getMessage());
205 }
206 }
207 }