add --shared
[pylucene.git] / lucene-java-3.4.0 / lucene / src / java / org / apache / lucene / search / Query.java
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
24 import java.util.Set;
25
26 import org.apache.lucene.index.IndexReader;
27 import org.apache.lucene.index.Term;
28
29 /** The abstract base class for queries.
30     <p>Instantiable subclasses are:
31     <ul>
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}
43     </ul>
44     <p>A parser for queries is contained in:
45     <ul>
46     <li>{@link org.apache.lucene.queryParser.QueryParser QueryParser}
47     </ul>
48 */
49 public abstract class Query implements java.io.Serializable, Cloneable {
50   private float boost = 1.0f;                     // query boost factor
51
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>.
55    */
56   public void setBoost(float b) { boost = b; }
57
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.
61    */
62   public float getBoost() { return boost; }
63
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:
69    * <ul>
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>
76    * </ul>
77    */
78   public abstract String toString(String field);
79
80   /** Prints a query to a string. */
81   @Override
82   public String toString() {
83     return toString("");
84   }
85
86   /**
87    * Expert: Constructs an appropriate Weight implementation for this query.
88    * 
89    * <p>
90    * Only implemented by primitive queries, which re-write to themselves.
91    */
92   public Weight createWeight(Searcher searcher) throws IOException {
93     throw new UnsupportedOperationException("Query " + this + " does not implement createWeight");
94   }
95
96   /**
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.
100    */
101   @Deprecated
102   public final Weight weight(Searcher searcher) throws IOException {
103     return searcher.createNormalizedWeight(this);
104   }
105   
106
107   /** Expert: called to re-write queries into primitive queries. For example,
108    * a PrefixQuery will be rewritten into a BooleanQuery that consists
109    * of TermQuerys.
110    */
111   public Query rewrite(IndexReader reader) throws IOException {
112     return this;
113   }
114   
115
116   /** Expert: called when re-writing queries under MultiSearcher.
117    *
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
125    * the other queries.
126   */
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);
134       if(splittable){
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);
140         }
141       }
142       if(splittable){
143         for (int j = 0; j < clauses.length; j++) {
144           uniques.add(clauses[j].getQuery());
145         }
146       } else {
147         uniques.add(query);
148       }
149     }
150     // optimization: if we have just one query, just return it
151     if(uniques.size() == 1){
152         return uniques.iterator().next();
153     }
154     BooleanQuery result = new BooleanQuery(true);
155     for (final Query query : uniques)
156       result.add(query, BooleanClause.Occur.SHOULD);
157     return result;
158   }
159   
160
161   /**
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.
164    * 
165    * @throws UnsupportedOperationException if this query is not yet rewritten
166    */
167   public void extractTerms(Set<Term> terms) {
168     // needs to be implemented by query subclasses
169     throw new UnsupportedOperationException();
170   }
171   
172
173
174   /** Expert: merges the clauses of a set of BooleanQuery's into a single
175    * BooleanQuery.
176    *
177    *<p>A utility for use by {@link #combine(Query[])} implementations.
178    */
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);
184       }
185     }
186
187     boolean coordDisabled =
188       queries.length==0? false : queries[0].isCoordDisabled();
189     BooleanQuery result = new BooleanQuery(coordDisabled);
190     for(BooleanClause clause2 : allClauses) {
191       result.add(clause2);
192     }
193     return result;
194   }
195   
196
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.
202    */
203   @Deprecated
204   public Similarity getSimilarity(Searcher searcher) {
205     return searcher.getSimilarity();
206   }
207
208   /** Returns a clone of this query. */
209   @Override
210   public Object clone() {
211     try {
212       return super.clone();
213     } catch (CloneNotSupportedException e) {
214       throw new RuntimeException("Clone not supported: " + e.getMessage());
215     }
216   }
217
218   @Override
219   public int hashCode() {
220     final int prime = 31;
221     int result = 1;
222     result = prime * result + Float.floatToIntBits(boost);
223     return result;
224   }
225
226   @Override
227   public boolean equals(Object obj) {
228     if (this == obj)
229       return true;
230     if (obj == null)
231       return false;
232     if (getClass() != obj.getClass())
233       return false;
234     Query other = (Query) obj;
235     if (Float.floatToIntBits(boost) != Float.floatToIntBits(other.boost))
236       return false;
237     return true;
238   }
239 }