1 package org.apache.lucene.search.spans;
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;
21 import java.lang.reflect.Method;
23 import org.apache.lucene.index.IndexReader;
24 import org.apache.lucene.index.Term;
25 import org.apache.lucene.search.MultiTermQuery;
26 import org.apache.lucene.search.Query;
27 import org.apache.lucene.search.TopTermsRewrite;
28 import org.apache.lucene.search.ScoringRewrite;
29 import org.apache.lucene.search.BooleanClause.Occur; // javadocs only
32 * Wraps any {@link MultiTermQuery} as a {@link SpanQuery},
33 * so it can be nested within other SpanQuery classes.
35 * The query is rewritten by default to a {@link SpanOrQuery} containing
36 * the expanded terms, but this can be customized.
41 * WildcardQuery wildcard = new WildcardQuery(new Term("field", "bro?n"));
42 * SpanQuery spanWildcard = new SpanMultiTermQueryWrapper<WildcardQuery>(wildcard);
43 * // do something with spanWildcard, such as use it in a SpanFirstQuery
47 public class SpanMultiTermQueryWrapper<Q extends MultiTermQuery> extends SpanQuery {
48 protected final Q query;
49 private Method getFieldMethod = null, getTermMethod = null;
52 * Create a new SpanMultiTermQueryWrapper.
54 * @param query Query to wrap.
56 * NOTE: This will call {@link MultiTermQuery#setRewriteMethod(MultiTermQuery.RewriteMethod)}
57 * on the wrapped <code>query</code>, changing its rewrite method to a suitable one for spans.
58 * Be sure to not change the rewrite method on the wrapped query afterwards! Doing so will
59 * throw {@link UnsupportedOperationException} on rewriting this query!
60 * In Lucene 3.x, MultiTermQuery allows queries to rewrite to different field names, but SpanQuery
61 * needs a fixed field. The wrapped query must therefore support getField() or getTerm().
62 * @throws IllegalArgumentException if the wrapped query does not provide getField() or getTerm().
64 public SpanMultiTermQueryWrapper(Q query) {
67 MultiTermQuery.RewriteMethod method = query.getRewriteMethod();
68 if (method instanceof TopTermsRewrite) {
69 final int pqsize = ((TopTermsRewrite) method).getSize();
70 setRewriteMethod(new TopTermsSpanBooleanQueryRewrite(pqsize));
72 setRewriteMethod(SCORING_SPAN_QUERY_REWRITE);
75 // In Lucene 3.x, MTQ has no fixed field, we need to get it by reflection.
76 // If the underlying query does not allow to get a constant field, we throw IAE:
78 getFieldMethod = query.getClass().getMethod("getField");
79 } catch (Exception e1) {
81 getTermMethod = query.getClass().getMethod("getTerm");
82 } catch (Exception e2) {
84 getTermMethod = query.getClass().getMethod("getPrefix");
85 } catch (Exception e3) {
86 throw new IllegalArgumentException("SpanMultiTermQueryWrapper can only wrap MultiTermQueries"+
87 " that can return a field name using getField() or getTerm()");
94 * Expert: returns the rewriteMethod
96 public final SpanRewriteMethod getRewriteMethod() {
97 final MultiTermQuery.RewriteMethod m = query.getRewriteMethod();
98 if (!(m instanceof SpanRewriteMethod))
99 throw new UnsupportedOperationException("You can only use SpanMultiTermQueryWrapper with a suitable SpanRewriteMethod.");
100 return (SpanRewriteMethod) m;
104 * Expert: sets the rewrite method. This only makes sense
105 * to be a span rewrite method.
107 public final void setRewriteMethod(SpanRewriteMethod rewriteMethod) {
108 query.setRewriteMethod(rewriteMethod);
112 public Spans getSpans(IndexReader reader) throws IOException {
113 throw new UnsupportedOperationException("Query should have been rewritten");
117 public String getField() {
119 if (getFieldMethod != null) {
120 return (String) getFieldMethod.invoke(query);
122 assert getTermMethod != null;
123 return ((Term) getTermMethod.invoke(query)).field();
125 } catch (Exception e) {
126 throw new RuntimeException("Cannot invoke getField() or getTerm() on wrapped query.", e);
131 public String toString(String field) {
132 StringBuilder builder = new StringBuilder();
133 builder.append("SpanMultiTermQueryWrapper(");
134 builder.append(query.toString(field));
136 return builder.toString();
140 public Query rewrite(IndexReader reader) throws IOException {
141 final Query q = query.rewrite(reader);
142 if (!(q instanceof SpanQuery))
143 throw new UnsupportedOperationException("You can only use SpanMultiTermQueryWrapper with a suitable SpanRewriteMethod.");
148 public int hashCode() {
149 return 31 * query.hashCode();
153 public boolean equals(Object obj) {
154 if (this == obj) return true;
155 if (obj == null) return false;
156 if (getClass() != obj.getClass()) return false;
157 final SpanMultiTermQueryWrapper other = (SpanMultiTermQueryWrapper) obj;
158 return query.equals(other.query);
161 /** Abstract class that defines how the query is rewritten. */
162 public static abstract class SpanRewriteMethod extends MultiTermQuery.RewriteMethod {
164 public abstract SpanQuery rewrite(IndexReader reader, MultiTermQuery query) throws IOException;
168 * A rewrite method that first translates each term into a SpanTermQuery in a
169 * {@link Occur#SHOULD} clause in a BooleanQuery, and keeps the
170 * scores as computed by the query.
172 * @see #setRewriteMethod
174 public final static SpanRewriteMethod SCORING_SPAN_QUERY_REWRITE = new SpanRewriteMethod() {
175 private final ScoringRewrite<SpanOrQuery> delegate = new ScoringRewrite<SpanOrQuery>() {
177 protected SpanOrQuery getTopLevelQuery() {
178 return new SpanOrQuery();
182 protected void addClause(SpanOrQuery topLevel, Term term, float boost) {
183 final SpanTermQuery q = new SpanTermQuery(term);
185 topLevel.addClause(q);
190 public SpanQuery rewrite(IndexReader reader, MultiTermQuery query) throws IOException {
191 return delegate.rewrite(reader, query);
194 // Make sure we are still a singleton even after deserializing
195 protected Object readResolve() {
196 return SCORING_SPAN_QUERY_REWRITE;
201 * A rewrite method that first translates each term into a SpanTermQuery in a
202 * {@link Occur#SHOULD} clause in a BooleanQuery, and keeps the
203 * scores as computed by the query.
206 * This rewrite method only uses the top scoring terms so it will not overflow
207 * the boolean max clause count.
209 * @see #setRewriteMethod
211 public static final class TopTermsSpanBooleanQueryRewrite extends SpanRewriteMethod {
212 private final TopTermsRewrite<SpanOrQuery> delegate;
215 * Create a TopTermsSpanBooleanQueryRewrite for
216 * at most <code>size</code> terms.
218 public TopTermsSpanBooleanQueryRewrite(int size) {
219 delegate = new TopTermsRewrite<SpanOrQuery>(size) {
221 protected int getMaxSize() {
222 return Integer.MAX_VALUE;
226 protected SpanOrQuery getTopLevelQuery() {
227 return new SpanOrQuery();
231 protected void addClause(SpanOrQuery topLevel, Term term, float boost) {
232 final SpanTermQuery q = new SpanTermQuery(term);
234 topLevel.addClause(q);
239 /** return the maximum priority queue size */
240 public int getSize() {
241 return delegate.getSize();
245 public SpanQuery rewrite(IndexReader reader, MultiTermQuery query) throws IOException {
246 return delegate.rewrite(reader, query);
250 public int hashCode() {
251 return 31 * delegate.hashCode();
255 public boolean equals(Object obj) {
256 if (this == obj) return true;
257 if (obj == null) return false;
258 if (getClass() != obj.getClass()) return false;
259 final TopTermsSpanBooleanQueryRewrite other = (TopTermsSpanBooleanQueryRewrite) obj;
260 return delegate.equals(other.delegate);