1 package org.apache.lucene.search;
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 import java.io.IOException;
22 import java.util.HashSet;
26 import org.apache.lucene.index.IndexReader;
27 import org.apache.lucene.index.Term;
29 /** The abstract base class for queries.
30 <p>Instantiable subclasses are:
32 <li> {@link TermQuery}
33 <li> {@link MultiTermQuery}
34 <li> {@link BooleanQuery}
35 <li> {@link WildcardQuery}
36 <li> {@link PhraseQuery}
37 <li> {@link PrefixQuery}
38 <li> {@link MultiPhraseQuery}
39 <li> {@link FuzzyQuery}
40 <li> {@link TermRangeQuery}
41 <li> {@link NumericRangeQuery}
42 <li> {@link org.apache.lucene.search.spans.SpanQuery}
44 <p>A parser for queries is contained in:
46 <li>{@link org.apache.lucene.queryParser.QueryParser QueryParser}
49 public abstract class Query implements java.io.Serializable, Cloneable {
50 private float boost = 1.0f; // query boost factor
52 /** Sets the boost for this query clause to <code>b</code>. Documents
53 * matching this clause will (in addition to the normal weightings) have
54 * their score multiplied by <code>b</code>.
56 public void setBoost(float b) { boost = b; }
58 /** Gets the boost for this clause. Documents matching
59 * this clause will (in addition to the normal weightings) have their score
60 * multiplied by <code>b</code>. The boost is 1.0 by default.
62 public float getBoost() { return boost; }
64 /** Prints a query to a string, with <code>field</code> assumed to be the
65 * default field and omitted.
66 * <p>The representation used is one that is supposed to be readable
67 * by {@link org.apache.lucene.queryParser.QueryParser QueryParser}. However,
68 * there are the following limitations:
70 * <li>If the query was created by the parser, the printed
71 * representation may not be exactly what was parsed. For example,
72 * characters that need to be escaped will be represented without
73 * the required backslash.</li>
74 * <li>Some of the more complicated queries (e.g. span queries)
75 * don't have a representation that can be parsed by QueryParser.</li>
78 public abstract String toString(String field);
80 /** Prints a query to a string. */
82 public String toString() {
87 * Expert: Constructs an appropriate Weight implementation for this query.
90 * Only implemented by primitive queries, which re-write to themselves.
92 public Weight createWeight(Searcher searcher) throws IOException {
93 throw new UnsupportedOperationException("Query " + this + " does not implement createWeight");
97 * Expert: Constructs and initializes a Weight for a <b>top-level</b> query.
98 * @deprecated never ever use this method in {@link Weight} implementations.
99 * Subclasses of {@code Query} should use {@link #createWeight}, instead.
102 public final Weight weight(Searcher searcher) throws IOException {
103 return searcher.createNormalizedWeight(this);
107 /** Expert: called to re-write queries into primitive queries. For example,
108 * a PrefixQuery will be rewritten into a BooleanQuery that consists
111 public Query rewrite(IndexReader reader) throws IOException {
116 /** Expert: called when re-writing queries under MultiSearcher.
118 * Create a single query suitable for use by all subsearchers (in 1-1
119 * correspondence with queries). This is an optimization of the OR of
120 * all queries. We handle the common optimization cases of equal
121 * queries and overlapping clauses of boolean OR queries (as generated
122 * by MultiTermQuery.rewrite()).
123 * Be careful overriding this method as queries[0] determines which
124 * method will be called and is not necessarily of the same type as
127 public Query combine(Query[] queries) {
128 HashSet<Query> uniques = new HashSet<Query>();
129 for (int i = 0; i < queries.length; i++) {
130 Query query = queries[i];
131 BooleanClause[] clauses = null;
132 // check if we can split the query into clauses
133 boolean splittable = (query instanceof BooleanQuery);
135 BooleanQuery bq = (BooleanQuery) query;
136 splittable = bq.isCoordDisabled();
137 clauses = bq.getClauses();
138 for (int j = 0; splittable && j < clauses.length; j++) {
139 splittable = (clauses[j].getOccur() == BooleanClause.Occur.SHOULD);
143 for (int j = 0; j < clauses.length; j++) {
144 uniques.add(clauses[j].getQuery());
150 // optimization: if we have just one query, just return it
151 if(uniques.size() == 1){
152 return uniques.iterator().next();
154 BooleanQuery result = new BooleanQuery(true);
155 for (final Query query : uniques)
156 result.add(query, BooleanClause.Occur.SHOULD);
162 * Expert: adds all terms occurring in this query to the terms set. Only
163 * works if this query is in its {@link #rewrite rewritten} form.
165 * @throws UnsupportedOperationException if this query is not yet rewritten
167 public void extractTerms(Set<Term> terms) {
168 // needs to be implemented by query subclasses
169 throw new UnsupportedOperationException();
174 /** Expert: merges the clauses of a set of BooleanQuery's into a single
177 *<p>A utility for use by {@link #combine(Query[])} implementations.
179 public static Query mergeBooleanQueries(BooleanQuery... queries) {
180 HashSet<BooleanClause> allClauses = new HashSet<BooleanClause>();
181 for (BooleanQuery booleanQuery : queries) {
182 for (BooleanClause clause : booleanQuery) {
183 allClauses.add(clause);
187 boolean coordDisabled =
188 queries.length==0? false : queries[0].isCoordDisabled();
189 BooleanQuery result = new BooleanQuery(coordDisabled);
190 for(BooleanClause clause2 : allClauses) {
197 /** Expert: Returns the Similarity implementation to be used for this query.
198 * Subclasses may override this method to specify their own Similarity
199 * implementation, perhaps one that delegates through that of the Searcher.
200 * By default the Searcher's Similarity implementation is returned.
201 * @deprecated Instead of using "runtime" subclassing/delegation, subclass the Weight instead.
204 public Similarity getSimilarity(Searcher searcher) {
205 return searcher.getSimilarity();
208 /** Returns a clone of this query. */
210 public Object clone() {
212 return super.clone();
213 } catch (CloneNotSupportedException e) {
214 throw new RuntimeException("Clone not supported: " + e.getMessage());
219 public int hashCode() {
220 final int prime = 31;
222 result = prime * result + Float.floatToIntBits(boost);
227 public boolean equals(Object obj) {
232 if (getClass() != obj.getClass())
234 Query other = (Query) obj;
235 if (Float.floatToIntBits(boost) != Float.floatToIntBits(other.boost))