Skip to content

armgit / solr

Public Imported from GitHub
0

Apache Solr open-source search software

LUCENE-6590: Replace Query.getBoost, setBoost and clone with a new BoostQuery.

Adrien Grand962313b83ba9
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index be646f5b24f..783023158cb 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -73,6 +73,12 @@ New Features
fast, very accurate query to find all indexed points within an
earth-surface shape (Karl Wright, Mike McCandless)
+API Changes
+
+* LUCENE-6590: Query.setBoost(), Query.getBoost() and Query.clone() are gone.
+ In order to apply boosts, you now need to wrap queries in a BoostQuery.
+ (Adrien Grand)
+
Optimizations
* LUCENE-6708: TopFieldCollector does not compute the score several times on the
diff --git a/lucene/MIGRATE.txt b/lucene/MIGRATE.txt
index 13a29c251ff..8e1f770a673 100644
--- a/lucene/MIGRATE.txt
+++ b/lucene/MIGRATE.txt
@@ -63,3 +63,18 @@ AttributeImpl removed the default, reflection-based implementation of
reflectWith(AtrributeReflector). The method was made abstract. If you have
implemented your own attribute, make sure to add the required method sigature.
See the Javadocs for an example.
+
+## Query.setBoost() and Query.clone() are removed (LUCENE-6590)
+
+Query.setBoost has been removed. In order to apply a boost to a Query, you now
+need to wrap it inside a BoostQuery. For instance,
+
+ Query q = ...;
+ float boost = ...;
+ q = new BoostQuery(q, boost);
+
+would be equivalent to the following code with the old setBoost API:
+
+ Query q = ...;
+ float boost = ...;
+ q.setBoost(q.getBoost() * boost);
diff --git a/lucene/core/src/java/org/apache/lucene/search/AutomatonQuery.java b/lucene/core/src/java/org/apache/lucene/search/AutomatonQuery.java
index b35cfb62499..35aecc0ef89 100644
--- a/lucene/core/src/java/org/apache/lucene/search/AutomatonQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/AutomatonQuery.java
@@ -18,13 +18,11 @@ package org.apache.lucene.search;
*/
import java.io.IOException;
-import java.util.Objects;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.util.AttributeSource;
-import org.apache.lucene.util.ToStringUtils;
import org.apache.lucene.util.automaton.Automaton;
import org.apache.lucene.util.automaton.CompiledAutomaton;
import org.apache.lucene.util.automaton.Operations;
@@ -149,7 +147,6 @@ public class AutomatonQuery extends MultiTermQuery {
buffer.append('\n');
buffer.append(automaton.toString());
buffer.append("}");
- buffer.append(ToStringUtils.boost(getBoost()));
return buffer.toString();
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/BlendedTermQuery.java b/lucene/core/src/java/org/apache/lucene/search/BlendedTermQuery.java
index 5fd88564db5..7cedb237943 100644
--- a/lucene/core/src/java/org/apache/lucene/search/BlendedTermQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/BlendedTermQuery.java
@@ -252,8 +252,10 @@ public final class BlendedTermQuery extends Query {
if (i != 0) {
builder.append(" ");
}
- TermQuery termQuery = new TermQuery(terms[i]);
- termQuery.setBoost(boosts[i]);
+ Query termQuery = new TermQuery(terms[i]);
+ if (boosts[i] != 1f) {
+ termQuery = new BoostQuery(termQuery, boosts[i]);
+ }
builder.append(termQuery.toString(field));
}
builder.append(")");
@@ -287,14 +289,14 @@ public final class BlendedTermQuery extends Query {
contexts[i] = adjustFrequencies(contexts[i], df, ttf);
}
- TermQuery[] termQueries = new TermQuery[terms.length];
+ Query[] termQueries = new Query[terms.length];
for (int i = 0; i < terms.length; ++i) {
termQueries[i] = new TermQuery(terms[i], contexts[i]);
- termQueries[i].setBoost(boosts[i]);
+ if (boosts[i] != 1f) {
+ termQueries[i] = new BoostQuery(termQueries[i], boosts[i]);
+ }
}
- Query rewritten = rewriteMethod.rewrite(termQueries);
- rewritten.setBoost(getBoost());
- return rewritten;
+ return rewriteMethod.rewrite(termQueries);
}
private static TermContext adjustFrequencies(TermContext ctx, int artificialDf, long artificialTtf) {
diff --git a/lucene/core/src/java/org/apache/lucene/search/BooleanQuery.java b/lucene/core/src/java/org/apache/lucene/search/BooleanQuery.java
index 5257085fbdf..fcae9fcc506 100644
--- a/lucene/core/src/java/org/apache/lucene/search/BooleanQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/BooleanQuery.java
@@ -28,7 +28,6 @@ import java.util.Objects;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.similarities.Similarity;
-import org.apache.lucene.util.ToStringUtils;
/** A Query that matches documents matching boolean combinations of other
* queries, e.g. {@link TermQuery}s, {@link PhraseQuery}s or other
@@ -203,22 +202,11 @@ public class BooleanQuery extends Query implements Iterable<BooleanClause> {
BooleanClause c = clauses.get(0);
if (!c.isProhibited()) { // just return clause
- Query query = c.getQuery().rewrite(reader); // rewrite first
-
- if (c.isScoring()) {
- if (getBoost() != 1.0f) { // incorporate boost
- if (query == c.getQuery()) { // if rewrite was no-op
- query = query.clone(); // then clone before boost
- }
- // Since the BooleanQuery only has 1 clause, the BooleanQuery will be
- // written out. Therefore the rewritten Query's boost must incorporate both
- // the clause's boost, and the boost of the BooleanQuery itself
- query.setBoost(getBoost() * query.getBoost());
- }
- } else {
- // our single clause is a filter
- query = new ConstantScoreQuery(query);
- query.setBoost(0);
+ Query query = c.getQuery();
+
+ if (c.isScoring() == false) {
+ // our single clause is a filter, so we need to disable scoring
+ query = new BoostQuery(new ConstantScoreQuery(query), 0);
}
return query;
@@ -238,9 +226,7 @@ public class BooleanQuery extends Query implements Iterable<BooleanClause> {
builder.add(rewritten, clause.getOccur());
}
if (actuallyRewritten) {
- BooleanQuery rewritten = builder.build();
- rewritten.setBoost(getBoost());
- return rewritten;
+ return builder.build();
}
return super.rewrite(reader);
}
@@ -249,7 +235,7 @@ public class BooleanQuery extends Query implements Iterable<BooleanClause> {
@Override
public String toString(String field) {
StringBuilder buffer = new StringBuilder();
- boolean needParens= getBoost() != 1.0 || getMinimumNumberShouldMatch() > 0;
+ boolean needParens = getMinimumNumberShouldMatch() > 0;
if (needParens) {
buffer.append("(");
}
@@ -282,10 +268,6 @@ public class BooleanQuery extends Query implements Iterable<BooleanClause> {
buffer.append(getMinimumNumberShouldMatch());
}
- if (getBoost() != 1.0f) {
- buffer.append(ToStringUtils.boost(getBoost()));
- }
-
return buffer.toString();
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/BooleanWeight.java b/lucene/core/src/java/org/apache/lucene/search/BooleanWeight.java
index c619bccde99..813a8804302 100644
--- a/lucene/core/src/java/org/apache/lucene/search/BooleanWeight.java
+++ b/lucene/core/src/java/org/apache/lucene/search/BooleanWeight.java
@@ -43,6 +43,7 @@ final class BooleanWeight extends Weight {
final boolean disableCoord;
final boolean needsScores;
final float coords[];
+ float boost = 1f;
BooleanWeight(BooleanQuery query, IndexSearcher searcher, boolean needsScores, boolean disableCoord) throws IOException {
super(query);
@@ -105,7 +106,7 @@ final class BooleanWeight extends Weight {
i += 1;
}
- sum *= query.getBoost() * query.getBoost(); // boost each sub-weight
+ sum *= boost * boost; // boost each sub-weight
return sum ;
}
@@ -127,11 +128,11 @@ final class BooleanWeight extends Weight {
}
@Override
- public void normalize(float norm, float topLevelBoost) {
- topLevelBoost *= query.getBoost(); // incorporate boost
+ public void normalize(float norm, float boost) {
+ this.boost = boost;
for (Weight w : weights) {
// normalize all clauses, (even if non-scoring in case of side affects)
- w.normalize(norm, topLevelBoost);
+ w.normalize(norm, boost);
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/BoostQuery.java b/lucene/core/src/java/org/apache/lucene/search/BoostQuery.java
new file mode 100644
index 00000000000..eb4e1707fdf
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/search/BoostQuery.java
@@ -0,0 +1,181 @@
+package org.apache.lucene.search;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Objects;
+import java.util.Set;
+
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.Term;
+
+/**
+ * A {@link Query} wrapper that allows to give a boost to the wrapped query.
+ * Boost values that are less than one will give less importance to this
+ * query compared to other ones while values that are greater than one will
+ * give more importance to the scores returned by this query.
+ */
+public final class BoostQuery extends Query {
+
+ /** By default we enclose the wrapped query within parenthesis, but this is
+ * not required for all queries, so we use a whitelist of queries that don't
+ * need parenthesis to have a better toString(). */
+ private static final Set<Class<? extends Query>> NO_PARENS_REQUIRED_QUERIES = Collections.unmodifiableSet(
+ new HashSet<>(Arrays.asList(
+ TermQuery.class,
+ PhraseQuery.class,
+ MultiPhraseQuery.class,
+ ConstantScoreQuery.class,
+ TermRangeQuery.class,
+ NumericRangeQuery.class,
+ PrefixQuery.class,
+ FuzzyQuery.class,
+ WildcardQuery.class,
+ RegexpQuery.class
+ )));
+
+ private final Query query;
+ private final float boost;
+
+ /** Sole constructor: wrap {@code query} in such a way that the produced
+ * scores will be boosted by {@code boost}. */
+ public BoostQuery(Query query, float boost) {
+ this.query = Objects.requireNonNull(query);
+ this.boost = boost;
+ }
+
+ /**
+ * Return the wrapped {@link Query}.
+ */
+ public Query getQuery() {
+ return query;
+ }
+
+ /**
+ * Return the applied boost.
+ */
+ public float getBoost() {
+ return boost;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (super.equals(obj) == false) {
+ return false;
+ }
+ BoostQuery that = (BoostQuery) obj;
+ return query.equals(that.query)
+ && Float.floatToIntBits(boost) == Float.floatToIntBits(that.boost);
+ }
+
+ @Override
+ public int hashCode() {
+ int h = super.hashCode();
+ h = 31 * h + query.hashCode();
+ h = 31 * h + Float.floatToIntBits(boost);
+ return h;
+ }
+
+ @Override
+ public Query rewrite(IndexReader reader) throws IOException {
+ final Query rewritten = query.rewrite(reader);
+
+ if (boost == 1f) {
+ return rewritten;
+ }
+
+ if (rewritten.getClass() == BoostQuery.class) {
+ BoostQuery in = (BoostQuery) rewritten;
+ return new BoostQuery(in.query, boost * in.boost);
+ }
+
+ if (boost == 0f && rewritten.getClass() != ConstantScoreQuery.class) {
+ // so that we pass needScores=false
+ return new BoostQuery(new ConstantScoreQuery(rewritten), 0f);
+ }
+
+ if (query != rewritten) {
+ return new BoostQuery(rewritten, boost);
+ }
+
+ return super.rewrite(reader);
+ }
+
+ @Override
+ public String toString(String field) {
+ boolean needsParens = NO_PARENS_REQUIRED_QUERIES.contains(query.getClass()) == false;
+ StringBuilder builder = new StringBuilder();
+ if (needsParens) {
+ builder.append("(");
+ }
+ builder.append(query.toString(field));
+ if (needsParens) {
+ builder.append(")");
+ }
+ builder.append("^");
+ builder.append(boost);
+ return builder.toString();
+ }
+
+ @Override
+ public Weight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {
+ final Weight weight = query.createWeight(searcher, needsScores);
+ if (needsScores == false) {
+ return weight;
+ }
+ // Apply the query boost, this may impact the return value of getValueForNormalization()
+ weight.normalize(1f, boost);
+ return new Weight(this) {
+
+ @Override
+ public void extractTerms(Set<Term> terms) {
+ weight.extractTerms(terms);
+ }
+
+ @Override
+ public Explanation explain(LeafReaderContext context, int doc) throws IOException {
+ return weight.explain(context, doc);
+ }
+
+ @Override
+ public float getValueForNormalization() throws IOException {
+ return weight.getValueForNormalization();
+ }
+
+ @Override
+ public void normalize(float norm, float boost) {
+ weight.normalize(norm, BoostQuery.this.boost * boost);
+ }
+
+ @Override
+ public Scorer scorer(LeafReaderContext context) throws IOException {
+ return weight.scorer(context);
+ }
+
+ @Override
+ public BulkScorer bulkScorer(LeafReaderContext context) throws IOException {
+ return weight.bulkScorer(context);
+ }
+ };
+ }
+
+}
diff --git a/lucene/core/src/java/org/apache/lucene/search/CachingWrapperQuery.java b/lucene/core/src/java/org/apache/lucene/search/CachingWrapperQuery.java
index f0ae0cb90b0..4dfe1cead6d 100644
--- a/lucene/core/src/java/org/apache/lucene/search/CachingWrapperQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/CachingWrapperQuery.java
@@ -41,7 +41,7 @@ import org.apache.lucene.util.RoaringDocIdSet;
* needed. The purpose is to allow queries to simply care about matching and
* scoring, and then wrap with this class to add caching.
*/
-public class CachingWrapperQuery extends Query implements Accountable {
+public class CachingWrapperQuery extends Query implements Accountable, Cloneable {
private Query query; // not final because of clone
private final QueryCachingPolicy policy;
private final Map<Object,DocIdSet> cache = Collections.synchronizedMap(new WeakHashMap<Object,DocIdSet>());
@@ -62,13 +62,6 @@ public class CachingWrapperQuery extends Query implements Accountable {
this(query, QueryCachingPolicy.CacheOnLargeSegments.DEFAULT);
}
- @Override
- public CachingWrapperQuery clone() {
- final CachingWrapperQuery clone = (CachingWrapperQuery) super.clone();
- clone.query = query.clone();
- return clone;
- }
-
/**
* Gets the contained query.
* @return the contained query.
@@ -77,16 +70,6 @@ public class CachingWrapperQuery extends Query implements Accountable {
return query;
}
- @Override
- public float getBoost() {
- return query.getBoost();
- }
-
- @Override
- public void setBoost(float b) {
- query.setBoost(b);
- }
-
/**
* Default cache implementation: uses {@link RoaringDocIdSet}.
*/
@@ -98,11 +81,16 @@ public class CachingWrapperQuery extends Query implements Accountable {
public Query rewrite(IndexReader reader) throws IOException {
final Query rewritten = query.rewrite(reader);
if (query == rewritten) {
- return this;
+ return super.rewrite(reader);
} else {
- CachingWrapperQuery clone = clone();
- clone.query = rewritten;
- return clone;
+ CachingWrapperQuery clone;
+ try {
+ clone = (CachingWrapperQuery) clone();
+ clone.query = rewritten;
+ return clone;
+ } catch (CloneNotSupportedException e) {
+ throw new AssertionError(e);
+ }
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/ConstantScoreQuery.java b/lucene/core/src/java/org/apache/lucene/search/ConstantScoreQuery.java
index 8c65778f2dc..3f6d51be0a0 100644
--- a/lucene/core/src/java/org/apache/lucene/search/ConstantScoreQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/ConstantScoreQuery.java
@@ -25,18 +25,17 @@ import java.util.Objects;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.util.Bits;
-import org.apache.lucene.util.ToStringUtils;
/**
- * A query that wraps another query and simply returns a constant score equal to the
- * query boost for every document that matches the query.
- * It therefore simply strips of all scores and returns a constant one.
+ * A query that wraps another query and simply returns a constant score equal to
+ * 1 for every document that matches the query.
+ * It therefore simply strips of all scores and always returns 1.
*/
-public class ConstantScoreQuery extends Query {
- protected final Query query;
+public final class ConstantScoreQuery extends Query {
+ private final Query query;
/** Strips off scores from the passed in Query. The hits will get a constant score
- * dependent on the boost factor of this query. */
+ * of 1. */
public ConstantScoreQuery(Query query) {
this.query = Objects.requireNonNull(query, "Query must not be null");
}
@@ -50,21 +49,19 @@ public class ConstantScoreQuery extends Query {
public Query rewrite(IndexReader reader) throws IOException {
Query rewritten = query.rewrite(reader);
- if (rewritten.getClass() == getClass()) {
- if (getBoost() != rewritten.getBoost()) {
- rewritten = rewritten.clone();
- rewritten.setBoost(getBoost());
- }
- return rewritten;
+ if (rewritten != query) {
+ return new ConstantScoreQuery(rewritten);
}
- if (rewritten != query) {
- rewritten = new ConstantScoreQuery(rewritten);
- rewritten.setBoost(this.getBoost());
+ if (rewritten.getClass() == ConstantScoreQuery.class) {
return rewritten;
}
- return this;
+ if (rewritten.getClass() == BoostQuery.class) {
+ return new ConstantScoreQuery(((BoostQuery) rewritten).getQuery());
+ }
+
+ return super.rewrite(reader);
}
/** We return this as our {@link BulkScorer} so that if the CSQ
@@ -161,7 +158,6 @@ public class ConstantScoreQuery extends Query {
return new StringBuilder("ConstantScore(")
.append(query.toString(field))
.append(')')
- .append(ToStringUtils.boost(getBoost()))
.toString();
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/ConstantScoreWeight.java b/lucene/core/src/java/org/apache/lucene/search/ConstantScoreWeight.java
index 6631fd38735..a381627b963 100644
--- a/lucene/core/src/java/org/apache/lucene/search/ConstantScoreWeight.java
+++ b/lucene/core/src/java/org/apache/lucene/search/ConstantScoreWeight.java
@@ -32,13 +32,13 @@ import org.apache.lucene.index.Term;
*/
public abstract class ConstantScoreWeight extends Weight {
+ private float boost;
private float queryNorm;
private float queryWeight;
protected ConstantScoreWeight(Query query) {
super(query);
- queryWeight = getQuery().getBoost();
- queryNorm = 1f;
+ normalize(1f, 1f);
}
@Override
@@ -54,9 +54,20 @@ public abstract class ConstantScoreWeight extends Weight {
}
@Override
- public final void normalize(float norm, float topLevelBoost) {
- queryNorm = norm * topLevelBoost;
- queryWeight *= queryNorm;
+ public void normalize(float norm, float boost) {
+ this.boost = boost;
+ queryNorm = norm;
+ queryWeight = queryNorm * boost;
+ }
+
+ /** Return the normalization factor for this weight. */
+ protected final float queryNorm() {
+ return queryNorm;
+ }
+
+ /** Return the boost for this weight. */
+ protected final float boost() {
+ return boost;
}
/** Return the score produced by this {@link Weight}. */
@@ -65,7 +76,7 @@ public abstract class ConstantScoreWeight extends Weight {
}
@Override
- public final Explanation explain(LeafReaderContext context, int doc) throws IOException {
+ public Explanation explain(LeafReaderContext context, int doc) throws IOException {
final Scorer s = scorer(context);
final boolean exists;
if (s == null) {
@@ -82,7 +93,7 @@ public abstract class ConstantScoreWeight extends Weight {
if (exists) {
return Explanation.match(
queryWeight, getQuery().toString() + ", product of:",
- Explanation.match(getQuery().getBoost(), "boost"), Explanation.match(queryNorm, "queryNorm"));
+ Explanation.match(boost, "boost"), Explanation.match(queryNorm, "queryNorm"));
} else {
return Explanation.noMatch(getQuery().toString() + " doesn't match id " + doc);
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/DisjunctionMaxQuery.java b/lucene/core/src/java/org/apache/lucene/search/DisjunctionMaxQuery.java
index de096cabf50..eeba6c311ab 100644
--- a/lucene/core/src/java/org/apache/lucene/search/DisjunctionMaxQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/DisjunctionMaxQuery.java
@@ -42,7 +42,7 @@ import org.apache.lucene.index.Term;
* include this term in only the best of those multiple fields, without confusing this with the better case of two different terms
* in the multiple fields.
*/
-public class DisjunctionMaxQuery extends Query implements Iterable<Query> {
+public final class DisjunctionMaxQuery extends Query implements Iterable<Query> {
/* The subqueries */
private ArrayList<Query> disjuncts = new ArrayList<>();
@@ -118,6 +118,7 @@ public class DisjunctionMaxQuery extends Query implements Iterable<Query> {
/** The Weights for our subqueries, in 1-1 correspondence with disjuncts */
protected final ArrayList<Weight> weights = new ArrayList<>(); // The Weight's for our subqueries, in 1-1 correspondence with disjuncts
private final boolean needsScores;
+ private float boost;
/** Construct the Weight for this Query searched by searcher. Recursively construct subquery weights. */
public DisjunctionMaxWeight(IndexSearcher searcher, boolean needsScores) throws IOException {
@@ -126,6 +127,7 @@ public class DisjunctionMaxQuery extends Query implements Iterable<Query> {
weights.add(searcher.createWeight(disjunctQuery, needsScores));
}
this.needsScores = needsScores;
+ this.boost = 1f;
}
@Override
@@ -145,16 +147,15 @@ public class DisjunctionMaxQuery extends Query implements Iterable<Query> {
max = Math.max(max, sub);
}
- float boost = getBoost();
return (((sum - max) * tieBreakerMultiplier * tieBreakerMultiplier) + max) * boost * boost;
}
/** Apply the computed normalization factor to our subqueries */
@Override
- public void normalize(float norm, float topLevelBoost) {
- topLevelBoost *= getBoost(); // Incorporate our boost
+ public void normalize(float norm, float boost) {
+ this.boost = boost;
for (Weight wt : weights) {
- wt.normalize(norm, topLevelBoost);
+ wt.normalize(norm, boost);
}
}
@@ -219,34 +220,20 @@ public class DisjunctionMaxQuery extends Query implements Iterable<Query> {
public Query rewrite(IndexReader reader) throws IOException {
int numDisjunctions = disjuncts.size();
if (numDisjunctions == 1) {
- Query singleton = disjuncts.get(0);
- Query result = singleton.rewrite(reader);
- if (getBoost() != 1.0f) {
- if (result == singleton) result = result.clone();
- result.setBoost(getBoost() * result.getBoost());
- }
- return result;
+ return disjuncts.get(0);
}
- DisjunctionMaxQuery clone = null;
- for (int i = 0 ; i < numDisjunctions; i++) {
- Query clause = disjuncts.get(i);
- Query rewrite = clause.rewrite(reader);
- if (rewrite != clause) {
- if (clone == null) clone = this.clone();
- clone.disjuncts.set(i, rewrite);
- }
+ DisjunctionMaxQuery rewritten = new DisjunctionMaxQuery(tieBreakerMultiplier);
+ boolean actuallyRewritten = false;
+ for (Query sub : disjuncts) {
+ Query rewrittenSub = sub.rewrite(reader);
+ actuallyRewritten |= rewrittenSub != sub;
+ rewritten.add(rewrittenSub);
}
- if (clone != null) return clone;
- else return this;
- }
- /** Create a shallow copy of us -- used in rewriting if necessary
- * @return a copy of us (but reuse, don't copy, our subqueries) */
- @Override @SuppressWarnings("unchecked")
- public DisjunctionMaxQuery clone() {
- DisjunctionMaxQuery clone = (DisjunctionMaxQuery)super.clone();
- clone.disjuncts = (ArrayList<Query>) this.disjuncts.clone();
- return clone;
+ if (actuallyRewritten) {
+ return rewritten;
+ }
+ return super.rewrite(reader);
}
/** Prettyprint us.
@@ -273,10 +260,6 @@ public class DisjunctionMaxQuery extends Query implements Iterable<Query> {
buffer.append("~");
buffer.append(tieBreakerMultiplier);
}
- if (getBoost() != 1.0) {
- buffer.append("^");
- buffer.append(getBoost());
- }
return buffer.toString();
}
@@ -298,9 +281,10 @@ public class DisjunctionMaxQuery extends Query implements Iterable<Query> {
*/
@Override
public int hashCode() {
- return Float.floatToIntBits(getBoost())
- + Float.floatToIntBits(tieBreakerMultiplier)
- + disjuncts.hashCode();
+ int h = super.hashCode();
+ h = 31 * h + Float.floatToIntBits(tieBreakerMultiplier);
+ h = 31 * h + disjuncts.hashCode();
+ return h;
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/DocValuesRewriteMethod.java b/lucene/core/src/java/org/apache/lucene/search/DocValuesRewriteMethod.java
index dfb4ba2c69c..62f016b8015 100644
--- a/lucene/core/src/java/org/apache/lucene/search/DocValuesRewriteMethod.java
+++ b/lucene/core/src/java/org/apache/lucene/search/DocValuesRewriteMethod.java
@@ -18,7 +18,6 @@ package org.apache.lucene.search;
*/
import java.io.IOException;
-import java.util.Objects;
import org.apache.lucene.index.DocValues;
import org.apache.lucene.index.IndexReader;
@@ -39,9 +38,7 @@ public final class DocValuesRewriteMethod extends MultiTermQuery.RewriteMethod {
@Override
public Query rewrite(IndexReader reader, MultiTermQuery query) {
- Query result = new ConstantScoreQuery(new MultiTermQueryDocValuesWrapper(query));
- result.setBoost(query.getBoost());
- return result;
+ return new ConstantScoreQuery(new MultiTermQueryDocValuesWrapper(query));
}
static class MultiTermQueryDocValuesWrapper extends Query {
@@ -63,18 +60,16 @@ public final class DocValuesRewriteMethod extends MultiTermQuery.RewriteMethod {
@Override
public final boolean equals(final Object o) {
- if (o==this) return true;
- if (o==null) return false;
- if (this.getClass().equals(o.getClass())) {
- final MultiTermQueryDocValuesWrapper that = (MultiTermQueryDocValuesWrapper) o;
- return this.query.equals(that.query) && this.getBoost() == that.getBoost();
+ if (super.equals(o) == false) {
+ return false;
}
- return false;
+ MultiTermQueryDocValuesWrapper that = (MultiTermQueryDocValuesWrapper) o;
+ return query.equals(that.query);
}
@Override
public final int hashCode() {
- return Objects.hash(getClass(), query, getBoost());
+ return 31 * super.hashCode() + query.hashCode();
}
/** Returns the field name for this query */
diff --git a/lucene/core/src/java/org/apache/lucene/search/FieldValueQuery.java b/lucene/core/src/java/org/apache/lucene/search/FieldValueQuery.java
index e9a06240540..aa21a8f14c4 100644
--- a/lucene/core/src/java/org/apache/lucene/search/FieldValueQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/FieldValueQuery.java
@@ -23,7 +23,6 @@ import java.util.Objects;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.util.Bits;
-import org.apache.lucene.util.ToStringUtils;
/**
* A {@link Query} that matches documents that have a value for a given field
@@ -41,21 +40,21 @@ public final class FieldValueQuery extends Query {
@Override
public boolean equals(Object obj) {
- if (obj instanceof FieldValueQuery == false) {
+ if (super.equals(obj) == false) {
return false;
}
final FieldValueQuery that = (FieldValueQuery) obj;
- return super.equals(obj) && field.equals(that.field);
+ return field.equals(that.field);
}
@Override
public int hashCode() {
- return Objects.hash(getClass(), field, getBoost());
+ return 31 * super.hashCode() + field.hashCode();
}
@Override
public String toString(String field) {
- return "FieldValueQuery [field=" + this.field + "]" + ToStringUtils.boost(getBoost());
+ return "FieldValueQuery [field=" + this.field + "]";
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/search/Filter.java b/lucene/core/src/java/org/apache/lucene/search/Filter.java
index 1c3aa7c1167..105e3bd04f6 100644
--- a/lucene/core/src/java/org/apache/lucene/search/Filter.java
+++ b/lucene/core/src/java/org/apache/lucene/search/Filter.java
@@ -92,7 +92,7 @@ public abstract class Filter extends Query {
}
@Override
- public void normalize(float norm, float topLevelBoost) {}
+ public void normalize(float norm, float boost) {}
@Override
public Explanation explain(LeafReaderContext context, int doc) throws IOException {
diff --git a/lucene/core/src/java/org/apache/lucene/search/FuzzyQuery.java b/lucene/core/src/java/org/apache/lucene/search/FuzzyQuery.java
index 5a15a859e62..57bb4645764 100644
--- a/lucene/core/src/java/org/apache/lucene/search/FuzzyQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/FuzzyQuery.java
@@ -24,7 +24,6 @@ import org.apache.lucene.index.Term;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.util.AttributeSource;
-import org.apache.lucene.util.ToStringUtils;
import org.apache.lucene.util.automaton.LevenshteinAutomata;
/** Implements the fuzzy search query. The similarity measurement
@@ -172,7 +171,6 @@ public class FuzzyQuery extends MultiTermQuery {
buffer.append(term.text());
buffer.append('~');
buffer.append(Integer.toString(maxEdits));
- buffer.append(ToStringUtils.boost(getBoost()));
return buffer.toString();
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/IndexSearcher.java b/lucene/core/src/java/org/apache/lucene/search/IndexSearcher.java
index 197bab33f40..9e3082a1d7d 100644
--- a/lucene/core/src/java/org/apache/lucene/search/IndexSearcher.java
+++ b/lucene/core/src/java/org/apache/lucene/search/IndexSearcher.java
@@ -87,7 +87,7 @@ public class IndexSearcher {
}
@Override
- public SimWeight computeWeight(float queryBoost, CollectionStatistics collectionStats, TermStatistics... termStats) {
+ public SimWeight computeWeight(CollectionStatistics collectionStats, TermStatistics... termStats) {
return new SimWeight() {
@Override
@@ -96,7 +96,7 @@ public class IndexSearcher {
}
@Override
- public void normalize(float queryNorm, float topLevelBoost) {}
+ public void normalize(float queryNorm, float boost) {}
};
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/LRUQueryCache.java b/lucene/core/src/java/org/apache/lucene/search/LRUQueryCache.java
index 8f83726b7e0..4f828f41c63 100644
--- a/lucene/core/src/java/org/apache/lucene/search/LRUQueryCache.java
+++ b/lucene/core/src/java/org/apache/lucene/search/LRUQueryCache.java
@@ -216,7 +216,8 @@ public class LRUQueryCache implements QueryCache, Accountable {
}
synchronized DocIdSet get(Query key, LeafReaderContext context) {
- key = QueryCache.cacheKey(key);
+ assert key instanceof BoostQuery == false;
+ assert key instanceof ConstantScoreQuery == false;
final Object readerKey = context.reader().getCoreCacheKey();
final LeafCache leafCache = cache.get(readerKey);
if (leafCache == null) {
@@ -241,9 +242,8 @@ public class LRUQueryCache implements QueryCache, Accountable {
synchronized void putIfAbsent(Query query, LeafReaderContext context, DocIdSet set) {
// under a lock to make sure that mostRecentlyUsedQueries and cache remain sync'ed
// we don't want to have user-provided queries as keys in our cache since queries are mutable
- query = query.clone();
- query.setBoost(1f);
- assert query == QueryCache.cacheKey(query);
+ assert query instanceof BoostQuery == false;
+ assert query instanceof ConstantScoreQuery == false;
Query singleton = uniqueQueries.putIfAbsent(query, query);
if (singleton == null) {
onQueryCache(singleton, LINKED_HASHTABLE_RAM_BYTES_PER_ENTRY + ramBytesUsed(query));
@@ -306,7 +306,7 @@ public class LRUQueryCache implements QueryCache, Accountable {
* Remove all cache entries for the given query.
*/
public synchronized void clearQuery(Query query) {
- final Query singleton = uniqueQueries.remove(QueryCache.cacheKey(query));
+ final Query singleton = uniqueQueries.remove(query);
if (singleton != null) {
onEviction(singleton);
}
@@ -510,12 +510,14 @@ public class LRUQueryCache implements QueryCache, Accountable {
}
DocIdSet get(Query query) {
- assert query == QueryCache.cacheKey(query);
+ assert query instanceof BoostQuery == false;
+ assert query instanceof ConstantScoreQuery == false;
return cache.get(query);
}
void putIfAbsent(Query query, DocIdSet set) {
- assert query == QueryCache.cacheKey(query);
+ assert query instanceof BoostQuery == false;
+ assert query instanceof ConstantScoreQuery == false;
if (cache.putIfAbsent(query, set) == null) {
// the set was actually put
onDocIdSetCache(HASHTABLE_RAM_BYTES_PER_ENTRY + set.ramBytesUsed());
@@ -523,7 +525,8 @@ public class LRUQueryCache implements QueryCache, Accountable {
}
void remove(Query query) {
- assert query == QueryCache.cacheKey(query);
+ assert query instanceof BoostQuery == false;
+ assert query instanceof ConstantScoreQuery == false;
DocIdSet removed = cache.remove(query);
if (removed != null) {
onDocIdSetEviction(HASHTABLE_RAM_BYTES_PER_ENTRY + removed.ramBytesUsed());
diff --git a/lucene/core/src/java/org/apache/lucene/search/MatchAllDocsQuery.java b/lucene/core/src/java/org/apache/lucene/search/MatchAllDocsQuery.java
index e67a95ea6e5..e2bbfe752b8 100644
--- a/lucene/core/src/java/org/apache/lucene/search/MatchAllDocsQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/MatchAllDocsQuery.java
@@ -21,7 +21,6 @@ import java.io.IOException;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.util.Bits;
-import org.apache.lucene.util.ToStringUtils;
/**
* A query that matches all documents.
@@ -70,9 +69,6 @@ public final class MatchAllDocsQuery extends Query {
@Override
public String toString(String field) {
- StringBuilder buffer = new StringBuilder();
- buffer.append("*:*");
- buffer.append(ToStringUtils.boost(getBoost()));
- return buffer.toString();
+ return "*:*";
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/MatchNoDocsQuery.java b/lucene/core/src/java/org/apache/lucene/search/MatchNoDocsQuery.java
index 93f389b3bd3..000552a7d06 100644
--- a/lucene/core/src/java/org/apache/lucene/search/MatchNoDocsQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/MatchNoDocsQuery.java
@@ -20,7 +20,6 @@ package org.apache.lucene.search;
import java.io.IOException;
import org.apache.lucene.index.IndexReader;
-import org.apache.lucene.util.ToStringUtils;
/**
* A query that matches no documents.
@@ -30,17 +29,11 @@ public class MatchNoDocsQuery extends Query {
@Override
public Query rewrite(IndexReader reader) throws IOException {
// Rewrite to an empty BooleanQuery so no Scorer or Weight is required
- BooleanQuery.Builder builder = new BooleanQuery.Builder();
- Query rewritten = builder.build();
- rewritten.setBoost(getBoost());
- return rewritten;
+ return new BooleanQuery.Builder().build();
}
@Override
public String toString(String field) {
- StringBuilder buffer = new StringBuilder();
- buffer.append("");
- buffer.append(ToStringUtils.boost(getBoost()));
- return buffer.toString();
+ return "";
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java b/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java
index 65556f5287d..f29d86a758d 100644
--- a/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java
@@ -35,7 +35,6 @@ import org.apache.lucene.search.similarities.Similarity;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.PriorityQueue;
-import org.apache.lucene.util.ToStringUtils;
/**
* MultiPhraseQuery is a generalized version of PhraseQuery, with an added
@@ -147,7 +146,7 @@ public class MultiPhraseQuery extends Query {
allTermStats.add(searcher.termStatistics(term, termContext));
}
}
- stats = similarity.computeWeight(getBoost(),
+ stats = similarity.computeWeight(
searcher.collectionStatistics(field),
allTermStats.toArray(new TermStatistics[allTermStats.size()]));
}
@@ -167,8 +166,8 @@ public class MultiPhraseQuery extends Query {
}
@Override
- public void normalize(float queryNorm, float topLevelBoost) {
- stats.normalize(queryNorm, topLevelBoost);
+ public void normalize(float queryNorm, float boost) {
+ stats.normalize(queryNorm, boost);
}
@Override
@@ -251,11 +250,9 @@ public class MultiPhraseQuery extends Query {
}
@Override
- public Query rewrite(IndexReader reader) {
+ public Query rewrite(IndexReader reader) throws IOException {
if (termArrays.isEmpty()) {
- MatchNoDocsQuery rewritten = new MatchNoDocsQuery();
- rewritten.setBoost(getBoost());
- return rewritten;
+ return new MatchNoDocsQuery();
} else if (termArrays.size() == 1) { // optimize one-term case
Term[] terms = termArrays.get(0);
BooleanQuery.Builder builder = new BooleanQuery.Builder();
@@ -263,11 +260,9 @@ public class MultiPhraseQuery extends Query {
for (int i=0; i<terms.length; i++) {
builder.add(new TermQuery(terms[i]), BooleanClause.Occur.SHOULD);
}
- BooleanQuery boq = builder.build();
- boq.setBoost(getBoost());
- return boq;
+ return builder.build();
} else {
- return this;
+ return super.rewrite(reader);
}
}
@@ -322,8 +317,6 @@ public class MultiPhraseQuery extends Query {
buffer.append(slop);
}
- buffer.append(ToStringUtils.boost(getBoost()));
-
return buffer.toString();
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/MultiTermQuery.java b/lucene/core/src/java/org/apache/lucene/search/MultiTermQuery.java
index 368f8383469..79204b787c1 100644
--- a/lucene/core/src/java/org/apache/lucene/search/MultiTermQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/MultiTermQuery.java
@@ -94,9 +94,7 @@ public abstract class MultiTermQuery extends Query {
public static final RewriteMethod CONSTANT_SCORE_REWRITE = new RewriteMethod() {
@Override
public Query rewrite(IndexReader reader, MultiTermQuery query) {
- Query result = new MultiTermQueryConstantScoreWrapper<>(query);
- result.setBoost(query.getBoost());
- return result;
+ return new MultiTermQueryConstantScoreWrapper<>(query);
}
};
@@ -172,8 +170,7 @@ public abstract class MultiTermQuery extends Query {
@Override
protected void addClause(BooleanQuery.Builder topLevel, Term term, int docCount, float boost, TermContext states) {
final TermQuery tq = new TermQuery(term, states);
- tq.setBoost(boost);
- topLevel.add(tq, BooleanClause.Occur.SHOULD);
+ topLevel.add(new BoostQuery(tq, boost), BooleanClause.Occur.SHOULD);
}
}
@@ -271,8 +268,7 @@ public abstract class MultiTermQuery extends Query {
@Override
protected void addClause(BooleanQuery.Builder topLevel, Term term, int docFreq, float boost, TermContext states) {
final Query q = new ConstantScoreQuery(new TermQuery(term, states));
- q.setBoost(boost);
- topLevel.add(q, BooleanClause.Occur.SHOULD);
+ topLevel.add(new BoostQuery(q, boost), BooleanClause.Occur.SHOULD);
}
}
@@ -337,7 +333,6 @@ public abstract class MultiTermQuery extends Query {
public int hashCode() {
final int prime = 31;
int result = 1;
- result = prime * result + Float.floatToIntBits(getBoost());
result = prime * result + rewriteMethod.hashCode();
if (field != null) result = prime * result + field.hashCode();
return result;
diff --git a/lucene/core/src/java/org/apache/lucene/search/MultiTermQueryConstantScoreWrapper.java b/lucene/core/src/java/org/apache/lucene/search/MultiTermQueryConstantScoreWrapper.java
index 11f139970e6..5e0f371cf75 100644
--- a/lucene/core/src/java/org/apache/lucene/search/MultiTermQueryConstantScoreWrapper.java
+++ b/lucene/core/src/java/org/apache/lucene/search/MultiTermQueryConstantScoreWrapper.java
@@ -96,7 +96,7 @@ final class MultiTermQueryConstantScoreWrapper<Q extends MultiTermQuery> extends
return false;
}
final MultiTermQueryConstantScoreWrapper<?> that = (MultiTermQueryConstantScoreWrapper<?>) o;
- return this.query.equals(that.query) && this.getBoost() == that.getBoost();
+ return this.query.equals(that.query);
}
@Override
@@ -157,8 +157,9 @@ final class MultiTermQueryConstantScoreWrapper<Q extends MultiTermQuery> extends
bq.add(new TermQuery(new Term(query.field, t.term), termContext), Occur.SHOULD);
}
Query q = new ConstantScoreQuery(bq.build());
- q.setBoost(score());
- return new WeightOrDocIdSet(searcher.rewrite(q).createWeight(searcher, needsScores));
+ final Weight weight = searcher.rewrite(q).createWeight(searcher, needsScores);
+ weight.normalize(1f, score());
+ return new WeightOrDocIdSet(weight);
}
// Too many terms: go back to the terms we already collected and start building the bit set
diff --git a/lucene/core/src/java/org/apache/lucene/search/NGramPhraseQuery.java b/lucene/core/src/java/org/apache/lucene/search/NGramPhraseQuery.java
index 9e035d8e7a2..7af2d5375d5 100644
--- a/lucene/core/src/java/org/apache/lucene/search/NGramPhraseQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/NGramPhraseQuery.java
@@ -74,9 +74,7 @@ public class NGramPhraseQuery extends Query {
builder.add(terms[i], i);
}
}
- PhraseQuery rewritten = builder.build();
- rewritten.setBoost(phraseQuery.getBoost());
- return rewritten;
+ return builder.build();
}
@Override
@@ -106,16 +104,6 @@ public class NGramPhraseQuery extends Query {
return phraseQuery.getPositions();
}
- @Override
- public float getBoost() {
- return phraseQuery.getBoost();
- }
-
- @Override
- public void setBoost(float b) {
- phraseQuery.setBoost(b);
- }
-
@Override
public String toString(String field) {
return phraseQuery.toString(field);
diff --git a/lucene/core/src/java/org/apache/lucene/search/NumericRangeQuery.java b/lucene/core/src/java/org/apache/lucene/search/NumericRangeQuery.java
index 93dee178c3e..ce413b578f7 100644
--- a/lucene/core/src/java/org/apache/lucene/search/NumericRangeQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/NumericRangeQuery.java
@@ -33,7 +33,6 @@ import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.util.AttributeSource;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.NumericUtils;
-import org.apache.lucene.util.ToStringUtils;
import org.apache.lucene.index.Term; // for javadocs
/**
@@ -324,7 +323,6 @@ public final class NumericRangeQuery<T extends Number> extends MultiTermQuery {
.append(" TO ")
.append((max == null) ? "*" : max.toString())
.append(maxInclusive ? ']' : '}')
- .append(ToStringUtils.boost(getBoost()))
.toString();
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java b/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
index 452a934ff39..599a1ae5b76 100644
--- a/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
@@ -38,7 +38,6 @@ import org.apache.lucene.search.similarities.Similarity;
import org.apache.lucene.search.similarities.Similarity.SimScorer;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.ToStringUtils;
/** A Query that matches documents containing a particular sequence of terms.
* A PhraseQuery is built by QueryParser for input like <code>"new york"</code>.
@@ -265,21 +264,15 @@ public class PhraseQuery extends Query {
@Override
public Query rewrite(IndexReader reader) throws IOException {
if (terms.length == 0) {
- MatchNoDocsQuery q = new MatchNoDocsQuery();
- q.setBoost(getBoost());
- return q;
+ return new MatchNoDocsQuery();
} else if (terms.length == 1) {
- TermQuery tq = new TermQuery(terms[0]);
- tq.setBoost(getBoost());
- return tq;
+ return new TermQuery(terms[0]);
} else if (positions[0] != 0) {
int[] newPositions = new int[positions.length];
for (int i = 0; i < positions.length; ++i) {
newPositions[i] = positions[i] - positions[0];
}
- PhraseQuery rewritten = new PhraseQuery(slop, terms, newPositions);
- rewritten.setBoost(getBoost());
- return rewritten;
+ return new PhraseQuery(slop, terms, newPositions);
} else {
return super.rewrite(reader);
}
@@ -375,7 +368,7 @@ public class PhraseQuery extends Query {
states[i] = TermContext.build(context, term);
termStats[i] = searcher.termStatistics(term, states[i]);
}
- stats = similarity.computeWeight(getBoost(), searcher.collectionStatistics(field), termStats);
+ stats = similarity.computeWeight(searcher.collectionStatistics(field), termStats);
}
@Override
@@ -392,8 +385,8 @@ public class PhraseQuery extends Query {
}
@Override
- public void normalize(float queryNorm, float topLevelBoost) {
- stats.normalize(queryNorm, topLevelBoost);
+ public void normalize(float queryNorm, float boost) {
+ stats.normalize(queryNorm, boost);
}
@Override
@@ -514,8 +507,6 @@ public class PhraseQuery extends Query {
buffer.append(slop);
}
- buffer.append(ToStringUtils.boost(getBoost()));
-
return buffer.toString();
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/PrefixQuery.java b/lucene/core/src/java/org/apache/lucene/search/PrefixQuery.java
index 4303cea1ef2..f618e29210e 100644
--- a/lucene/core/src/java/org/apache/lucene/search/PrefixQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/PrefixQuery.java
@@ -19,7 +19,6 @@ package org.apache.lucene.search;
import org.apache.lucene.index.Term;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.ToStringUtils;
import org.apache.lucene.util.automaton.Automaton;
/** A Query that matches documents containing terms with a specified prefix. A PrefixQuery
@@ -71,7 +70,6 @@ public class PrefixQuery extends AutomatonQuery {
}
buffer.append(term.text());
buffer.append('*');
- buffer.append(ToStringUtils.boost(getBoost()));
return buffer.toString();
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/Query.java b/lucene/core/src/java/org/apache/lucene/search/Query.java
index 2d9ea70aecd..e70ee5015c0 100644
--- a/lucene/core/src/java/org/apache/lucene/search/Query.java
+++ b/lucene/core/src/java/org/apache/lucene/search/Query.java
@@ -41,20 +41,7 @@ import org.apache.lucene.index.IndexReader;
<p>See also the family of {@link org.apache.lucene.search.spans Span Queries}
and additional queries available in the <a href="{@docRoot}/../queries/overview-summary.html">Queries module</a>
*/
-public abstract class Query implements Cloneable {
- private float boost = 1.0f; // query boost factor
-
- /** Sets the boost for this query clause to <code>b</code>. Documents
- * matching this clause will (in addition to the normal weightings) have
- * their score multiplied by <code>b</code>.
- */
- public void setBoost(float b) { boost = b; }
-
- /** Gets the boost for this clause. Documents matching
- * this clause will (in addition to the normal weightings) have their score
- * multiplied by <code>b</code>. The boost is 1.0 by default.
- */
- public float getBoost() { return boost; }
+public abstract class Query {
/** Prints a query to a string, with <code>field</code> assumed to be the
* default field and omitted.
@@ -87,19 +74,9 @@ public abstract class Query implements Cloneable {
return this;
}
- /** Returns a clone of this query. */
- @Override
- public Query clone() {
- try {
- return (Query)super.clone();
- } catch (CloneNotSupportedException e) {
- throw new RuntimeException("Clone not supported: " + e.getMessage());
- }
- }
-
@Override
public int hashCode() {
- return Float.floatToIntBits(getBoost()) ^ getClass().hashCode();
+ return getClass().hashCode();
}
@Override
@@ -110,9 +87,6 @@ public abstract class Query implements Cloneable {
return false;
if (getClass() != obj.getClass())
return false;
- Query other = (Query) obj;
- if (Float.floatToIntBits(boost) != Float.floatToIntBits(other.boost))
- return false;
return true;
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/QueryCache.java b/lucene/core/src/java/org/apache/lucene/search/QueryCache.java
index f452124f443..64461565991 100644
--- a/lucene/core/src/java/org/apache/lucene/search/QueryCache.java
+++ b/lucene/core/src/java/org/apache/lucene/search/QueryCache.java
@@ -25,22 +25,6 @@ package org.apache.lucene.search;
*/
public interface QueryCache {
- /**
- * Return a key for the given query that only takes matching documents into
- * account. Boosts will be ignored.
- * @lucene.internal
- */
- public static Query cacheKey(Query query) {
- if (query.getBoost() == 1f) {
- return query;
- } else {
- Query key = query.clone();
- key.setBoost(1f);
- assert key == cacheKey(key);
- return key;
- }
- }
-
/**
* Return a wrapper around the provided <code>weight</code> that will cache
* matching docs per-segment accordingly to the given <code>policy</code>.
diff --git a/lucene/core/src/java/org/apache/lucene/search/QueryWrapperFilter.java b/lucene/core/src/java/org/apache/lucene/search/QueryWrapperFilter.java
index d08e36cd4bf..533b23f6c00 100644
--- a/lucene/core/src/java/org/apache/lucene/search/QueryWrapperFilter.java
+++ b/lucene/core/src/java/org/apache/lucene/search/QueryWrapperFilter.java
@@ -46,9 +46,7 @@ public class QueryWrapperFilter extends Filter {
@Override
public Query rewrite(IndexReader reader) throws IOException {
- ConstantScoreQuery rewritten = new ConstantScoreQuery(query);
- rewritten.setBoost(0);
- return rewritten;
+ return new BoostQuery(new ConstantScoreQuery(query), 0f);
}
/** returns the inner Query */
diff --git a/lucene/core/src/java/org/apache/lucene/search/RegexpQuery.java b/lucene/core/src/java/org/apache/lucene/search/RegexpQuery.java
index 547a20ca84c..afb7c04c521 100644
--- a/lucene/core/src/java/org/apache/lucene/search/RegexpQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/RegexpQuery.java
@@ -121,7 +121,6 @@ public class RegexpQuery extends AutomatonQuery {
buffer.append('/');
buffer.append(term.text());
buffer.append('/');
- buffer.append(ToStringUtils.boost(getBoost()));
return buffer.toString();
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/ScoringRewrite.java b/lucene/core/src/java/org/apache/lucene/search/ScoringRewrite.java
index b0de0cb8486..d987d64b7f2 100644
--- a/lucene/core/src/java/org/apache/lucene/search/ScoringRewrite.java
+++ b/lucene/core/src/java/org/apache/lucene/search/ScoringRewrite.java
@@ -69,8 +69,7 @@ public abstract class ScoringRewrite<B> extends TermCollectingRewrite<B> {
protected void addClause(BooleanQuery.Builder topLevel, Term term, int docCount,
float boost, TermContext states) {
final TermQuery tq = new TermQuery(term, states);
- tq.setBoost(boost);
- topLevel.add(tq, BooleanClause.Occur.SHOULD);
+ topLevel.add(new BoostQuery(tq, boost), BooleanClause.Occur.SHOULD);
}
@Override
@@ -95,9 +94,7 @@ public abstract class ScoringRewrite<B> extends TermCollectingRewrite<B> {
public Query rewrite(IndexReader reader, MultiTermQuery query) throws IOException {
final Query bq = SCORING_BOOLEAN_REWRITE.rewrite(reader, query);
// strip the scores off
- final Query result = new ConstantScoreQuery(bq);
- result.setBoost(query.getBoost());
- return result;
+ return new ConstantScoreQuery(bq);
}
};
@@ -120,7 +117,7 @@ public abstract class ScoringRewrite<B> extends TermCollectingRewrite<B> {
final int pos = sort[i];
final Term term = new Term(query.getField(), col.terms.get(pos, new BytesRef()));
assert termStates[pos].hasOnlyRealTerms() == false || reader.docFreq(term) == termStates[pos].docFreq();
- addClause(builder, term, termStates[pos].docFreq(), query.getBoost() * boost[pos], termStates[pos]);
+ addClause(builder, term, termStates[pos].docFreq(), boost[pos], termStates[pos]);
}
}
return build(builder);
diff --git a/lucene/core/src/java/org/apache/lucene/search/TermQuery.java b/lucene/core/src/java/org/apache/lucene/search/TermQuery.java
index 2de627bcf60..bf8f3f9edff 100644
--- a/lucene/core/src/java/org/apache/lucene/search/TermQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/TermQuery.java
@@ -32,7 +32,6 @@ import org.apache.lucene.index.TermState;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.similarities.Similarity;
import org.apache.lucene.search.similarities.Similarity.SimScorer;
-import org.apache.lucene.util.ToStringUtils;
/**
* A Query that matches documents containing a term. This may be combined with
@@ -73,7 +72,7 @@ public class TermQuery extends Query {
termStats = new TermStatistics(term.bytes(), docFreq, totalTermFreq);
}
- this.stats = similarity.computeWeight(getBoost(), collectionStats, termStats);
+ this.stats = similarity.computeWeight(collectionStats, termStats);
}
@Override
@@ -92,8 +91,8 @@ public class TermQuery extends Query {
}
@Override
- public void normalize(float queryNorm, float topLevelBoost) {
- stats.normalize(queryNorm, topLevelBoost);
+ public void normalize(float queryNorm, float boost) {
+ stats.normalize(queryNorm, boost);
}
@Override
@@ -207,7 +206,6 @@ public class TermQuery extends Query {
buffer.append(":");
}
buffer.append(term.text());
- buffer.append(ToStringUtils.boost(getBoost()));
return buffer.toString();
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/TermRangeQuery.java b/lucene/core/src/java/org/apache/lucene/search/TermRangeQuery.java
index 24b4ed96520..b61a2348f20 100644
--- a/lucene/core/src/java/org/apache/lucene/search/TermRangeQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/TermRangeQuery.java
@@ -19,7 +19,6 @@ package org.apache.lucene.search;
import org.apache.lucene.index.Term;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.ToStringUtils;
import org.apache.lucene.util.automaton.Automata;
import org.apache.lucene.util.automaton.Automaton;
@@ -121,7 +120,6 @@ public class TermRangeQuery extends AutomatonQuery {
buffer.append(" TO ");
buffer.append(upperTerm != null ? ("*".equals(Term.toString(upperTerm)) ? "\\*" : Term.toString(upperTerm)) : "*");
buffer.append(includeUpper ? ']' : '}');
- buffer.append(ToStringUtils.boost(getBoost()));
return buffer.toString();
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/TopTermsRewrite.java b/lucene/core/src/java/org/apache/lucene/search/TopTermsRewrite.java
index 9fffbc6389b..000b893e37d 100644
--- a/lucene/core/src/java/org/apache/lucene/search/TopTermsRewrite.java
+++ b/lucene/core/src/java/org/apache/lucene/search/TopTermsRewrite.java
@@ -160,7 +160,7 @@ public abstract class TopTermsRewrite<B> extends TermCollectingRewrite<B> {
for (final ScoreTerm st : scoreTerms) {
final Term term = new Term(query.field, st.bytes.toBytesRef());
- addClause(b, term, st.termState.docFreq(), query.getBoost() * st.boost, st.termState); // add to query
+ addClause(b, term, st.termState.docFreq(), st.boost, st.termState); // add to query
}
return build(b);
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/UsageTrackingQueryCachingPolicy.java b/lucene/core/src/java/org/apache/lucene/search/UsageTrackingQueryCachingPolicy.java
index f2f146cebbe..c6bd6878ee6 100644
--- a/lucene/core/src/java/org/apache/lucene/search/UsageTrackingQueryCachingPolicy.java
+++ b/lucene/core/src/java/org/apache/lucene/search/UsageTrackingQueryCachingPolicy.java
@@ -98,9 +98,12 @@ public final class UsageTrackingQueryCachingPolicy implements QueryCachingPolicy
@Override
public void onUse(Query query) {
- // call possible Query clone and hashCode outside of sync block
+ assert query instanceof BoostQuery == false;
+ assert query instanceof ConstantScoreQuery == false;
+
+ // call hashCode outside of sync block
// in case it's somewhat expensive:
- int hashCode = QueryCache.cacheKey(query).hashCode();
+ int hashCode = query.hashCode();
// we only track hash codes to avoid holding references to possible
// large queries; this may cause rare false positives, but at worse
@@ -111,10 +114,12 @@ public final class UsageTrackingQueryCachingPolicy implements QueryCachingPolicy
}
int frequency(Query query) {
-
- // call possible Query clone and hashCode outside of sync block
+ assert query instanceof BoostQuery == false;
+ assert query instanceof ConstantScoreQuery == false;
+
+ // call hashCode outside of sync block
// in case it's somewhat expensive:
- int hashCode = QueryCache.cacheKey(query).hashCode();
+ int hashCode = query.hashCode();
synchronized (this) {
return recentlyUsedFilters.frequency(hashCode);
diff --git a/lucene/core/src/java/org/apache/lucene/search/Weight.java b/lucene/core/src/java/org/apache/lucene/search/Weight.java
index e653a317ef9..1f82e2c748d 100644
--- a/lucene/core/src/java/org/apache/lucene/search/Weight.java
+++ b/lucene/core/src/java/org/apache/lucene/search/Weight.java
@@ -94,8 +94,8 @@ public abstract class Weight {
/** The value for normalization of contained query clauses (e.g. sum of squared weights). */
public abstract float getValueForNormalization() throws IOException;
- /** Assigns the query normalization factor and boost from parent queries to this. */
- public abstract void normalize(float norm, float topLevelBoost);
+ /** Assigns the query normalization factor and boost to this. */
+ public abstract void normalize(float norm, float boost);
/**
* Returns a {@link Scorer} which can iterate in order over all matching
diff --git a/lucene/core/src/java/org/apache/lucene/search/WildcardQuery.java b/lucene/core/src/java/org/apache/lucene/search/WildcardQuery.java
index 82658817735..7a54fa80a75 100644
--- a/lucene/core/src/java/org/apache/lucene/search/WildcardQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/WildcardQuery.java
@@ -21,7 +21,6 @@ import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.index.Term;
-import org.apache.lucene.util.ToStringUtils;
import org.apache.lucene.util.automaton.Automata;
import org.apache.lucene.util.automaton.Automaton;
import org.apache.lucene.util.automaton.Operations;
@@ -121,7 +120,6 @@ public class WildcardQuery extends AutomatonQuery {
buffer.append(":");
}
buffer.append(term.text());
- buffer.append(ToStringUtils.boost(getBoost()));
return buffer.toString();
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/package-info.java b/lucene/core/src/java/org/apache/lucene/search/package-info.java
index 26f2421db15..4fb2b5bc19f 100644
--- a/lucene/core/src/java/org/apache/lucene/search/package-info.java
+++ b/lucene/core/src/java/org/apache/lucene/search/package-info.java
@@ -274,8 +274,8 @@
* <li><b>Index-time boost</b> by calling
* {@link org.apache.lucene.document.Field#setBoost(float) Field.setBoost()} before a document is
* added to the index.</li>
- * <li><b>Query-time boost</b> by setting a boost on a query clause, calling
- * {@link org.apache.lucene.search.Query#setBoost(float) Query.setBoost()}.</li>
+ * <li><b>Query-time boost</b> by applying a boost to a query by wrapping with
+ * {@link org.apache.lucene.search.BoostQuery}.</li>
* </ul>
* <p>Indexing time boosts are pre-processed for storage efficiency and written to
* storage for a field as follows:
@@ -366,7 +366,7 @@
* <li>{@link org.apache.lucene.search.Query#rewrite(org.apache.lucene.index.IndexReader) rewrite(IndexReader reader)} &mdash; Rewrites queries into primitive queries. Primitive queries are:
* {@link org.apache.lucene.search.TermQuery TermQuery},
* {@link org.apache.lucene.search.BooleanQuery BooleanQuery}, <span
- * >and other queries that implement {@link org.apache.lucene.search.Query#createWeight(IndexSearcher,boolean) createWeight(IndexSearcher searcher,boolean)}</span></li>
+ * >and other queries that implement {@link org.apache.lucene.search.Query#createWeight(IndexSearcher,boolean) createWeight(IndexSearcher searcher,boolean,float)}</span></li>
* </ol>
* <a name="weightClass"></a>
* <h3>The Weight Interface</h3>
@@ -389,10 +389,10 @@
* For example, with {@link org.apache.lucene.search.similarities.TFIDFSimilarity Lucene's classic vector-space formula}, this
* is implemented as the sum of squared weights: <code>(idf * boost)<sup>2</sup></code></li>
* <li>
- * {@link org.apache.lucene.search.Weight#normalize(float,float) normalize(float norm, float topLevelBoost)} &mdash;
+ * {@link org.apache.lucene.search.Weight#normalize(float,float) normalize(float norm, float boost)} &mdash;
* Performs query normalization:
* <ul>
- * <li><code>topLevelBoost</code>: A query-boost factor from any wrapping queries that should be multiplied into every
+ * <li><code>boost</code>: A query-boost factor from any wrapping queries that should be multiplied into every
* document's score. For example, a TermQuery that is wrapped within a BooleanQuery with a boost of <code>5</code> would
* receive this value at this time. This allows the TermQuery (the leaf node in this case) to compute this up-front
* a single time (e.g. by multiplying into the IDF), rather than for every document.</li>
diff --git a/lucene/core/src/java/org/apache/lucene/search/payloads/PayloadSpanUtil.java b/lucene/core/src/java/org/apache/lucene/search/payloads/PayloadSpanUtil.java
index ba477289214..56fae7525d6 100644
--- a/lucene/core/src/java/org/apache/lucene/search/payloads/PayloadSpanUtil.java
+++ b/lucene/core/src/java/org/apache/lucene/search/payloads/PayloadSpanUtil.java
@@ -100,11 +100,9 @@ public class PayloadSpanUtil {
}
SpanNearQuery sp = new SpanNearQuery(clauses, slop, inorder);
- sp.setBoost(query.getBoost());
getPayloads(payloads, sp);
} else if (query instanceof TermQuery) {
SpanTermQuery stq = new SpanTermQuery(((TermQuery) query).getTerm());
- stq.setBoost(query.getBoost());
getPayloads(payloads, stq);
} else if (query instanceof SpanQuery) {
getPayloads(payloads, (SpanQuery) query);
@@ -163,7 +161,6 @@ public class PayloadSpanUtil {
SpanNearQuery sp = new SpanNearQuery(clauses, slop + positionGaps,
inorder);
- sp.setBoost(query.getBoost());
getPayloads(payloads, sp);
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/payloads/SpanPayloadCheckQuery.java b/lucene/core/src/java/org/apache/lucene/search/payloads/SpanPayloadCheckQuery.java
index cc75eeb01d4..7775b9e2b02 100644
--- a/lucene/core/src/java/org/apache/lucene/search/payloads/SpanPayloadCheckQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/payloads/SpanPayloadCheckQuery.java
@@ -153,17 +153,9 @@ public class SpanPayloadCheckQuery extends SpanQuery {
buffer.append(';');
}
buffer.append(")");
- buffer.append(ToStringUtils.boost(getBoost()));
return buffer.toString();
}
- @Override
- public SpanPayloadCheckQuery clone() {
- SpanPayloadCheckQuery result = new SpanPayloadCheckQuery((SpanQuery) match.clone(), payloadToMatch);
- result.setBoost(getBoost());
- return result;
- }
-
@Override
public boolean equals(Object o) {
if (! super.equals(o)) {
diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/BM25Similarity.java b/lucene/core/src/java/org/apache/lucene/search/similarities/BM25Similarity.java
index d4031a4e201..058aceb69d2 100644
--- a/lucene/core/src/java/org/apache/lucene/search/similarities/BM25Similarity.java
+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/BM25Similarity.java
@@ -199,7 +199,7 @@ public class BM25Similarity extends Similarity {
}
@Override
- public final SimWeight computeWeight(float queryBoost, CollectionStatistics collectionStats, TermStatistics... termStats) {
+ public final SimWeight computeWeight(CollectionStatistics collectionStats, TermStatistics... termStats) {
Explanation idf = termStats.length == 1 ? idfExplain(collectionStats, termStats[0]) : idfExplain(collectionStats, termStats);
float avgdl = avgFieldLength(collectionStats);
@@ -209,7 +209,7 @@ public class BM25Similarity extends Similarity {
for (int i = 0; i < cache.length; i++) {
cache[i] = k1 * ((1 - b) + b * decodeNormValue((byte)i) / avgdl);
}
- return new BM25Stats(collectionStats.field(), idf, queryBoost, avgdl, cache);
+ return new BM25Stats(collectionStats.field(), idf, avgdl, cache);
}
@Override
@@ -260,10 +260,8 @@ public class BM25Similarity extends Similarity {
private final Explanation idf;
/** The average document length. */
private final float avgdl;
- /** query's inner boost */
- private final float queryBoost;
- /** query's outer boost (only for explain) */
- private float topLevelBoost;
+ /** query boost */
+ private float boost;
/** weight (idf * boost) */
private float weight;
/** field name, for pulling norms */
@@ -271,26 +269,25 @@ public class BM25Similarity extends Similarity {
/** precomputed norm[256] with k1 * ((1 - b) + b * dl / avgdl) */
private final float cache[];
- BM25Stats(String field, Explanation idf, float queryBoost, float avgdl, float cache[]) {
+ BM25Stats(String field, Explanation idf, float avgdl, float cache[]) {
this.field = field;
this.idf = idf;
- this.queryBoost = queryBoost;
this.avgdl = avgdl;
this.cache = cache;
+ normalize(1f, 1f);
}
@Override
public float getValueForNormalization() {
// we return a TF-IDF like normalization to be nice, but we don't actually normalize ourselves.
- final float queryWeight = idf.getValue() * queryBoost;
- return queryWeight * queryWeight;
+ return weight * weight;
}
@Override
- public void normalize(float queryNorm, float topLevelBoost) {
+ public void normalize(float queryNorm, float boost) {
// we don't normalize with queryNorm at all, we just capture the top-level boost
- this.topLevelBoost = topLevelBoost;
- this.weight = idf.getValue() * queryBoost * topLevelBoost;
+ this.boost = boost;
+ this.weight = idf.getValue() * boost;
}
}
@@ -315,7 +312,7 @@ public class BM25Similarity extends Similarity {
}
private Explanation explainScore(int doc, Explanation freq, BM25Stats stats, NumericDocValues norms) {
- Explanation boostExpl = Explanation.match(stats.queryBoost * stats.topLevelBoost, "boost");
+ Explanation boostExpl = Explanation.match(stats.boost, "boost");
List<Explanation> subs = new ArrayList<>();
if (boostExpl.getValue() != 1.0f)
subs.add(boostExpl);
diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/BasicStats.java b/lucene/core/src/java/org/apache/lucene/search/similarities/BasicStats.java
index 848f64c3042..d09c9f1c0d5 100644
--- a/lucene/core/src/java/org/apache/lucene/search/similarities/BasicStats.java
+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/BasicStats.java
@@ -37,21 +37,16 @@ public class BasicStats extends Similarity.SimWeight {
protected long totalTermFreq;
// -------------------------- Boost-related stuff --------------------------
-
- /** Query's inner boost. */
- protected final float queryBoost;
- /** Any outer query's boost. */
- protected float topLevelBoost;
+
/** For most Similarities, the immediate and the top level query boosts are
* not handled differently. Hence, this field is just the product of the
* other two. */
- protected float totalBoost;
+ protected float boost;
- /** Constructor. Sets the query boost. */
- public BasicStats(String field, float queryBoost) {
+ /** Constructor. */
+ public BasicStats(String field) {
this.field = field;
- this.queryBoost = queryBoost;
- this.totalBoost = queryBoost;
+ normalize(1f, 1f);
}
// ------------------------- Getter/setter methods -------------------------
@@ -128,19 +123,17 @@ public class BasicStats extends Similarity.SimWeight {
* {@link #normalize(float, float)}, etc.
*/
protected float rawNormalizationValue() {
- return queryBoost;
+ return boost;
}
- /** No normalization is done. {@code topLevelBoost} is saved in the object,
- * however. */
+ /** No normalization is done. {@code boost} is saved in the object, however. */
@Override
- public void normalize(float queryNorm, float topLevelBoost) {
- this.topLevelBoost = topLevelBoost;
- totalBoost = queryBoost * topLevelBoost;
+ public void normalize(float queryNorm, float boost) {
+ this.boost = boost;
}
/** Returns the total boost. */
- public float getTotalBoost() {
- return totalBoost;
+ public float getBoost() {
+ return boost;
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/DFRSimilarity.java b/lucene/core/src/java/org/apache/lucene/search/similarities/DFRSimilarity.java
index 64e5cd52612..773c1a02530 100644
--- a/lucene/core/src/java/org/apache/lucene/search/similarities/DFRSimilarity.java
+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/DFRSimilarity.java
@@ -109,15 +109,15 @@ public class DFRSimilarity extends SimilarityBase {
@Override
protected float score(BasicStats stats, float freq, float docLen) {
float tfn = normalization.tfn(stats, freq, docLen);
- return stats.getTotalBoost() *
+ return stats.getBoost() *
basicModel.score(stats, tfn) * afterEffect.score(stats, tfn);
}
@Override
protected void explain(List<Explanation> subs,
BasicStats stats, int doc, float freq, float docLen) {
- if (stats.getTotalBoost() != 1.0f) {
- subs.add(Explanation.match(stats.getTotalBoost(), "boost"));
+ if (stats.getBoost() != 1.0f) {
+ subs.add(Explanation.match(stats.getBoost(), "boost"));
}
Explanation normExpl = normalization.explain(stats, freq, docLen);
diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/IBSimilarity.java b/lucene/core/src/java/org/apache/lucene/search/similarities/IBSimilarity.java
index 81abcc5f4a5..46805aa40c4 100644
--- a/lucene/core/src/java/org/apache/lucene/search/similarities/IBSimilarity.java
+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/IBSimilarity.java
@@ -96,7 +96,7 @@ public class IBSimilarity extends SimilarityBase {
@Override
protected float score(BasicStats stats, float freq, float docLen) {
- return stats.getTotalBoost() *
+ return stats.getBoost() *
distribution.score(
stats,
normalization.tfn(stats, freq, docLen),
@@ -106,8 +106,8 @@ public class IBSimilarity extends SimilarityBase {
@Override
protected void explain(
List<Explanation> subs, BasicStats stats, int doc, float freq, float docLen) {
- if (stats.getTotalBoost() != 1.0f) {
- subs.add(Explanation.match(stats.getTotalBoost(), "boost"));
+ if (stats.getBoost() != 1.0f) {
+ subs.add(Explanation.match(stats.getBoost(), "boost"));
}
Explanation normExpl = normalization.explain(stats, freq, docLen);
Explanation lambdaExpl = lambda.explain(stats);
diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/LMDirichletSimilarity.java b/lucene/core/src/java/org/apache/lucene/search/similarities/LMDirichletSimilarity.java
index 7b91191c04e..b1c4563fb0a 100644
--- a/lucene/core/src/java/org/apache/lucene/search/similarities/LMDirichletSimilarity.java
+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/LMDirichletSimilarity.java
@@ -64,7 +64,7 @@ public class LMDirichletSimilarity extends LMSimilarity {
@Override
protected float score(BasicStats stats, float freq, float docLen) {
- float score = stats.getTotalBoost() * (float)(Math.log(1 + freq /
+ float score = stats.getBoost() * (float)(Math.log(1 + freq /
(mu * ((LMStats)stats).getCollectionProbability())) +
Math.log(mu / (docLen + mu)));
return score > 0.0f ? score : 0.0f;
@@ -73,8 +73,8 @@ public class LMDirichletSimilarity extends LMSimilarity {
@Override
protected void explain(List<Explanation> subs, BasicStats stats, int doc,
float freq, float docLen) {
- if (stats.getTotalBoost() != 1.0f) {
- subs.add(Explanation.match(stats.getTotalBoost(), "boost"));
+ if (stats.getBoost() != 1.0f) {
+ subs.add(Explanation.match(stats.getBoost(), "boost"));
}
subs.add(Explanation.match(mu, "mu"));
diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/LMJelinekMercerSimilarity.java b/lucene/core/src/java/org/apache/lucene/search/similarities/LMJelinekMercerSimilarity.java
index e0e2420a665..9f78f931810 100644
--- a/lucene/core/src/java/org/apache/lucene/search/similarities/LMJelinekMercerSimilarity.java
+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/LMJelinekMercerSimilarity.java
@@ -52,7 +52,7 @@ public class LMJelinekMercerSimilarity extends LMSimilarity {
@Override
protected float score(BasicStats stats, float freq, float docLen) {
- return stats.getTotalBoost() *
+ return stats.getBoost() *
(float)Math.log(1 +
((1 - lambda) * freq / docLen) /
(lambda * ((LMStats)stats).getCollectionProbability()));
@@ -61,8 +61,8 @@ public class LMJelinekMercerSimilarity extends LMSimilarity {
@Override
protected void explain(List<Explanation> subs, BasicStats stats, int doc,
float freq, float docLen) {
- if (stats.getTotalBoost() != 1.0f) {
- subs.add(Explanation.match(stats.getTotalBoost(), "boost"));
+ if (stats.getBoost() != 1.0f) {
+ subs.add(Explanation.match(stats.getBoost(), "boost"));
}
subs.add(Explanation.match(lambda, "lambda"));
super.explain(subs, stats, doc, freq, docLen);
diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/LMSimilarity.java b/lucene/core/src/java/org/apache/lucene/search/similarities/LMSimilarity.java
index a29eb7229ba..47b1e70a9b2 100644
--- a/lucene/core/src/java/org/apache/lucene/search/similarities/LMSimilarity.java
+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/LMSimilarity.java
@@ -54,8 +54,8 @@ public abstract class LMSimilarity extends SimilarityBase {
}
@Override
- protected BasicStats newStats(String field, float queryBoost) {
- return new LMStats(field, queryBoost);
+ protected BasicStats newStats(String field) {
+ return new LMStats(field);
}
/**
@@ -108,8 +108,8 @@ public abstract class LMSimilarity extends SimilarityBase {
/**
* Creates LMStats for the provided field and query-time boost
*/
- public LMStats(String field, float queryBoost) {
- super(field, queryBoost);
+ public LMStats(String field) {
+ super(field);
}
/**
diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/MultiSimilarity.java b/lucene/core/src/java/org/apache/lucene/search/similarities/MultiSimilarity.java
index aceeeca9d09..47e1fbf2ae4 100644
--- a/lucene/core/src/java/org/apache/lucene/search/similarities/MultiSimilarity.java
+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/MultiSimilarity.java
@@ -50,10 +50,10 @@ public class MultiSimilarity extends Similarity {
}
@Override
- public SimWeight computeWeight(float queryBoost, CollectionStatistics collectionStats, TermStatistics... termStats) {
+ public SimWeight computeWeight(CollectionStatistics collectionStats, TermStatistics... termStats) {
SimWeight subStats[] = new SimWeight[sims.length];
for (int i = 0; i < subStats.length; i++) {
- subStats[i] = sims[i].computeWeight(queryBoost, collectionStats, termStats);
+ subStats[i] = sims[i].computeWeight(collectionStats, termStats);
}
return new MultiStats(subStats);
}
@@ -120,9 +120,9 @@ public class MultiSimilarity extends Similarity {
}
@Override
- public void normalize(float queryNorm, float topLevelBoost) {
+ public void normalize(float queryNorm, float boost) {
for (SimWeight stat : subStats) {
- stat.normalize(queryNorm, topLevelBoost);
+ stat.normalize(queryNorm, boost);
}
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/PerFieldSimilarityWrapper.java b/lucene/core/src/java/org/apache/lucene/search/similarities/PerFieldSimilarityWrapper.java
index 282be56a734..8da73a82080 100644
--- a/lucene/core/src/java/org/apache/lucene/search/similarities/PerFieldSimilarityWrapper.java
+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/PerFieldSimilarityWrapper.java
@@ -46,10 +46,10 @@ public abstract class PerFieldSimilarityWrapper extends Similarity {
}
@Override
- public final SimWeight computeWeight(float queryBoost, CollectionStatistics collectionStats, TermStatistics... termStats) {
+ public final SimWeight computeWeight(CollectionStatistics collectionStats, TermStatistics... termStats) {
PerFieldSimWeight weight = new PerFieldSimWeight();
weight.delegate = get(collectionStats.field());
- weight.delegateWeight = weight.delegate.computeWeight(queryBoost, collectionStats, termStats);
+ weight.delegateWeight = weight.delegate.computeWeight(collectionStats, termStats);
return weight;
}
@@ -74,8 +74,8 @@ public abstract class PerFieldSimilarityWrapper extends Similarity {
}
@Override
- public void normalize(float queryNorm, float topLevelBoost) {
- delegateWeight.normalize(queryNorm, topLevelBoost);
+ public void normalize(float queryNorm, float boost) {
+ delegateWeight.normalize(queryNorm, boost);
}
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/Similarity.java b/lucene/core/src/java/org/apache/lucene/search/similarities/Similarity.java
index 4acebe9dc08..33764f90b4e 100644
--- a/lucene/core/src/java/org/apache/lucene/search/similarities/Similarity.java
+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/Similarity.java
@@ -78,7 +78,7 @@ import java.util.Collections;
* <a name="querytime">Query time</a>
* At query-time, Queries interact with the Similarity via these steps:
* <ol>
- * <li>The {@link #computeWeight(float, CollectionStatistics, TermStatistics...)} method is called a single time,
+ * <li>The {@link #computeWeight(CollectionStatistics, TermStatistics...)} method is called a single time,
* allowing the implementation to compute any statistics (such as IDF, average document length, etc)
* across <i>the entire collection</i>. The {@link TermStatistics} and {@link CollectionStatistics} passed in
* already contain all of the raw statistics involved, so a Similarity can freely use any combination
@@ -158,16 +158,15 @@ public abstract class Similarity {
/**
* Compute any collection-level weight (e.g. IDF, average document length, etc) needed for scoring a query.
*
- * @param queryBoost the query-time boost.
* @param collectionStats collection-level statistics, such as the number of tokens in the collection.
* @param termStats term-level statistics, such as the document frequency of a term across the collection.
* @return SimWeight object with the information this Similarity needs to score a query.
*/
- public abstract SimWeight computeWeight(float queryBoost, CollectionStatistics collectionStats, TermStatistics... termStats);
+ public abstract SimWeight computeWeight(CollectionStatistics collectionStats, TermStatistics... termStats);
/**
* Creates a new {@link Similarity.SimScorer} to score matching documents from a segment of the inverted index.
- * @param weight collection information from {@link #computeWeight(float, CollectionStatistics, TermStatistics...)}
+ * @param weight collection information from {@link #computeWeight(CollectionStatistics, TermStatistics...)}
* @param context segment of the inverted index to be scored.
* @return SloppySimScorer for scoring documents across <code>context</code>
* @throws IOException if there is a low-level I/O error
@@ -243,8 +242,11 @@ public abstract class Similarity {
* <p>
* NOTE: a Similarity implementation might not use this normalized value at all,
* it's not required. However, it's usually a good idea to at least incorporate
- * the topLevelBoost (e.g. from an outer BooleanQuery) into its score.
+ * the boost into its score.
+ * <p>
+ * NOTE: If this method is called several times, it behaves as if only the
+ * last call was performed.
*/
- public abstract void normalize(float queryNorm, float topLevelBoost);
+ public abstract void normalize(float queryNorm, float boost);
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/SimilarityBase.java b/lucene/core/src/java/org/apache/lucene/search/similarities/SimilarityBase.java
index 423dbbebaf7..370d5072971 100644
--- a/lucene/core/src/java/org/apache/lucene/search/similarities/SimilarityBase.java
+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/SimilarityBase.java
@@ -83,18 +83,18 @@ public abstract class SimilarityBase extends Similarity {
}
@Override
- public final SimWeight computeWeight(float queryBoost, CollectionStatistics collectionStats, TermStatistics... termStats) {
+ public final SimWeight computeWeight(CollectionStatistics collectionStats, TermStatistics... termStats) {
BasicStats stats[] = new BasicStats[termStats.length];
for (int i = 0; i < termStats.length; i++) {
- stats[i] = newStats(collectionStats.field(), queryBoost);
+ stats[i] = newStats(collectionStats.field());
fillBasicStats(stats[i], collectionStats, termStats[i]);
}
return stats.length == 1 ? stats[0] : new MultiSimilarity.MultiStats(stats);
}
/** Factory method to return a custom stats object */
- protected BasicStats newStats(String field, float queryBoost) {
- return new BasicStats(field, queryBoost);
+ protected BasicStats newStats(String field) {
+ return new BasicStats(field);
}
/** Fills all member fields defined in {@code BasicStats} in {@code stats}.
diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/TFIDFSimilarity.java b/lucene/core/src/java/org/apache/lucene/search/similarities/TFIDFSimilarity.java
index 2bf833f50c0..9bbbfdafd76 100644
--- a/lucene/core/src/java/org/apache/lucene/search/similarities/TFIDFSimilarity.java
+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/TFIDFSimilarity.java
@@ -414,7 +414,7 @@ import org.apache.lucene.util.BytesRef;
* <tr>
* <td valign="middle" align="right" rowspan="1">
* {@link org.apache.lucene.search.Weight#getValueForNormalization() sumOfSquaredWeights} &nbsp; = &nbsp;
- * {@link org.apache.lucene.search.Query#getBoost() q.getBoost()} <sup><big>2</big></sup>
+ * {@link org.apache.lucene.search.BoostQuery#getBoost() q.getBoost()} <sup><big>2</big></sup>
* &nbsp;&middot;&nbsp;
* </td>
* <td valign="bottom" align="center" rowspan="1" style="text-align: center">
@@ -443,13 +443,13 @@ import org.apache.lucene.util.BytesRef;
* is a search time boost of term <i>t</i> in the query <i>q</i> as
* specified in the query text
* (see <A HREF="{@docRoot}/../queryparser/org/apache/lucene/queryparser/classic/package-summary.html#Boosting_a_Term">query syntax</A>),
- * or as set by application calls to
- * {@link org.apache.lucene.search.Query#setBoost(float) setBoost()}.
+ * or as set by wrapping with
+ * {@link org.apache.lucene.search.BoostQuery#BoostQuery(org.apache.lucene.search.Query, float) BoostQuery}.
* Notice that there is really no direct API for accessing a boost of one term in a multi term query,
* but rather multi terms are represented in a query as multi
* {@link org.apache.lucene.search.TermQuery TermQuery} objects,
* and so the boost of a term in the query is accessible by calling the sub-query
- * {@link org.apache.lucene.search.Query#getBoost() getBoost()}.
+ * {@link org.apache.lucene.search.BoostQuery#getBoost() getBoost()}.
* <br>&nbsp;<br>
* </li>
*
@@ -684,11 +684,11 @@ public abstract class TFIDFSimilarity extends Similarity {
public abstract float scorePayload(int doc, int start, int end, BytesRef payload);
@Override
- public final SimWeight computeWeight(float queryBoost, CollectionStatistics collectionStats, TermStatistics... termStats) {
+ public final SimWeight computeWeight(CollectionStatistics collectionStats, TermStatistics... termStats) {
final Explanation idf = termStats.length == 1
? idfExplain(collectionStats, termStats[0])
: idfExplain(collectionStats, termStats);
- return new IDFStats(collectionStats.field(), idf, queryBoost);
+ return new IDFStats(collectionStats.field(), idf);
}
@Override
@@ -738,16 +738,15 @@ public abstract class TFIDFSimilarity extends Similarity {
/** The idf and its explanation */
private final Explanation idf;
private float queryNorm;
+ private float boost;
private float queryWeight;
- private final float queryBoost;
private float value;
- public IDFStats(String field, Explanation idf, float queryBoost) {
+ public IDFStats(String field, Explanation idf) {
// TODO: Validate?
this.field = field;
this.idf = idf;
- this.queryBoost = queryBoost;
- this.queryWeight = idf.getValue() * queryBoost; // compute query weight
+ normalize(1f, 1f);
}
@Override
@@ -757,9 +756,10 @@ public abstract class TFIDFSimilarity extends Similarity {
}
@Override
- public void normalize(float queryNorm, float topLevelBoost) {
- this.queryNorm = queryNorm * topLevelBoost;
- queryWeight *= this.queryNorm; // normalize query weight
+ public void normalize(float queryNorm, float boost) {
+ this.boost = boost;
+ this.queryNorm = queryNorm;
+ queryWeight = queryNorm * boost * idf.getValue();
value = queryWeight * idf.getValue(); // idf for document
}
}
@@ -767,8 +767,8 @@ public abstract class TFIDFSimilarity extends Similarity {
private Explanation explainQuery(IDFStats stats) {
List<Explanation> subs = new ArrayList<>();
- Explanation boostExpl = Explanation.match(stats.queryBoost, "boost");
- if (stats.queryBoost != 1.0f)
+ Explanation boostExpl = Explanation.match(stats.boost, "boost");
+ if (stats.boost != 1.0f)
subs.add(boostExpl);
subs.add(stats.idf);
diff --git a/lucene/core/src/java/org/apache/lucene/search/spans/FieldMaskingSpanQuery.java b/lucene/core/src/java/org/apache/lucene/search/spans/FieldMaskingSpanQuery.java
index b5211768559..f91ae0eb491 100644
--- a/lucene/core/src/java/org/apache/lucene/search/spans/FieldMaskingSpanQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/spans/FieldMaskingSpanQuery.java
@@ -20,7 +20,6 @@ package org.apache.lucene.search.spans;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
-import org.apache.lucene.util.ToStringUtils;
import java.io.IOException;
import java.util.Objects;
@@ -68,9 +67,9 @@ import java.util.Objects;
* but with the term statistics of the real field. This may lead to exceptions,
* poor performance, and unexpected scoring behaviour.
*/
-public class FieldMaskingSpanQuery extends SpanQuery {
- private SpanQuery maskedQuery;
- private String field;
+public final class FieldMaskingSpanQuery extends SpanQuery {
+ private final SpanQuery maskedQuery;
+ private final String field;
public FieldMaskingSpanQuery(SpanQuery maskedQuery, String maskedField) {
this.maskedQuery = Objects.requireNonNull(maskedQuery);
@@ -100,15 +99,10 @@ public class FieldMaskingSpanQuery extends SpanQuery {
SpanQuery rewritten = (SpanQuery) maskedQuery.rewrite(reader);
if (rewritten != maskedQuery) {
- clone = (FieldMaskingSpanQuery) this.clone();
- clone.maskedQuery = rewritten;
+ return new FieldMaskingSpanQuery(rewritten, field);
}
- if (clone != null) {
- return clone;
- } else {
- return this;
- }
+ return super.rewrite(reader);
}
@Override
@@ -117,7 +111,6 @@ public class FieldMaskingSpanQuery extends SpanQuery {
buffer.append("mask(");
buffer.append(maskedQuery.toString(field));
buffer.append(")");
- buffer.append(ToStringUtils.boost(getBoost()));
buffer.append(" as ");
buffer.append(this.field);
return buffer.toString();
diff --git a/lucene/core/src/java/org/apache/lucene/search/spans/SpanBoostQuery.java b/lucene/core/src/java/org/apache/lucene/search/spans/SpanBoostQuery.java
new file mode 100644
index 00000000000..c91f815f4bb
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/search/spans/SpanBoostQuery.java
@@ -0,0 +1,189 @@
+package org.apache.lucene.search.spans;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.TreeMap;
+
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.index.TermContext;
+import org.apache.lucene.search.BoostQuery;
+import org.apache.lucene.search.Explanation;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.Scorer;
+
+/**
+ * Counterpart of {@link BoostQuery} for spans.
+ */
+public final class SpanBoostQuery extends SpanQuery {
+
+ /** By default we enclose the wrapped query within parenthesis, but this is
+ * not required for all queries, so we use a whitelist of queries that don't
+ * need parenthesis to have a better toString(). */
+ private static final Set<Class<? extends SpanQuery>> NO_PARENS_REQUIRED_QUERIES = Collections.unmodifiableSet(
+ new HashSet<>(Arrays.asList(
+ SpanTermQuery.class,
+ SpanNearQuery.class,
+ SpanOrQuery.class,
+ SpanFirstQuery.class,
+ SpanContainingQuery.class,
+ SpanContainQuery.class,
+ SpanNotQuery.class,
+ SpanWithinQuery.class
+ )));
+
+ private final SpanQuery query;
+ private final float boost;
+
+ /** Sole constructor: wrap {@code query} in such a way that the produced
+ * scores will be boosted by {@code boost}. */
+ public SpanBoostQuery(SpanQuery query, float boost) {
+ this.query = Objects.requireNonNull(query);
+ this.boost = boost;
+ }
+
+ /**
+ * Return the wrapped {@link SpanQuery}.
+ */
+ public SpanQuery getQuery() {
+ return query;
+ }
+
+ /**
+ * Return the applied boost.
+ */
+ public float getBoost() {
+ return boost;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (super.equals(obj) == false) {
+ return false;
+ }
+ SpanBoostQuery that = (SpanBoostQuery) obj;
+ return query.equals(that.query)
+ && Float.floatToIntBits(boost) == Float.floatToIntBits(that.boost);
+ }
+
+ @Override
+ public int hashCode() {
+ int h = super.hashCode();
+ h = 31 * h + query.hashCode();
+ h = 31 * h + Float.floatToIntBits(boost);
+ return h;
+ }
+
+ @Override
+ public Query rewrite(IndexReader reader) throws IOException {
+ if (boost == 1f) {
+ return query;
+ }
+
+ final SpanQuery rewritten = (SpanQuery) query.rewrite(reader);
+ if (query != rewritten) {
+ return new SpanBoostQuery(rewritten, boost);
+ }
+
+ if (query.getClass() == SpanBoostQuery.class) {
+ SpanBoostQuery in = (SpanBoostQuery) query;
+ return new SpanBoostQuery(in.query, boost * in.boost);
+ }
+
+ return super.rewrite(reader);
+ }
+
+ @Override
+ public String toString(String field) {
+ boolean needsParens = NO_PARENS_REQUIRED_QUERIES.contains(query.getClass()) == false;
+ StringBuilder builder = new StringBuilder();
+ if (needsParens) {
+ builder.append("(");
+ }
+ builder.append(query.toString(field));
+ if (needsParens) {
+ builder.append(")");
+ }
+ builder.append("^");
+ builder.append(boost);
+ return builder.toString();
+ }
+
+ @Override
+ public String getField() {
+ return query.getField();
+ }
+
+ @Override
+ public SpanWeight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {
+ final SpanWeight weight = query.createWeight(searcher, needsScores);
+ if (needsScores == false) {
+ return weight;
+ }
+ Map<Term, TermContext> terms = new TreeMap<>();
+ weight.extractTermContexts(terms);
+ weight.normalize(1f, boost);
+ return new SpanWeight(this, searcher, terms) {
+
+ @Override
+ public void extractTerms(Set<Term> terms) {
+ weight.extractTerms(terms);
+ }
+
+ @Override
+ public Explanation explain(LeafReaderContext context, int doc) throws IOException {
+ return weight.explain(context, doc);
+ }
+
+ @Override
+ public float getValueForNormalization() throws IOException {
+ return weight.getValueForNormalization();
+ }
+
+ @Override
+ public void normalize(float norm, float boost) {
+ weight.normalize(norm, SpanBoostQuery.this.boost * boost);
+ }
+
+ @Override
+ public Spans getSpans(LeafReaderContext ctx, Postings requiredPostings) throws IOException {
+ return weight.getSpans(ctx, requiredPostings);
+ }
+
+ @Override
+ public Scorer scorer(LeafReaderContext context) throws IOException {
+ return weight.scorer(context);
+ }
+
+ @Override
+ public void extractTermContexts(Map<Term,TermContext> contexts) {
+ weight.extractTermContexts(contexts);
+ }
+ };
+ }
+
+}
diff --git a/lucene/core/src/java/org/apache/lucene/search/spans/SpanContainQuery.java b/lucene/core/src/java/org/apache/lucene/search/spans/SpanContainQuery.java
index d1bb8e4fc12..14c1f106f51 100644
--- a/lucene/core/src/java/org/apache/lucene/search/spans/SpanContainQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/spans/SpanContainQuery.java
@@ -35,7 +35,7 @@ abstract class SpanContainQuery extends SpanQuery implements Cloneable {
SpanQuery big;
SpanQuery little;
- SpanContainQuery(SpanQuery big, SpanQuery little, float boost) {
+ SpanContainQuery(SpanQuery big, SpanQuery little) {
this.big = Objects.requireNonNull(big);
this.little = Objects.requireNonNull(little);
Objects.requireNonNull(big.getField());
@@ -43,7 +43,6 @@ abstract class SpanContainQuery extends SpanQuery implements Cloneable {
if (! big.getField().equals(little.getField())) {
throw new IllegalArgumentException("big and little not same field");
}
- this.setBoost(boost);
}
@Override
@@ -104,23 +103,21 @@ abstract class SpanContainQuery extends SpanQuery implements Cloneable {
return buffer.toString();
}
- @Override
- public abstract SpanContainQuery clone();
-
@Override
public Query rewrite(IndexReader reader) throws IOException {
- SpanContainQuery clone = null;
SpanQuery rewrittenBig = (SpanQuery) big.rewrite(reader);
- if (rewrittenBig != big) {
- clone = this.clone();
- clone.big = rewrittenBig;
- }
SpanQuery rewrittenLittle = (SpanQuery) little.rewrite(reader);
- if (rewrittenLittle != little) {
- if (clone == null) clone = this.clone();
- clone.little = rewrittenLittle;
+ if (big != rewrittenBig || little != rewrittenLittle) {
+ try {
+ SpanContainQuery clone = (SpanContainQuery) super.clone();
+ clone.big = rewrittenBig;
+ clone.little = rewrittenLittle;
+ return clone;
+ } catch (CloneNotSupportedException e) {
+ throw new AssertionError(e);
+ }
}
- return (clone != null) ? clone : this;
+ return super.rewrite(reader);
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/search/spans/SpanContainingQuery.java b/lucene/core/src/java/org/apache/lucene/search/spans/SpanContainingQuery.java
index 6c2e0629ba1..7ac20b73e07 100644
--- a/lucene/core/src/java/org/apache/lucene/search/spans/SpanContainingQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/spans/SpanContainingQuery.java
@@ -21,21 +21,20 @@ import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermContext;
import org.apache.lucene.search.IndexSearcher;
-import org.apache.lucene.util.Bits;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
/** Keep matches that contain another Spans. */
-public class SpanContainingQuery extends SpanContainQuery {
+public final class SpanContainingQuery extends SpanContainQuery {
/** Construct a SpanContainingQuery matching spans from <code>big</code>
* that contain at least one spans from <code>little</code>.
* This query has the boost of <code>big</code>.
* <code>big</code> and <code>little</code> must be in the same field.
*/
public SpanContainingQuery(SpanQuery big, SpanQuery little) {
- super(big, little, big.getBoost());
+ super(big, little);
}
@Override
@@ -43,13 +42,6 @@ public class SpanContainingQuery extends SpanContainQuery {
return toString(field, "SpanContaining");
}
- @Override
- public SpanContainingQuery clone() {
- return new SpanContainingQuery(
- (SpanQuery) big.clone(),
- (SpanQuery) little.clone());
- }
-
@Override
public SpanWeight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {
SpanWeight bigWeight = big.createWeight(searcher, false);
diff --git a/lucene/core/src/java/org/apache/lucene/search/spans/SpanFirstQuery.java b/lucene/core/src/java/org/apache/lucene/search/spans/SpanFirstQuery.java
index 4065ba3b9d0..c162c37efed 100644
--- a/lucene/core/src/java/org/apache/lucene/search/spans/SpanFirstQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/spans/SpanFirstQuery.java
@@ -18,7 +18,6 @@ package org.apache.lucene.search.spans;
*/
import org.apache.lucene.search.spans.FilterSpans.AcceptStatus;
-import org.apache.lucene.util.ToStringUtils;
import java.io.IOException;
@@ -54,15 +53,7 @@ public class SpanFirstQuery extends SpanPositionRangeQuery {
buffer.append(", ");
buffer.append(end);
buffer.append(")");
- buffer.append(ToStringUtils.boost(getBoost()));
return buffer.toString();
}
- @Override
- public SpanFirstQuery clone() {
- SpanFirstQuery spanFirstQuery = new SpanFirstQuery((SpanQuery) match.clone(), end);
- spanFirstQuery.setBoost(getBoost());
- return spanFirstQuery;
- }
-
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/spans/SpanMultiTermQueryWrapper.java b/lucene/core/src/java/org/apache/lucene/search/spans/SpanMultiTermQueryWrapper.java
index c4c0b7a1409..9e31e875889 100644
--- a/lucene/core/src/java/org/apache/lucene/search/spans/SpanMultiTermQueryWrapper.java
+++ b/lucene/core/src/java/org/apache/lucene/search/spans/SpanMultiTermQueryWrapper.java
@@ -114,10 +114,6 @@ public class SpanMultiTermQueryWrapper<Q extends MultiTermQuery> extends SpanQue
String queryStr = query.toString(field);
builder.append(queryStr);
builder.append(")");
- if (getBoost() != 1F) {
- builder.append('^');
- builder.append(getBoost());
- }
return builder.toString();
}
@@ -126,7 +122,6 @@ public class SpanMultiTermQueryWrapper<Q extends MultiTermQuery> extends SpanQue
final Query q = query.rewrite(reader);
if (!(q instanceof SpanQuery))
throw new UnsupportedOperationException("You can only use SpanMultiTermQueryWrapper with a suitable SpanRewriteMethod.");
- q.setBoost(q.getBoost() * getBoost()); // multiply boost
return q;
}
@@ -179,7 +174,6 @@ public class SpanMultiTermQueryWrapper<Q extends MultiTermQuery> extends SpanQue
@Override
protected void addClause(SpanOrQuery topLevel, Term term, int docCount, float boost, TermContext states) {
final SpanTermQuery q = new SpanTermQuery(term, states);
- q.setBoost(boost);
topLevel.addClause(q);
}
};
@@ -228,7 +222,6 @@ public class SpanMultiTermQueryWrapper<Q extends MultiTermQuery> extends SpanQue
@Override
protected void addClause(SpanOrQuery topLevel, Term term, int docFreq, float boost, TermContext states) {
final SpanTermQuery q = new SpanTermQuery(term, states);
- q.setBoost(boost);
topLevel.addClause(q);
}
};
diff --git a/lucene/core/src/java/org/apache/lucene/search/spans/SpanNearQuery.java b/lucene/core/src/java/org/apache/lucene/search/spans/SpanNearQuery.java
index cfed917ec0c..7462da2016a 100644
--- a/lucene/core/src/java/org/apache/lucene/search/spans/SpanNearQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/spans/SpanNearQuery.java
@@ -173,7 +173,6 @@ public class SpanNearQuery extends SpanQuery implements Cloneable {
buffer.append(", ");
buffer.append(inOrder);
buffer.append(")");
- buffer.append(ToStringUtils.boost(getBoost()));
return buffer.toString();
}
@@ -235,34 +234,24 @@ public class SpanNearQuery extends SpanQuery implements Cloneable {
@Override
public Query rewrite(IndexReader reader) throws IOException {
- SpanNearQuery clone = null;
+ boolean actuallyRewritten = false;
+ List<SpanQuery> rewrittenClauses = new ArrayList<>();
for (int i = 0 ; i < clauses.size(); i++) {
SpanQuery c = clauses.get(i);
SpanQuery query = (SpanQuery) c.rewrite(reader);
- if (query != c) { // clause rewrote: must clone
- if (clone == null)
- clone = this.clone();
- clone.clauses.set(i,query);
+ actuallyRewritten |= query != c;
+ rewrittenClauses.add(query);
+ }
+ if (actuallyRewritten) {
+ try {
+ SpanNearQuery rewritten = (SpanNearQuery) clone();
+ rewritten.clauses = rewrittenClauses;
+ return rewritten;
+ } catch (CloneNotSupportedException e) {
+ throw new AssertionError(e);
}
}
- if (clone != null) {
- return clone; // some clauses rewrote
- } else {
- return this; // no clauses rewrote
- }
- }
-
- @Override
- public SpanNearQuery clone() {
- int sz = clauses.size();
- SpanQuery[] newClauses = new SpanQuery[sz];
-
- for (int i = 0; i < sz; i++) {
- newClauses[i] = (SpanQuery) clauses.get(i).clone();
- }
- SpanNearQuery spanNearQuery = new SpanNearQuery(newClauses, slop, inOrder);
- spanNearQuery.setBoost(getBoost());
- return spanNearQuery;
+ return super.rewrite(reader);
}
/** Returns true iff <code>o</code> is equal to this. */
diff --git a/lucene/core/src/java/org/apache/lucene/search/spans/SpanNotQuery.java b/lucene/core/src/java/org/apache/lucene/search/spans/SpanNotQuery.java
index 72235e69a62..5a0bcd41a0d 100644
--- a/lucene/core/src/java/org/apache/lucene/search/spans/SpanNotQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/spans/SpanNotQuery.java
@@ -35,7 +35,7 @@ import java.util.Set;
/** Removes matches which overlap with another SpanQuery or which are
* within x tokens before or y tokens after another SpanQuery.
*/
-public class SpanNotQuery extends SpanQuery implements Cloneable {
+public final class SpanNotQuery extends SpanQuery {
private SpanQuery include;
private SpanQuery exclude;
private final int pre;
@@ -89,17 +89,9 @@ public class SpanNotQuery extends SpanQuery implements Cloneable {
buffer.append(", ");
buffer.append(Integer.toString(post));
buffer.append(")");
- buffer.append(ToStringUtils.boost(getBoost()));
return buffer.toString();
}
- @Override
- public SpanNotQuery clone() {
- SpanNotQuery spanNotQuery = new SpanNotQuery((SpanQuery) include.clone(),
- (SpanQuery) exclude.clone(), pre, post);
- spanNotQuery.setBoost(getBoost());
- return spanNotQuery;
- }
@Override
public SpanWeight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {
@@ -200,24 +192,12 @@ public class SpanNotQuery extends SpanQuery implements Cloneable {
@Override
public Query rewrite(IndexReader reader) throws IOException {
- SpanNotQuery clone = null;
-
SpanQuery rewrittenInclude = (SpanQuery) include.rewrite(reader);
- if (rewrittenInclude != include) {
- clone = this.clone();
- clone.include = rewrittenInclude;
- }
SpanQuery rewrittenExclude = (SpanQuery) exclude.rewrite(reader);
- if (rewrittenExclude != exclude) {
- if (clone == null) clone = this.clone();
- clone.exclude = rewrittenExclude;
- }
-
- if (clone != null) {
- return clone; // some clauses rewrote
- } else {
- return this; // no clauses rewrote
+ if (rewrittenInclude != include || rewrittenExclude != exclude) {
+ return new SpanNotQuery(rewrittenInclude, rewrittenExclude);
}
+ return super.rewrite(reader);
}
/** Returns true iff <code>o</code> is equal to this. */
diff --git a/lucene/core/src/java/org/apache/lucene/search/spans/SpanOrQuery.java b/lucene/core/src/java/org/apache/lucene/search/spans/SpanOrQuery.java
index a59467cc30a..df96d71d68d 100644
--- a/lucene/core/src/java/org/apache/lucene/search/spans/SpanOrQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/spans/SpanOrQuery.java
@@ -27,7 +27,6 @@ import org.apache.lucene.search.DisjunctionDISIApproximation;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TwoPhaseIterator;
-import org.apache.lucene.util.ToStringUtils;
import java.io.IOException;
import java.util.ArrayList;
@@ -39,7 +38,7 @@ import java.util.Set;
/** Matches the union of its clauses.
*/
-public class SpanOrQuery extends SpanQuery implements Cloneable {
+public final class SpanOrQuery extends SpanQuery {
private List<SpanQuery> clauses;
private String field;
@@ -71,36 +70,20 @@ public class SpanOrQuery extends SpanQuery implements Cloneable {
@Override
public String getField() { return field; }
- @Override
- public SpanOrQuery clone() {
- int sz = clauses.size();
- SpanQuery[] newClauses = new SpanQuery[sz];
-
- for (int i = 0; i < sz; i++) {
- newClauses[i] = (SpanQuery) clauses.get(i).clone();
- }
- SpanOrQuery soq = new SpanOrQuery(newClauses);
- soq.setBoost(getBoost());
- return soq;
- }
-
@Override
public Query rewrite(IndexReader reader) throws IOException {
- SpanOrQuery clone = null;
+ SpanOrQuery rewritten = new SpanOrQuery();
+ boolean actuallyRewritten = false;
for (int i = 0 ; i < clauses.size(); i++) {
SpanQuery c = clauses.get(i);
SpanQuery query = (SpanQuery) c.rewrite(reader);
- if (query != c) { // clause rewrote: must clone
- if (clone == null)
- clone = this.clone();
- clone.clauses.set(i,query);
- }
+ actuallyRewritten |= query != c;
+ rewritten.addClause(query);
}
- if (clone != null) {
- return clone; // some clauses rewrote
- } else {
- return this; // no clauses rewrote
+ if (actuallyRewritten) {
+ return rewritten;
}
+ return super.rewrite(reader);
}
@Override
@@ -116,7 +99,6 @@ public class SpanOrQuery extends SpanQuery implements Cloneable {
}
}
buffer.append("])");
- buffer.append(ToStringUtils.boost(getBoost()));
return buffer.toString();
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/spans/SpanPositionCheckQuery.java b/lucene/core/src/java/org/apache/lucene/search/spans/SpanPositionCheckQuery.java
index e01fa01d5b3..85622a03cdb 100644
--- a/lucene/core/src/java/org/apache/lucene/search/spans/SpanPositionCheckQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/spans/SpanPositionCheckQuery.java
@@ -106,19 +106,18 @@ public abstract class SpanPositionCheckQuery extends SpanQuery implements Clonea
@Override
public Query rewrite(IndexReader reader) throws IOException {
- SpanPositionCheckQuery clone = null;
-
SpanQuery rewritten = (SpanQuery) match.rewrite(reader);
if (rewritten != match) {
- clone = (SpanPositionCheckQuery) this.clone();
- clone.match = rewritten;
+ try {
+ SpanPositionCheckQuery clone = (SpanPositionCheckQuery) this.clone();
+ clone.match = rewritten;
+ return clone;
+ } catch (CloneNotSupportedException e) {
+ throw new AssertionError(e);
+ }
}
- if (clone != null) {
- return clone; // some clauses rewrote
- } else {
- return this; // no clauses rewrote
- }
+ return super.rewrite(reader);
}
/** Returns true iff <code>o</code> is equal to this. */
diff --git a/lucene/core/src/java/org/apache/lucene/search/spans/SpanPositionRangeQuery.java b/lucene/core/src/java/org/apache/lucene/search/spans/SpanPositionRangeQuery.java
index 2f16fca3ee5..c64253f38f5 100644
--- a/lucene/core/src/java/org/apache/lucene/search/spans/SpanPositionRangeQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/spans/SpanPositionRangeQuery.java
@@ -18,7 +18,6 @@ package org.apache.lucene.search.spans;
import org.apache.lucene.search.spans.FilterSpans.AcceptStatus;
-import org.apache.lucene.util.ToStringUtils;
import java.io.IOException;
@@ -70,17 +69,9 @@ public class SpanPositionRangeQuery extends SpanPositionCheckQuery {
buffer.append(", ").append(start).append(", ");
buffer.append(end);
buffer.append(")");
- buffer.append(ToStringUtils.boost(getBoost()));
return buffer.toString();
}
- @Override
- public SpanPositionRangeQuery clone() {
- SpanPositionRangeQuery result = new SpanPositionRangeQuery((SpanQuery) match.clone(), start, end);
- result.setBoost(getBoost());
- return result;
- }
-
@Override
public boolean equals(Object o) {
if (! super.equals(o)) {
diff --git a/lucene/core/src/java/org/apache/lucene/search/spans/SpanTermQuery.java b/lucene/core/src/java/org/apache/lucene/search/spans/SpanTermQuery.java
index f9aa01f10c2..e2961abd60a 100644
--- a/lucene/core/src/java/org/apache/lucene/search/spans/SpanTermQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/spans/SpanTermQuery.java
@@ -129,7 +129,6 @@ public class SpanTermQuery extends SpanQuery {
buffer.append(term.text());
else
buffer.append(term.toString());
- buffer.append(ToStringUtils.boost(getBoost()));
return buffer.toString();
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/spans/SpanWeight.java b/lucene/core/src/java/org/apache/lucene/search/spans/SpanWeight.java
index 67f47a7330d..4e587df400d 100644
--- a/lucene/core/src/java/org/apache/lucene/search/spans/SpanWeight.java
+++ b/lucene/core/src/java/org/apache/lucene/search/spans/SpanWeight.java
@@ -101,7 +101,7 @@ public abstract class SpanWeight extends Weight {
i++;
}
CollectionStatistics collectionStats = searcher.collectionStatistics(query.getField());
- return searcher.getSimilarity(true).computeWeight(query.getBoost(), collectionStats, termStats);
+ return searcher.getSimilarity(true).computeWeight(collectionStats, termStats);
}
/**
@@ -124,9 +124,9 @@ public abstract class SpanWeight extends Weight {
}
@Override
- public void normalize(float queryNorm, float topLevelBoost) {
+ public void normalize(float queryNorm, float boost) {
if (simWeight != null) {
- simWeight.normalize(queryNorm, topLevelBoost);
+ simWeight.normalize(queryNorm, boost);
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/spans/SpanWithinQuery.java b/lucene/core/src/java/org/apache/lucene/search/spans/SpanWithinQuery.java
index d172c2785b2..01bf937399f 100644
--- a/lucene/core/src/java/org/apache/lucene/search/spans/SpanWithinQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/spans/SpanWithinQuery.java
@@ -27,7 +27,7 @@ import java.util.ArrayList;
import java.util.Map;
/** Keep matches that are contained within another Spans. */
-public class SpanWithinQuery extends SpanContainQuery {
+public final class SpanWithinQuery extends SpanContainQuery {
/** Construct a SpanWithinQuery matching spans from <code>little</code>
* that are inside of <code>big</code>.
@@ -35,7 +35,7 @@ public class SpanWithinQuery extends SpanContainQuery {
* <code>big</code> and <code>little</code> must be in the same field.
*/
public SpanWithinQuery(SpanQuery big, SpanQuery little) {
- super(big, little, little.getBoost());
+ super(big, little);
}
@Override
@@ -43,13 +43,6 @@ public class SpanWithinQuery extends SpanContainQuery {
return toString(field, "SpanWithin");
}
- @Override
- public SpanWithinQuery clone() {
- return new SpanWithinQuery(
- (SpanQuery) big.clone(),
- (SpanQuery) little.clone());
- }
-
@Override
public SpanWeight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {
SpanWeight bigWeight = big.createWeight(searcher, false);
diff --git a/lucene/core/src/java/org/apache/lucene/util/ToStringUtils.java b/lucene/core/src/java/org/apache/lucene/util/ToStringUtils.java
index 3612c953a4b..26853718b81 100644
--- a/lucene/core/src/java/org/apache/lucene/util/ToStringUtils.java
+++ b/lucene/core/src/java/org/apache/lucene/util/ToStringUtils.java
@@ -24,15 +24,6 @@ public final class ToStringUtils {
private ToStringUtils() {} // no instance
- /**
- * for printing boost only if not 1.0
- */
- public static String boost(float boost) {
- if (boost != 1.0f) {
- return "^" + Float.toString(boost);
- } else return "";
- }
-
public static void byteArray(StringBuilder buffer, byte[] bytes) {
for (int i = 0; i < bytes.length; i++) {
buffer.append("b[").append(i).append("]=").append(bytes[i]);
diff --git a/lucene/core/src/test/org/apache/lucene/TestSearch.java b/lucene/core/src/test/org/apache/lucene/TestSearch.java
index a748a7cf9c8..ccf18989128 100644
--- a/lucene/core/src/test/org/apache/lucene/TestSearch.java
+++ b/lucene/core/src/test/org/apache/lucene/TestSearch.java
@@ -34,9 +34,8 @@ import org.apache.lucene.search.*;
public class TestSearch extends LuceneTestCase {
public void testNegativeQueryBoost() throws Exception {
- Query q = new TermQuery(new Term("foo", "bar"));
- q.setBoost(-42f);
- assertEquals(-42f, q.getBoost(), 0.0f);
+ BoostQuery q = new BoostQuery(new TermQuery(new Term("foo", "bar")), -42f);
+ assertEquals(-42f, q.getBoost(), 0f);
Directory directory = newDirectory();
try {
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestCustomNorms.java b/lucene/core/src/test/org/apache/lucene/index/TestCustomNorms.java
index fe324f95935..f1ce650c233 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestCustomNorms.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestCustomNorms.java
@@ -110,7 +110,7 @@ public class TestCustomNorms extends LuceneTestCase {
}
@Override
- public SimWeight computeWeight(float queryBoost, CollectionStatistics collectionStats, TermStatistics... termStats) {
+ public SimWeight computeWeight(CollectionStatistics collectionStats, TermStatistics... termStats) {
throw new UnsupportedOperationException();
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestNorms.java b/lucene/core/src/test/org/apache/lucene/index/TestNorms.java
index f30b5833f30..564284a3eb1 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestNorms.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestNorms.java
@@ -187,7 +187,7 @@ public class TestNorms extends LuceneTestCase {
}
@Override
- public SimWeight computeWeight(float queryBoost, CollectionStatistics collectionStats, TermStatistics... termStats) {
+ public SimWeight computeWeight(CollectionStatistics collectionStats, TermStatistics... termStats) {
throw new UnsupportedOperationException();
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestUniqueTermCount.java b/lucene/core/src/test/org/apache/lucene/index/TestUniqueTermCount.java
index eab5f1130fd..2cb9332c66e 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestUniqueTermCount.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestUniqueTermCount.java
@@ -105,7 +105,7 @@ public class TestUniqueTermCount extends LuceneTestCase {
}
@Override
- public SimWeight computeWeight(float queryBoost, CollectionStatistics collectionStats, TermStatistics... termStats) {
+ public SimWeight computeWeight(CollectionStatistics collectionStats, TermStatistics... termStats) {
throw new UnsupportedOperationException();
}
diff --git a/lucene/core/src/test/org/apache/lucene/search/JustCompileSearch.java b/lucene/core/src/test/org/apache/lucene/search/JustCompileSearch.java
index 6387d25f5d4..f6ccdc258a6 100644
--- a/lucene/core/src/test/org/apache/lucene/search/JustCompileSearch.java
+++ b/lucene/core/src/test/org/apache/lucene/search/JustCompileSearch.java
@@ -224,7 +224,7 @@ final class JustCompileSearch {
static final class JustCompileSimilarity extends Similarity {
@Override
- public SimWeight computeWeight(float queryBoost, CollectionStatistics collectionStats, TermStatistics... termStats) {
+ public SimWeight computeWeight(CollectionStatistics collectionStats, TermStatistics... termStats) {
throw new UnsupportedOperationException(UNSUPPORTED_MSG);
}
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestBooleanCoord.java b/lucene/core/src/test/org/apache/lucene/search/TestBooleanCoord.java
index dcb1bc72f89..3c58355f29c 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestBooleanCoord.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestBooleanCoord.java
@@ -84,7 +84,7 @@ public class TestBooleanCoord extends LuceneTestCase {
}
@Override
- public SimWeight computeWeight(float queryBoost, CollectionStatistics collectionStats, TermStatistics... termStats) {
+ public SimWeight computeWeight(CollectionStatistics collectionStats, TermStatistics... termStats) {
return new SimWeight() {
@Override
public float getValueForNormalization() {
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestBooleanQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestBooleanQuery.java
index 43c0f4894c3..25c83377e28 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestBooleanQuery.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestBooleanQuery.java
@@ -102,8 +102,7 @@ public class TestBooleanQuery extends LuceneTestCase {
// LUCENE-2617: make sure that a term not in the index still contributes to the score via coord factor
float score = s.search(q.build(), 10).getMaxScore();
- Query subQuery = new TermQuery(new Term("field", "not_in_index"));
- subQuery.setBoost(0);
+ Query subQuery = new BoostQuery(new TermQuery(new Term("field", "not_in_index")), 0f);
q.add(subQuery, BooleanClause.Occur.SHOULD);
float score2 = s.search(q.build(), 10).getMaxScore();
assertEquals(score*.5F, score2, 1e-6);
@@ -114,14 +113,12 @@ public class TestBooleanQuery extends LuceneTestCase {
qq.add(clause);
}
PhraseQuery phrase = new PhraseQuery("field", "not_in_index", "another_not_in_index");
- phrase.setBoost(0);
- qq.add(phrase, BooleanClause.Occur.SHOULD);
+ qq.add(new BoostQuery(phrase, 0f), BooleanClause.Occur.SHOULD);
score2 = s.search(qq.build(), 10).getMaxScore();
assertEquals(score*(1/3F), score2, 1e-6);
// now test BooleanScorer2
- subQuery = new TermQuery(new Term("field", "b"));
- subQuery.setBoost(0);
+ subQuery = new BoostQuery(new TermQuery(new Term("field", "b")), 0f);
q.add(subQuery, BooleanClause.Occur.MUST);
score2 = s.search(q.build(), 10).getMaxScore();
assertEquals(score*(2/3F), score2, 1e-6);
@@ -334,7 +331,6 @@ public class TestBooleanQuery extends LuceneTestCase {
}
public void testOneClauseRewriteOptimization() throws Exception {
- final float BOOST = 3.5F;
final String FIELD = "content";
final String VALUE = "foo";
@@ -343,29 +339,20 @@ public class TestBooleanQuery extends LuceneTestCase {
IndexReader r = DirectoryReader.open(dir);
TermQuery expected = new TermQuery(new Term(FIELD, VALUE));
- expected.setBoost(BOOST);
final int numLayers = atLeast(3);
- boolean needBoost = true;
Query actual = new TermQuery(new Term(FIELD, VALUE));
for (int i = 0; i < numLayers; i++) {
- if (needBoost && 0 == TestUtil.nextInt(random(),0,numLayers)) {
- needBoost = false;
- actual.setBoost(BOOST);
- }
BooleanQuery.Builder bq = new BooleanQuery.Builder();
bq.add(actual, random().nextBoolean()
? BooleanClause.Occur.SHOULD : BooleanClause.Occur.MUST);
actual = bq.build();
}
- if (needBoost) {
- actual.setBoost(BOOST);
- }
assertEquals(numLayers + ": " + actual.toString(),
- expected, actual.rewrite(r));
+ expected, new IndexSearcher(r).rewrite(actual));
r.close();
dir.close();
@@ -462,7 +449,6 @@ public class TestBooleanQuery extends LuceneTestCase {
}
bq2Builder.setMinimumNumberShouldMatch(bq.getMinimumNumberShouldMatch());
BooleanQuery bq2 = bq2Builder.build();
- bq2.setBoost(bq.getBoost());
final AtomicBoolean matched = new AtomicBoolean();
searcher.search(bq, new SimpleCollector() {
@@ -515,7 +501,6 @@ public class TestBooleanQuery extends LuceneTestCase {
BooleanQuery.Builder qBuilder = new BooleanQuery.Builder();
BooleanQuery q = qBuilder.build();
- q.setBoost(random().nextFloat());
qBuilder.add(new TermQuery(new Term("field", "a")), Occur.FILTER);
// With a single clause, we will rewrite to the underlying
@@ -526,7 +511,6 @@ public class TestBooleanQuery extends LuceneTestCase {
// Make sure it returns null scores
qBuilder.add(new TermQuery(new Term("field", "b")), Occur.FILTER);
q = qBuilder.build();
- q.setBoost(random().nextFloat());
assertSameScoresWithoutFilters(searcher, q);
// Now with a scoring clause, we need to make sure that
@@ -534,7 +518,6 @@ public class TestBooleanQuery extends LuceneTestCase {
// query
qBuilder.add(new TermQuery(new Term("field", "c")), Occur.SHOULD);
q = qBuilder.build();
- q.setBoost(random().nextFloat());
assertSameScoresWithoutFilters(searcher, q);
// FILTER and empty SHOULD
@@ -542,7 +525,6 @@ public class TestBooleanQuery extends LuceneTestCase {
qBuilder.add(new TermQuery(new Term("field", "a")), Occur.FILTER);
qBuilder.add(new TermQuery(new Term("field", "e")), Occur.SHOULD);
q = qBuilder.build();
- q.setBoost(random().nextFloat());
assertSameScoresWithoutFilters(searcher, q);
// mix of FILTER and MUST
@@ -550,7 +532,6 @@ public class TestBooleanQuery extends LuceneTestCase {
qBuilder.add(new TermQuery(new Term("field", "a")), Occur.FILTER);
qBuilder.add(new TermQuery(new Term("field", "d")), Occur.MUST);
q = qBuilder.build();
- q.setBoost(random().nextFloat());
assertSameScoresWithoutFilters(searcher, q);
// FILTER + minShouldMatch
@@ -560,7 +541,6 @@ public class TestBooleanQuery extends LuceneTestCase {
qBuilder.add(new TermQuery(new Term("field", "d")), Occur.SHOULD);
qBuilder.setMinimumNumberShouldMatch(1);
q = qBuilder.build();
- q.setBoost(random().nextFloat());
assertSameScoresWithoutFilters(searcher, q);
reader.close();
@@ -585,8 +565,8 @@ public class TestBooleanQuery extends LuceneTestCase {
// Single clauses rewrite to a term query
final Query rewritten1 = query1.build().rewrite(reader);
- assertTrue(rewritten1 instanceof ConstantScoreQuery);
- assertEquals(0f, rewritten1.getBoost(), 0f);
+ assertTrue(rewritten1 instanceof BoostQuery);
+ assertEquals(0f, ((BoostQuery) rewritten1).getBoost(), 0f);
// When there are two clauses, we cannot rewrite, but if one of them creates
// a null scorer we will end up with a single filter scorer and will need to
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestBoostQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestBoostQuery.java
new file mode 100644
index 00000000000..a6a470d43ff
--- /dev/null
+++ b/lucene/core/src/test/org/apache/lucene/search/TestBoostQuery.java
@@ -0,0 +1,70 @@
+package org.apache.lucene.search;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.io.IOException;
+
+import org.apache.lucene.index.MultiReader;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.search.BooleanClause.Occur;
+import org.apache.lucene.util.LuceneTestCase;
+
+public class TestBoostQuery extends LuceneTestCase {
+
+ public void testEquals() {
+ final float boost = random().nextFloat() * 3 - 1;
+ BoostQuery q1 = new BoostQuery(new MatchAllDocsQuery(), boost);
+ BoostQuery q2 = new BoostQuery(new MatchAllDocsQuery(), boost);
+ assertEquals(q1, q2);
+ assertEquals(q1.getBoost(), q2.getBoost(), 0f);
+
+ float boost2 = boost;
+ while (boost == boost2) {
+ boost2 = random().nextFloat() * 3 - 1;
+ }
+ BoostQuery q3 = new BoostQuery(new MatchAllDocsQuery(), boost2);
+ assertFalse(q1.equals(q3));
+ assertFalse(q1.hashCode() == q3.hashCode());
+ }
+
+ public void testToString() {
+ assertEquals("foo:bar^2.0", new BoostQuery(new TermQuery(new Term("foo", "bar")), 2).toString());
+ BooleanQuery bq = new BooleanQuery.Builder()
+ .add(new TermQuery(new Term("foo", "bar")), Occur.SHOULD)
+ .add(new TermQuery(new Term("foo", "baz")), Occur.SHOULD)
+ .build();
+ assertEquals("(foo:bar foo:baz)^2.0", new BoostQuery(bq, 2).toString());
+ }
+
+ public void testRewrite() throws IOException {
+ IndexSearcher searcher = new IndexSearcher(new MultiReader());
+
+ // inner queries are rewritten
+ Query q = new BoostQuery(new MatchNoDocsQuery(), 2);
+ assertEquals(new BoostQuery(new BooleanQuery.Builder().build(), 2), searcher.rewrite(q));
+
+ // boosts are merged
+ q = new BoostQuery(new BoostQuery(new MatchAllDocsQuery(), 3), 2);
+ assertEquals(new BoostQuery(new MatchAllDocsQuery(), 6), searcher.rewrite(q));
+
+ // scores are not computed when the boost is 0
+ q = new BoostQuery(new MatchAllDocsQuery(), 0);
+ assertEquals(new BoostQuery(new ConstantScoreQuery(new MatchAllDocsQuery()), 0), searcher.rewrite(q));
+ }
+
+}
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestComplexExplanations.java b/lucene/core/src/test/org/apache/lucene/search/TestComplexExplanations.java
index 6a946a80e1a..f278d2d37f2 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestComplexExplanations.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestComplexExplanations.java
@@ -73,12 +73,10 @@ public class TestComplexExplanations extends BaseExplanationTestCase {
.add(new TermQuery(new Term(FIELD, "xx")), Occur.MUST)
.add(matchTheseItems(new int[] {1,3}), Occur.FILTER)
.build();
- t.setBoost(1000);
- q.add(t, Occur.SHOULD);
+ q.add(new BoostQuery(t, 1000), Occur.SHOULD);
t = new ConstantScoreQuery(matchTheseItems(new int[] {0,2}));
- t.setBoost(30);
- q.add(t, Occur.SHOULD);
+ q.add(new BoostQuery(t, 30), Occur.SHOULD);
DisjunctionMaxQuery dm = new DisjunctionMaxQuery(0.2f);
dm.add(snear(st("w2"),
@@ -135,12 +133,10 @@ public class TestComplexExplanations extends BaseExplanationTestCase {
.add(new TermQuery(new Term(FIELD, "xx")), Occur.MUST)
.add(matchTheseItems(new int[] {1,3}), Occur.FILTER)
.build();
- t.setBoost(1000);
- q.add(t, Occur.SHOULD);
+ q.add(new BoostQuery(t, 1000), Occur.SHOULD);
t = new ConstantScoreQuery(matchTheseItems(new int[] {0,2}));
- t.setBoost(-20.0f);
- q.add(t, Occur.SHOULD);
+ q.add(new BoostQuery(t, -20), Occur.SHOULD);
DisjunctionMaxQuery dm = new DisjunctionMaxQuery(0.2f);
dm.add(snear(st("w2"),
@@ -175,9 +171,8 @@ public class TestComplexExplanations extends BaseExplanationTestCase {
builder.add(snear("w2","w3",1,true), Occur.SHOULD);
builder.add(snear("w1","w3",3,true), Occur.SHOULD);
BooleanQuery b = builder.build();
- b.setBoost(0.0f);
- q.add(b, Occur.SHOULD);
+ q.add(new BoostQuery(b, 0), Occur.SHOULD);
qtest(q.build(), new int[] { 0,1,2 });
}
@@ -193,21 +188,18 @@ public class TestComplexExplanations extends BaseExplanationTestCase {
public void testT3() throws Exception {
TermQuery query = new TermQuery(new Term(FIELD, "w1"));
- query.setBoost(0);
- bqtest(query, new int[] { 0,1,2,3 });
+ bqtest(new BoostQuery(query, 0), new int[] { 0,1,2,3 });
}
public void testMA3() throws Exception {
Query q=new MatchAllDocsQuery();
- q.setBoost(0);
- bqtest(q, new int[] { 0,1,2,3 });
+ bqtest(new BoostQuery(q, 0), new int[] { 0,1,2,3 });
}
public void testFQ5() throws Exception {
TermQuery query = new TermQuery(new Term(FIELD, "xx"));
- query.setBoost(0);
Query filtered = new BooleanQuery.Builder()
- .add(query, Occur.MUST)
+ .add(new BoostQuery(query, 0), Occur.MUST)
.add(matchTheseItems(new int[] {1,3}), Occur.FILTER)
.build();
bqtest(filtered, new int[] {3});
@@ -215,8 +207,7 @@ public class TestComplexExplanations extends BaseExplanationTestCase {
public void testCSQ4() throws Exception {
Query q = new ConstantScoreQuery(matchTheseItems(new int[] {3}));
- q.setBoost(0);
- bqtest(q, new int[] {3});
+ bqtest(new BoostQuery(q, 0), new int[] {3});
}
public void testDMQ10() throws Exception {
@@ -225,17 +216,14 @@ public class TestComplexExplanations extends BaseExplanationTestCase {
BooleanQuery.Builder query = new BooleanQuery.Builder();;
query.add(new TermQuery(new Term(FIELD, "yy")), Occur.SHOULD);
TermQuery boostedQuery = new TermQuery(new Term(FIELD, "w5"));
- boostedQuery.setBoost(100);
- query.add(boostedQuery, Occur.SHOULD);
+ query.add(new BoostQuery(boostedQuery, 100), Occur.SHOULD);
q.add(query.build());
TermQuery xxBoostedQuery = new TermQuery(new Term(FIELD, "xx"));
- xxBoostedQuery.setBoost(0);
- q.add(xxBoostedQuery);
- q.setBoost(0.0f);
- bqtest(q, new int[] { 0,2,3 });
+ q.add(new BoostQuery(xxBoostedQuery, 0));
+ bqtest(new BoostQuery(q, 0), new int[] { 0,2,3 });
}
public void testMPQ7() throws Exception {
@@ -243,8 +231,7 @@ public class TestComplexExplanations extends BaseExplanationTestCase {
q.add(ta(new String[] {"w1"}));
q.add(ta(new String[] {"w2"}));
q.setSlop(1);
- q.setBoost(0.0f);
- bqtest(q, new int[] { 0,1,2 });
+ bqtest(new BoostQuery(q, 0), new int[] { 0,1,2 });
}
public void testBQ12() throws Exception {
@@ -252,8 +239,7 @@ public class TestComplexExplanations extends BaseExplanationTestCase {
BooleanQuery.Builder query = new BooleanQuery.Builder();;
query.add(new TermQuery(new Term(FIELD, "w1")), Occur.SHOULD);
TermQuery boostedQuery = new TermQuery(new Term(FIELD, "w2"));
- boostedQuery.setBoost(0);
- query.add(boostedQuery, Occur.SHOULD);
+ query.add(new BoostQuery(boostedQuery, 0), Occur.SHOULD);
qtest(query.build(), new int[] { 0,1,2,3 });
}
@@ -262,8 +248,7 @@ public class TestComplexExplanations extends BaseExplanationTestCase {
BooleanQuery.Builder query = new BooleanQuery.Builder();;
query.add(new TermQuery(new Term(FIELD, "w1")), Occur.SHOULD);
TermQuery boostedQuery = new TermQuery(new Term(FIELD, "w5"));
- boostedQuery.setBoost(0);
- query.add(boostedQuery, Occur.MUST_NOT);
+ query.add(new BoostQuery(boostedQuery, 0), Occur.MUST_NOT);
qtest(query.build(), new int[] { 1,2,3 });
}
@@ -271,8 +256,7 @@ public class TestComplexExplanations extends BaseExplanationTestCase {
// NOTE: using qtest not bqtest
BooleanQuery.Builder query = new BooleanQuery.Builder();;
TermQuery boostedQuery = new TermQuery(new Term(FIELD, "w1"));
- boostedQuery.setBoost(0);
- query.add(boostedQuery, Occur.MUST);
+ query.add(new BoostQuery(boostedQuery, 0), Occur.MUST);
query.add(new TermQuery(new Term(FIELD, "w2")), Occur.SHOULD);
qtest(query.build(), new int[] { 0,1,2,3 });
@@ -283,66 +267,57 @@ public class TestComplexExplanations extends BaseExplanationTestCase {
builder.add(new TermQuery(new Term(FIELD, "w2")), Occur.SHOULD);
Query query = builder.build();
- query.setBoost(0);
- bqtest(query, new int[] { 0,1,2,3 });
+ bqtest(new BoostQuery(query, 0), new int[] { 0,1,2,3 });
}
public void testBQ22() throws Exception {
BooleanQuery.Builder builder = new BooleanQuery.Builder();;
TermQuery boostedQuery = new TermQuery(new Term(FIELD, "w1"));
- boostedQuery.setBoost(0);
- builder.add(boostedQuery, Occur.MUST);
+ builder.add(new BoostQuery(boostedQuery, 0), Occur.MUST);
builder.add(new TermQuery(new Term(FIELD, "w2")), Occur.SHOULD);
BooleanQuery query = builder.build();
- query.setBoost(0);
- bqtest(query, new int[] { 0,1,2,3 });
+ bqtest(new BoostQuery(query, 0), new int[] { 0,1,2,3 });
}
public void testST3() throws Exception {
SpanQuery q = st("w1");
- q.setBoost(0);
- bqtest(q, new int[] {0,1,2,3});
+ bqtest(new SpanBoostQuery(q, 0), new int[] {0,1,2,3});
}
public void testST6() throws Exception {
SpanQuery q = st("xx");
- q.setBoost(0);
- qtest(q, new int[] {2,3});
+ qtest(new SpanBoostQuery(q, 0), new int[] {2,3});
}
public void testSF3() throws Exception {
SpanQuery q = sf(("w1"),1);
- q.setBoost(0);
- bqtest(q, new int[] {0,1,2,3});
+ bqtest(new SpanBoostQuery(q, 0), new int[] {0,1,2,3});
}
public void testSF7() throws Exception {
SpanQuery q = sf(("xx"),3);
- q.setBoost(0);
- bqtest(q, new int[] {2,3});
+ bqtest(new SpanBoostQuery(q, 0), new int[] {2,3});
}
public void testSNot3() throws Exception {
SpanQuery q = snot(sf("w1",10),st("QQ"));
- q.setBoost(0);
- bqtest(q, new int[] {0,1,2,3});
+ bqtest(new SpanBoostQuery(q, 0), new int[] {0,1,2,3});
}
public void testSNot6() throws Exception {
SpanQuery q = snot(sf("w1",10),st("xx"));
- q.setBoost(0);
- bqtest(q, new int[] {0,1,2,3});
+ bqtest(new SpanBoostQuery(q, 0), new int[] {0,1,2,3});
}
public void testSNot8() throws Exception {
// NOTE: using qtest not bqtest
SpanQuery f = snear("w1","w3",10,true);
- f.setBoost(0);
+ f = new SpanBoostQuery(f, 0);
SpanQuery q = snot(f, st("xx"));
qtest(q, new int[] {0,1,3});
}
public void testSNot9() throws Exception {
// NOTE: using qtest not bqtest
SpanQuery t = st("xx");
- t.setBoost(0);
+ t = new SpanBoostQuery(t, 0);
SpanQuery q = snot(snear("w1","w3",10,true), t);
qtest(q, new int[] {0,1,3});
}
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestConjunctions.java b/lucene/core/src/test/org/apache/lucene/search/TestConjunctions.java
index c5de43c46ff..a97dff69980 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestConjunctions.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestConjunctions.java
@@ -94,7 +94,7 @@ public class TestConjunctions extends LuceneTestCase {
}
@Override
- public SimWeight computeWeight(float queryBoost,
+ public SimWeight computeWeight(
CollectionStatistics collectionStats, TermStatistics... termStats) {
return new SimWeight() {
@Override
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestConstantScoreQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestConstantScoreQuery.java
index b7a1a724103..47f9faa0ba2 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestConstantScoreQuery.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestConstantScoreQuery.java
@@ -110,17 +110,14 @@ public class TestConstantScoreQuery extends LuceneTestCase {
}
});
- final Query csq1 = new ConstantScoreQuery(new TermQuery(new Term ("field", "term")));
- csq1.setBoost(2.0f);
- final Query csq2 = new ConstantScoreQuery(csq1);
- csq2.setBoost(5.0f);
+ final BoostQuery csq1 = new BoostQuery(new ConstantScoreQuery(new TermQuery(new Term ("field", "term"))), 2f);
+ final BoostQuery csq2 = new BoostQuery(new ConstantScoreQuery(csq1), 5f);
final BooleanQuery.Builder bq = new BooleanQuery.Builder();
bq.add(csq1, BooleanClause.Occur.SHOULD);
bq.add(csq2, BooleanClause.Occur.SHOULD);
- final Query csqbq = new ConstantScoreQuery(bq.build());
- csqbq.setBoost(17.0f);
+ final BoostQuery csqbq = new BoostQuery(new ConstantScoreQuery(bq.build()), 17f);
checkHits(searcher, csq1, csq1.getBoost(), TermScorer.class);
checkHits(searcher, csq2, csq2.getBoost(), TermScorer.class);
@@ -212,16 +209,19 @@ public class TestConstantScoreQuery extends LuceneTestCase {
IndexReader r = w.getReader();
w.close();
- Filter filter = new QueryWrapperFilter(AssertingQuery.wrap(random(), new TermQuery(new Term("field", "a"))));
+ final Query wrapped = AssertingQuery.wrap(random(), new TermQuery(new Term("field", "a")));
+ Filter filter = new QueryWrapperFilter(wrapped);
IndexSearcher s = newSearcher(r);
assert s instanceof AssertingIndexSearcher;
// this used to fail
s.search(new ConstantScoreQuery(filter), new TotalHitCountCollector());
// check the rewrite
- Query rewritten = new ConstantScoreQuery(filter).rewrite(r);
- assertTrue(rewritten instanceof ConstantScoreQuery);
- assertTrue(((ConstantScoreQuery) rewritten).getQuery() instanceof AssertingQuery);
+ Query rewritten = filter;
+ for (Query q = rewritten.rewrite(r); q != rewritten; q = rewritten.rewrite(r)) {
+ rewritten = q;
+ }
+ assertEquals(new BoostQuery(new ConstantScoreQuery(wrapped), 0), rewritten);
r.close();
d.close();
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestDisjunctionMaxQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestDisjunctionMaxQuery.java
index de50c52ca62..a5d05deeef1 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestDisjunctionMaxQuery.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestDisjunctionMaxQuery.java
@@ -517,8 +517,7 @@ public class TestDisjunctionMaxQuery extends LuceneTestCase {
/** macro */
protected Query tq(String f, String t, float b) {
Query q = tq(f, t);
- q.setBoost(b);
- return q;
+ return new BoostQuery(q, b);
}
protected void printHits(String test, ScoreDoc[] h, IndexSearcher searcher)
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestDocValuesScoring.java b/lucene/core/src/test/org/apache/lucene/search/TestDocValuesScoring.java
index 0176bed5562..92a9b86d4a4 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestDocValuesScoring.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestDocValuesScoring.java
@@ -153,8 +153,8 @@ public class TestDocValuesScoring extends LuceneTestCase {
}
@Override
- public SimWeight computeWeight(float queryBoost, CollectionStatistics collectionStats, TermStatistics... termStats) {
- return sim.computeWeight(queryBoost, collectionStats, termStats);
+ public SimWeight computeWeight(CollectionStatistics collectionStats, TermStatistics... termStats) {
+ return sim.computeWeight(collectionStats, termStats);
}
@Override
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestElevationComparator.java b/lucene/core/src/test/org/apache/lucene/search/TestElevationComparator.java
index de43425d0e0..d0c6daf77e1 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestElevationComparator.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestElevationComparator.java
@@ -121,8 +121,7 @@ public class TestElevationComparator extends LuceneTestCase {
// System.out.println(" pri doc=" + vals[i+1] + " pri=" + (1+max));
}
BooleanQuery q = b.build();
- q.setBoost(0);
- return q;
+ return new BoostQuery(q, 0f);
}
private Document adoc(String[] vals) {
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestFieldValueQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestFieldValueQuery.java
index 5f9c6bb21d8..cc2434762b6 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestFieldValueQuery.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestFieldValueQuery.java
@@ -139,15 +139,12 @@ public class TestFieldValueQuery extends LuceneTestCase {
iw.close();
final float boost = random().nextFloat() * 10;
- final Query ref = new ConstantScoreQuery(new TermQuery(new Term("has_value", "yes")));
- ref.setBoost(boost);
+ final Query ref = new BoostQuery(new ConstantScoreQuery(new TermQuery(new Term("has_value", "yes"))), boost);
- final Query q1 = new FieldValueQuery("dv1");
- q1.setBoost(boost);
+ final Query q1 = new BoostQuery(new FieldValueQuery("dv1"), boost);
assertSameMatches(searcher, ref, q1, true);
- final Query q2 = new FieldValueQuery("dv2");
- q2.setBoost(boost);
+ final Query q2 = new BoostQuery(new FieldValueQuery("dv2"), boost);
assertSameMatches(searcher, ref, q2, true);
reader.close();
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestLRUQueryCache.java b/lucene/core/src/test/org/apache/lucene/search/TestLRUQueryCache.java
index cb45f518779..019e23ba231 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestLRUQueryCache.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestLRUQueryCache.java
@@ -240,16 +240,14 @@ public class TestLRUQueryCache extends LuceneTestCase {
final IndexSearcher searcher = newSearcher(reader);
final Query query1 = new TermQuery(new Term("color", "blue"));
- query1.setBoost(random().nextFloat());
// different instance yet equal
final Query query2 = new TermQuery(new Term("color", "blue"));
- query2.setBoost(random().nextFloat());
final LRUQueryCache queryCache = new LRUQueryCache(Integer.MAX_VALUE, Long.MAX_VALUE);
searcher.setQueryCache(queryCache);
searcher.setQueryCachingPolicy(QueryCachingPolicy.ALWAYS_CACHE);
- searcher.search(new ConstantScoreQuery(query1), 1);
+ searcher.search(new BoostQuery(new ConstantScoreQuery(query1), random().nextFloat()), 1);
assertEquals(1, queryCache.cachedQueries().size());
queryCache.clearQuery(query2);
@@ -467,8 +465,7 @@ public class TestLRUQueryCache extends LuceneTestCase {
Query[] queries = new Query[10 + random().nextInt(10)];
for (int i = 0; i < queries.length; ++i) {
- queries[i] = new TermQuery(new Term("color", RandomPicks.randomFrom(random(), Arrays.asList("red", "blue", "green", "yellow"))));
- queries[i].setBoost(random().nextFloat());
+ queries[i] = new BoostQuery(new TermQuery(new Term("color", RandomPicks.randomFrom(random(), Arrays.asList("red", "blue", "green", "yellow")))), random().nextFloat());
}
searcher.setQueryCache(queryCache);
@@ -476,7 +473,11 @@ public class TestLRUQueryCache extends LuceneTestCase {
for (int i = 0; i < 20; ++i) {
final int idx = random().nextInt(queries.length);
searcher.search(new ConstantScoreQuery(queries[idx]), 1);
- actualCounts.put(queries[idx], 1 + actualCounts.getOrDefault(queries[idx], 0));
+ Query cacheKey = queries[idx];
+ while (cacheKey instanceof BoostQuery) {
+ cacheKey = ((BoostQuery) cacheKey).getQuery();
+ }
+ actualCounts.put(cacheKey, 1 + actualCounts.getOrDefault(cacheKey, 0));
}
assertEquals(actualCounts, expectedCounts);
@@ -743,9 +744,7 @@ public class TestLRUQueryCache extends LuceneTestCase {
public void testUseRewrittenQueryAsCacheKey() throws IOException {
final Query expectedCacheKey = new TermQuery(new Term("foo", "bar"));
final BooleanQuery.Builder query = new BooleanQuery.Builder();
- final Query sub = expectedCacheKey.clone();
- sub.setBoost(42);
- query.add(sub, Occur.MUST);
+ query.add(new BoostQuery(expectedCacheKey, 42f), Occur.MUST);
final LRUQueryCache queryCache = new LRUQueryCache(1000000, 10000000);
Directory dir = newDirectory();
@@ -762,13 +761,13 @@ public class TestLRUQueryCache extends LuceneTestCase {
@Override
public boolean shouldCache(Query query, LeafReaderContext context) throws IOException {
- assertEquals(expectedCacheKey, QueryCache.cacheKey(query));
+ assertEquals(expectedCacheKey, query);
return true;
}
@Override
public void onUse(Query query) {
- assertEquals(expectedCacheKey, QueryCache.cacheKey(query));
+ assertEquals(expectedCacheKey, query);
}
};
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestMatchAllDocsQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestMatchAllDocsQuery.java
index ba4ecc98c7a..086f2edf6e8 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestMatchAllDocsQuery.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestMatchAllDocsQuery.java
@@ -90,8 +90,6 @@ public class TestMatchAllDocsQuery extends LuceneTestCase {
Query q1 = new MatchAllDocsQuery();
Query q2 = new MatchAllDocsQuery();
assertTrue(q1.equals(q2));
- q1.setBoost(1.5f);
- assertFalse(q1.equals(q2));
}
private void addDoc(String text, IndexWriter iw, float boost) throws IOException {
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestMinShouldMatch2.java b/lucene/core/src/test/org/apache/lucene/search/TestMinShouldMatch2.java
index 4c3690aaaf1..9749581973a 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestMinShouldMatch2.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestMinShouldMatch2.java
@@ -334,7 +334,7 @@ public class TestMinShouldMatch2 extends LuceneTestCase {
boolean success = ords.add(ord);
assert success; // no dups
TermContext context = TermContext.build(reader.getContext(), term);
- SimWeight w = weight.similarity.computeWeight(1f,
+ SimWeight w = weight.similarity.computeWeight(
searcher.collectionStatistics("field"),
searcher.termStatistics(term, context));
w.getValueForNormalization(); // ignored
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestMultiTermConstantScore.java b/lucene/core/src/test/org/apache/lucene/search/TestMultiTermConstantScore.java
index f214d141efd..7a807a6bc2a 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestMultiTermConstantScore.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestMultiTermConstantScore.java
@@ -225,8 +225,7 @@ public class TestMultiTermConstantScore extends BaseTestRangeFilter {
search.setSimilarity(new DefaultSimilarity());
Query q = csrq("data", "1", "6", T, T);
- q.setBoost(100);
- search.search(q, new SimpleCollector() {
+ search.search(new BoostQuery(q, 100), new SimpleCollector() {
private int base = 0;
private Scorer scorer;
@Override
@@ -252,8 +251,7 @@ public class TestMultiTermConstantScore extends BaseTestRangeFilter {
// Ensure that boosting works to score one clause of a query higher
// than another.
//
- Query q1 = csrq("data", "A", "A", T, T); // matches document #0
- q1.setBoost(.1f);
+ Query q1 = new BoostQuery(csrq("data", "A", "A", T, T), .1f); // matches document #0
Query q2 = csrq("data", "Z", "Z", T, T); // matches document #1
BooleanQuery.Builder bq = new BooleanQuery.Builder();
bq.setDisableCoord(true);
@@ -265,8 +263,7 @@ public class TestMultiTermConstantScore extends BaseTestRangeFilter {
Assert.assertEquals(0, hits[1].doc);
assertTrue(hits[0].score > hits[1].score);
- q1 = csrq("data", "A", "A", T, T, MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE); // matches document #0
- q1.setBoost(.1f);
+ q1 = new BoostQuery(csrq("data", "A", "A", T, T, MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE), .1f); // matches document #0
q2 = csrq("data", "Z", "Z", T, T, MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE); // matches document #1
bq = new BooleanQuery.Builder();
bq.setDisableCoord(true);
@@ -278,8 +275,7 @@ public class TestMultiTermConstantScore extends BaseTestRangeFilter {
Assert.assertEquals(0, hits[1].doc);
assertTrue(hits[0].score > hits[1].score);
- q1 = csrq("data", "A", "A", T, T); // matches document #0
- q1.setBoost(10f);
+ q1 = new BoostQuery(csrq("data", "A", "A", T, T), 10f); // matches document #0
q2 = csrq("data", "Z", "Z", T, T); // matches document #1
bq = new BooleanQuery.Builder();
bq.add(q1, BooleanClause.Occur.SHOULD);
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestMultiTermQueryRewrites.java b/lucene/core/src/test/org/apache/lucene/search/TestMultiTermQueryRewrites.java
index fc50d7e8e6d..05996eef992 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestMultiTermQueryRewrites.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestMultiTermQueryRewrites.java
@@ -143,9 +143,10 @@ public class TestMultiTermQueryRewrites extends LuceneTestCase {
private void checkBooleanQueryBoosts(BooleanQuery bq) {
for (BooleanClause clause : bq.clauses()) {
- final TermQuery mtq = (TermQuery) clause.getQuery();
+ final BoostQuery boostQ = (BoostQuery) clause.getQuery();
+ final TermQuery mtq = (TermQuery) boostQ.getQuery();
assertEquals("Parallel sorting of boosts in rewrite mode broken",
- Float.parseFloat(mtq.getTerm().text()), mtq.getBoost(), 0);
+ Float.parseFloat(mtq.getTerm().text()), boostQ.getBoost(), 0);
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestNGramPhraseQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestNGramPhraseQuery.java
index 0dab82978e6..29c2d3ab498 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestNGramPhraseQuery.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestNGramPhraseQuery.java
@@ -76,14 +76,6 @@ public class TestNGramPhraseQuery extends LuceneTestCase {
PhraseQuery rewritten3 = (PhraseQuery) q;
assertArrayEquals(new Term[]{new Term("f", "ABC"), new Term("f", "DEF"), new Term("f", "FGH")}, rewritten3.getTerms());
assertArrayEquals(new int[]{0, 3, 5}, rewritten3.getPositions());
-
- // LUCENE-4970: boosting test
- NGramPhraseQuery pq4 = new NGramPhraseQuery(2, new PhraseQuery("f", "AB", "BC", "CD"));
- pq4.setBoost(100.0F);
-
- q = pq4.rewrite(reader);
- assertNotSame(pq4, q);
- assertEquals(pq4.getBoost(), q.getBoost(), 0.1f);
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestNeedsScores.java b/lucene/core/src/test/org/apache/lucene/search/TestNeedsScores.java
index 3549fed74ba..514ff64d8b0 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestNeedsScores.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestNeedsScores.java
@@ -28,7 +28,6 @@ import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
-import org.apache.lucene.util.Bits;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.LuceneTestCase;
@@ -143,7 +142,7 @@ public class TestNeedsScores extends LuceneTestCase {
public Query rewrite(IndexReader reader) throws IOException {
Query in2 = in.rewrite(reader);
if (in2 == in) {
- return this;
+ return super.rewrite(reader);
} else {
return new AssertNeedsScores(in2, value);
}
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestPhraseQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestPhraseQuery.java
index a0633c47fa0..dd4f7579a9d 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestPhraseQuery.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestPhraseQuery.java
@@ -372,9 +372,6 @@ public class TestPhraseQuery extends LuceneTestCase {
builder.setSlop(5);
q = builder.build();
assertEquals("field:\"? hi|hello ? ? ? test\"~5", q.toString());
-
- q.setBoost(2);
- assertEquals("field:\"? hi|hello ? ? ? test\"~5^2.0", q.toString());
}
public void testWrappedPhrase() throws IOException {
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestQueryRescorer.java b/lucene/core/src/test/org/apache/lucene/search/TestQueryRescorer.java
index de8186d1dfc..9e704f82362 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestQueryRescorer.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestQueryRescorer.java
@@ -35,7 +35,6 @@ import org.apache.lucene.search.spans.SpanNearQuery;
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.search.spans.SpanTermQuery;
import org.apache.lucene.store.Directory;
-import org.apache.lucene.util.Bits;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TestUtil;
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestSimpleExplanations.java b/lucene/core/src/test/org/apache/lucene/search/TestSimpleExplanations.java
index 21ee8968770..c77329f8a82 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestSimpleExplanations.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestSimpleExplanations.java
@@ -36,8 +36,7 @@ public class TestSimpleExplanations extends BaseExplanationTestCase {
}
public void testT2() throws Exception {
TermQuery termQuery = new TermQuery(new Term(FIELD, "w1"));
- termQuery.setBoost(100);
- qtest(termQuery, new int[] { 0,1,2,3 });
+ qtest(new BoostQuery(termQuery, 100), new int[] { 0,1,2,3 });
}
/* MatchAllDocs */
@@ -47,8 +46,7 @@ public class TestSimpleExplanations extends BaseExplanationTestCase {
}
public void testMA2() throws Exception {
Query q=new MatchAllDocsQuery();
- q.setBoost(1000);
- qtest(q, new int[] { 0,1,2,3 });
+ qtest(new BoostQuery(q, 1000), new int[] { 0,1,2,3 });
}
/* some simple phrase tests */
@@ -94,8 +92,7 @@ public class TestSimpleExplanations extends BaseExplanationTestCase {
}
public void testCSQ3() throws Exception {
Query q = new ConstantScoreQuery(matchTheseItems(new int[] {0,2}));
- q.setBoost(1000);
- qtest(q, new int[] {0,2});
+ qtest(new BoostQuery(q, 1000), new int[] {0,2});
}
/* DisjunctionMaxQuery */
@@ -164,13 +161,11 @@ public class TestSimpleExplanations extends BaseExplanationTestCase {
booleanQuery.add(new TermQuery(new Term(FIELD, "yy")), BooleanClause.Occur.SHOULD);
TermQuery boostedQuery = new TermQuery(new Term(FIELD, "w5"));
- boostedQuery.setBoost(100);
- booleanQuery.add(boostedQuery, BooleanClause.Occur.SHOULD);
+ booleanQuery.add(new BoostQuery(boostedQuery, 100), BooleanClause.Occur.SHOULD);
q.add(booleanQuery.build());
TermQuery xxBoostedQuery = new TermQuery(new Term(FIELD, "xx"));
- xxBoostedQuery.setBoost(100000);
- q.add(xxBoostedQuery);
+ q.add(new BoostQuery(xxBoostedQuery, 100000));
qtest(q, new int[] { 0,2,3 });
}
@@ -181,13 +176,11 @@ public class TestSimpleExplanations extends BaseExplanationTestCase {
booleanQuery.add(new TermQuery(new Term(FIELD, "yy")), BooleanClause.Occur.SHOULD);
TermQuery boostedQuery = new TermQuery(new Term(FIELD, "w5"));
- boostedQuery.setBoost(100);
- booleanQuery.add(boostedQuery, BooleanClause.Occur.SHOULD);
+ booleanQuery.add(new BoostQuery(boostedQuery, 100), BooleanClause.Occur.SHOULD);
q.add(booleanQuery.build());
TermQuery xxBoostedQuery = new TermQuery(new Term(FIELD, "xx"));
- xxBoostedQuery.setBoost(0);
- q.add(xxBoostedQuery);
+ q.add(new BoostQuery(xxBoostedQuery, 0));
qtest(q, new int[] { 0,2,3 });
}
@@ -374,8 +367,7 @@ public class TestSimpleExplanations extends BaseExplanationTestCase {
BooleanQuery.Builder query = new BooleanQuery.Builder();
query.add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.SHOULD);
TermQuery boostedQuery = new TermQuery(new Term(FIELD, "w1"));
- boostedQuery.setBoost(1000);
- query.add(boostedQuery, BooleanClause.Occur.SHOULD);
+ query.add(new BoostQuery(boostedQuery, 1000), BooleanClause.Occur.SHOULD);
qtest(query.build(), new int[] { 0,1,2,3 });
}
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestSimpleSearchEquivalence.java b/lucene/core/src/test/org/apache/lucene/search/TestSimpleSearchEquivalence.java
index 4b89542b0bf..ddf83371d64 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestSimpleSearchEquivalence.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestSimpleSearchEquivalence.java
@@ -202,4 +202,16 @@ public class TestSimpleSearchEquivalence extends SearchEquivalenceTestBase {
PhraseQuery q2 = builder.build();
assertSameScores(q1, q2);
}
+
+ public void testBoostQuerySimplification() throws Exception {
+ float b1 = random().nextFloat() * 10;
+ float b2 = random().nextFloat() * 10;
+ Term term = randomTerm();
+
+ Query q1 = new BoostQuery(new BoostQuery(new TermQuery(term), b2), b1);
+ // Use AssertingQuery to prevent BoostQuery from merging inner and outer boosts
+ Query q2 = new BoostQuery(new AssertingQuery(random(), new BoostQuery(new TermQuery(term), b2)), b1);
+
+ assertSameScores(q1, q2);
+ }
}
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestTermRangeQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestTermRangeQuery.java
index 82c9249206d..e2a6d5b6724 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestTermRangeQuery.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestTermRangeQuery.java
@@ -159,17 +159,12 @@ public class TestTermRangeQuery extends LuceneTestCase {
public void testEqualsHashcode() {
Query query = TermRangeQuery.newStringRange("content", "A", "C", true, true);
- query.setBoost(1.0f);
Query other = TermRangeQuery.newStringRange("content", "A", "C", true, true);
- other.setBoost(1.0f);
assertEquals("query equals itself is true", query, query);
assertEquals("equivalent queries are equal", query, other);
assertEquals("hashcode must return same value when equals is true", query.hashCode(), other.hashCode());
- other.setBoost(2.0f);
- assertFalse("Different boost queries are not equal", query.equals(other));
-
other = TermRangeQuery.newStringRange("notcontent", "A", "C", true, true);
assertFalse("Different fields are not equal", query.equals(other));
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestTopFieldCollector.java b/lucene/core/src/test/org/apache/lucene/search/TestTopFieldCollector.java
index a2c0ca3bab0..b9773fe7d6b 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestTopFieldCollector.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestTopFieldCollector.java
@@ -190,11 +190,11 @@ public class TestTopFieldCollector extends LuceneTestCase {
text.setStringValue("baz");
w.addDocument(doc);
IndexReader reader = w.getReader();
- TermQuery foo = new TermQuery(new Term("text", "foo"));
- TermQuery bar = new TermQuery(new Term("text", "bar"));
- bar.setBoost(2);
- TermQuery baz = new TermQuery(new Term("text", "baz"));
- baz.setBoost(3);
+ Query foo = new TermQuery(new Term("text", "foo"));
+ Query bar = new TermQuery(new Term("text", "bar"));
+ foo = new BoostQuery(foo, 2);
+ Query baz = new TermQuery(new Term("text", "baz"));
+ baz = new BoostQuery(baz, 3);
Query query = new BooleanQuery.Builder()
.add(foo, Occur.SHOULD)
.add(bar, Occur.SHOULD)
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestUsageTrackingFilterCachingPolicy.java b/lucene/core/src/test/org/apache/lucene/search/TestUsageTrackingFilterCachingPolicy.java
index 1b478720c2e..fbbca92c72e 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestUsageTrackingFilterCachingPolicy.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestUsageTrackingFilterCachingPolicy.java
@@ -30,19 +30,6 @@ public class TestUsageTrackingFilterCachingPolicy extends LuceneTestCase {
assertFalse(UsageTrackingQueryCachingPolicy.isCostly(new TermQuery(new Term("field", "value"))));
}
- public void testBoostIgnored() {
- Query q1 = new TermQuery(new Term("foo", "bar"));
- q1.setBoost(2);
- Query q2 = q1.clone();
- q2.setBoost(3);
- Query q3 = q1.clone();
- q3.setBoost(4);
- UsageTrackingQueryCachingPolicy policy = new UsageTrackingQueryCachingPolicy();
- policy.onUse(q1);
- policy.onUse(q2);
- assertEquals(2, policy.frequency(q3));
- }
-
public void testNeverCacheMatchAll() throws Exception {
Query q = new MatchAllDocsQuery();
UsageTrackingQueryCachingPolicy policy = new UsageTrackingQueryCachingPolicy();
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestWildcard.java b/lucene/core/src/test/org/apache/lucene/search/TestWildcard.java
index dee2fe99070..f812d01c922 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestWildcard.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestWildcard.java
@@ -70,22 +70,16 @@ public class TestWildcard extends LuceneTestCase {
assertMatches(searcher, wq, 1);
wq.setRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_REWRITE);
- wq.setBoost(0.1F);
Query q = searcher.rewrite(wq);
assertTrue(q instanceof TermQuery);
- assertEquals(q.getBoost(), wq.getBoost(), 0);
wq.setRewriteMethod(MultiTermQuery.CONSTANT_SCORE_REWRITE);
- wq.setBoost(0.2F);
q = searcher.rewrite(wq);
assertTrue(q instanceof MultiTermQueryConstantScoreWrapper);
- assertEquals(q.getBoost(), wq.getBoost(), 0.1);
wq.setRewriteMethod(MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE);
- wq.setBoost(0.4F);
q = searcher.rewrite(wq);
assertTrue(q instanceof ConstantScoreQuery);
- assertEquals(q.getBoost(), wq.getBoost(), 0.1);
reader.close();
indexStore.close();
}
diff --git a/lucene/core/src/test/org/apache/lucene/search/payloads/TestPayloadExplanations.java b/lucene/core/src/test/org/apache/lucene/search/payloads/TestPayloadExplanations.java
index 359cf08b327..b6dc7d07ebf 100644
--- a/lucene/core/src/test/org/apache/lucene/search/payloads/TestPayloadExplanations.java
+++ b/lucene/core/src/test/org/apache/lucene/search/payloads/TestPayloadExplanations.java
@@ -20,6 +20,7 @@ package org.apache.lucene.search.payloads;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BaseExplanationTestCase;
import org.apache.lucene.search.similarities.DefaultSimilarity;
+import org.apache.lucene.search.spans.SpanBoostQuery;
import org.apache.lucene.search.spans.SpanNearQuery;
import org.apache.lucene.search.spans.SpanOrQuery;
import org.apache.lucene.search.spans.SpanQuery;
@@ -64,8 +65,7 @@ public class TestPayloadExplanations extends BaseExplanationTestCase {
public void testPT2() throws Exception {
for (PayloadFunction fn : functions) {
SpanQuery q = pt("w1", fn);
- q.setBoost(1000);
- qtest(q, new int[] {0,1,2,3});
+ qtest(new SpanBoostQuery(q, 1000), new int[] {0,1,2,3});
}
}
@@ -78,8 +78,7 @@ public class TestPayloadExplanations extends BaseExplanationTestCase {
public void testPT5() throws Exception {
for (PayloadFunction fn : functions) {
SpanQuery q = pt("xx", fn);
- q.setBoost(1000);
- qtest(q, new int[] {2,3});
+ qtest(new SpanBoostQuery(q, 1000), new int[] {2,3});
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/search/similarities/TestSimilarityBase.java b/lucene/core/src/test/org/apache/lucene/search/similarities/TestSimilarityBase.java
index cf61cb60b95..ee53565aaf4 100644
--- a/lucene/core/src/test/org/apache/lucene/search/similarities/TestSimilarityBase.java
+++ b/lucene/core/src/test/org/apache/lucene/search/similarities/TestSimilarityBase.java
@@ -165,7 +165,7 @@ public class TestSimilarityBase extends LuceneTestCase {
/** Creates the default statistics object that the specific tests modify. */
private BasicStats createStats() {
- BasicStats stats = new BasicStats("spoof", 1);
+ BasicStats stats = new BasicStats("spoof");
stats.setNumberOfDocuments(NUMBER_OF_DOCUMENTS);
stats.setNumberOfFieldTokens(NUMBER_OF_FIELD_TOKENS);
stats.setAvgFieldLength(AVG_FIELD_LENGTH);
@@ -189,9 +189,10 @@ public class TestSimilarityBase extends LuceneTestCase {
*/
private void unitTestCore(BasicStats stats, float freq, int docLen) {
for (SimilarityBase sim : sims) {
- BasicStats realStats = (BasicStats) sim.computeWeight(stats.getTotalBoost(),
+ BasicStats realStats = (BasicStats) sim.computeWeight(
toCollectionStats(stats),
toTermStats(stats));
+ realStats.normalize(1f, stats.getBoost());
float score = sim.score(realStats, freq, docLen);
float explScore = sim.explain(
realStats, 1, Explanation.match(freq, "freq"), docLen).getValue();
@@ -521,9 +522,10 @@ public class TestSimilarityBase extends LuceneTestCase {
*/
private void correctnessTestCore(SimilarityBase sim, float gold) {
BasicStats stats = createStats();
- BasicStats realStats = (BasicStats) sim.computeWeight(stats.getTotalBoost(),
+ BasicStats realStats = (BasicStats) sim.computeWeight(
toCollectionStats(stats),
toTermStats(stats));
+ realStats.normalize(1f, stats.getBoost());
float score = sim.score(realStats, FREQ, DOC_LEN);
assertEquals(
sim.toString() + " score not correct.", gold, score, FLOAT_EPSILON);
diff --git a/lucene/core/src/test/org/apache/lucene/search/spans/TestFieldMaskingSpanQuery.java b/lucene/core/src/test/org/apache/lucene/search/spans/TestFieldMaskingSpanQuery.java
index dd69190c733..8bb84420486 100644
--- a/lucene/core/src/test/org/apache/lucene/search/spans/TestFieldMaskingSpanQuery.java
+++ b/lucene/core/src/test/org/apache/lucene/search/spans/TestFieldMaskingSpanQuery.java
@@ -136,7 +136,6 @@ public class TestFieldMaskingSpanQuery extends LuceneTestCase {
public void testRewrite0() throws Exception {
SpanQuery q = new FieldMaskingSpanQuery
(new SpanTermQuery(new Term("last", "sally")) , "first");
- q.setBoost(8.7654321f);
SpanQuery qr = (SpanQuery) searcher.rewrite(q);
QueryUtils.checkEqual(q, qr);
@@ -195,16 +194,6 @@ public class TestFieldMaskingSpanQuery extends LuceneTestCase {
QueryUtils.checkUnequal(q1, q3);
QueryUtils.checkUnequal(q1, q4);
QueryUtils.checkUnequal(q1, q5);
-
- SpanQuery qA = new FieldMaskingSpanQuery
- (new SpanTermQuery(new Term("last", "sally")) , "first");
- qA.setBoost(9f);
- SpanQuery qB = new FieldMaskingSpanQuery
- (new SpanTermQuery(new Term("last", "sally")) , "first");
- QueryUtils.checkUnequal(qA, qB);
- qB.setBoost(9f);
- QueryUtils.checkEqual(qA, qB);
-
}
public void testNoop0() throws Exception {
diff --git a/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanBoostQuery.java b/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanBoostQuery.java
new file mode 100644
index 00000000000..265e9d55984
--- /dev/null
+++ b/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanBoostQuery.java
@@ -0,0 +1,50 @@
+package org.apache.lucene.search.spans;
+
+import org.apache.lucene.index.Term;
+import org.apache.lucene.util.LuceneTestCase;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+public class TestSpanBoostQuery extends LuceneTestCase {
+
+ public void testEquals() {
+ final float boost = random().nextFloat() * 3 - 1;
+ SpanTermQuery q = new SpanTermQuery(new Term("foo", "bar"));
+ SpanBoostQuery q1 = new SpanBoostQuery(q, boost);
+ SpanBoostQuery q2 = new SpanBoostQuery(q, boost);
+ assertEquals(q1, q2);
+ assertEquals(q1.getBoost(), q2.getBoost(), 0f);
+
+ float boost2 = boost;
+ while (boost == boost2) {
+ boost2 = random().nextFloat() * 3 - 1;
+ }
+ SpanBoostQuery q3 = new SpanBoostQuery(q, boost2);
+ assertFalse(q1.equals(q3));
+ assertFalse(q1.hashCode() == q3.hashCode());
+ }
+
+ public void testToString() {
+ assertEquals("foo:bar^2.0", new SpanBoostQuery(new SpanTermQuery(new Term("foo", "bar")), 2).toString());
+ SpanOrQuery bq = new SpanOrQuery(
+ new SpanTermQuery(new Term("foo", "bar")),
+ new SpanTermQuery(new Term("foo", "baz")));
+ assertEquals("spanOr([foo:bar, foo:baz])^2.0", new SpanBoostQuery(bq, 2).toString());
+ }
+
+}
diff --git a/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanExplanations.java b/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanExplanations.java
index d234d559647..f0bd5b208f0 100644
--- a/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanExplanations.java
+++ b/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanExplanations.java
@@ -19,8 +19,6 @@ package org.apache.lucene.search.spans;
import org.apache.lucene.search.*;
-import static org.apache.lucene.search.spans.SpanTestUtil.*;
-
/**
* TestExplanations subclass focusing on span queries
*/
@@ -34,8 +32,7 @@ public class TestSpanExplanations extends BaseExplanationTestCase {
}
public void testST2() throws Exception {
SpanQuery q = st("w1");
- q.setBoost(1000);
- qtest(q, new int[] {0,1,2,3});
+ qtest(new BoostQuery(q, 1000), new int[] {0,1,2,3});
}
public void testST4() throws Exception {
SpanQuery q = st("xx");
@@ -43,8 +40,7 @@ public class TestSpanExplanations extends BaseExplanationTestCase {
}
public void testST5() throws Exception {
SpanQuery q = st("xx");
- q.setBoost(1000);
- qtest(q, new int[] {2,3});
+ qtest(new BoostQuery(q, 1000), new int[] {2,3});
}
/* some SpanFirstQueries */
@@ -55,8 +51,7 @@ public class TestSpanExplanations extends BaseExplanationTestCase {
}
public void testSF2() throws Exception {
SpanQuery q = sf(("w1"),1);
- q.setBoost(1000);
- qtest(q, new int[] {0,1,2,3});
+ qtest(new BoostQuery(q, 1000), new int[] {0,1,2,3});
}
public void testSF4() throws Exception {
SpanQuery q = sf(("xx"),2);
@@ -68,8 +63,7 @@ public class TestSpanExplanations extends BaseExplanationTestCase {
}
public void testSF6() throws Exception {
SpanQuery q = sf(("yy"),4);
- q.setBoost(1000);
- qtest(q, new int[] {2});
+ qtest(new BoostQuery(q, 1000), new int[] {2});
}
/* some SpanOrQueries */
@@ -150,8 +144,7 @@ public class TestSpanExplanations extends BaseExplanationTestCase {
}
public void testSNot2() throws Exception {
SpanQuery q = snot(sf("w1",10),st("QQ"));
- q.setBoost(1000);
- qtest(q, new int[] {0,1,2,3});
+ qtest(new BoostQuery(q, 1000), new int[] {0,1,2,3});
}
public void testSNot4() throws Exception {
SpanQuery q = snot(sf("w1",10),st("xx"));
@@ -159,18 +152,15 @@ public class TestSpanExplanations extends BaseExplanationTestCase {
}
public void testSNot5() throws Exception {
SpanQuery q = snot(sf("w1",10),st("xx"));
- q.setBoost(1000);
- qtest(q, new int[] {0,1,2,3});
+ qtest(new BoostQuery(q, 1000), new int[] {0,1,2,3});
}
public void testSNot7() throws Exception {
SpanQuery f = snear("w1","w3",10,true);
- f.setBoost(1000);
SpanQuery q = snot(f, st("xx"));
qtest(q, new int[] {0,1,3});
}
public void testSNot10() throws Exception {
SpanQuery t = st("xx");
- t.setBoost(10000);
SpanQuery q = snot(snear("w1","w3",10,true), t);
qtest(q, new int[] {0,1,3});
}
diff --git a/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanSearchEquivalence.java b/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanSearchEquivalence.java
index 769251374f9..2c168f31f4d 100644
--- a/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanSearchEquivalence.java
+++ b/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanSearchEquivalence.java
@@ -454,4 +454,16 @@ public class TestSpanSearchEquivalence extends SearchEquivalenceTestBase {
Query q2 = spanQuery(new SpanContainingQuery(nearQuery, termQuery));
assertSameSet(q1, q2);
}
+
+ public void testSpanBoostQuerySimplification() throws Exception {
+ float b1 = random().nextFloat() * 10;
+ float b2 = random().nextFloat() * 10;
+ Term term = randomTerm();
+
+ Query q1 = new SpanBoostQuery(new SpanBoostQuery(new SpanTermQuery(term), b2), b1);
+ // Use AssertingQuery to prevent BoostQuery from merging inner and outer boosts
+ Query q2 = new SpanBoostQuery(new AssertingSpanQuery(new SpanBoostQuery(new SpanTermQuery(term), b2)), b1);
+
+ assertSameScores(q1, q2);
+ }
}
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/DrillDownQuery.java b/lucene/facet/src/java/org/apache/lucene/facet/DrillDownQuery.java
index fa67f5315f1..7967aaecfa5 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/DrillDownQuery.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/DrillDownQuery.java
@@ -28,7 +28,7 @@ import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
-import org.apache.lucene.search.ConstantScoreQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
@@ -39,8 +39,8 @@ import org.apache.lucene.search.TermQuery;
* want to drill-down over.
* <p>
* <b>NOTE:</b> if you choose to create your own {@link Query} by calling
- * {@link #term}, it is recommended to wrap it with {@link ConstantScoreQuery}
- * and set the {@link ConstantScoreQuery#setBoost(float) boost} to {@code 0.0f},
+ * {@link #term}, it is recommended to wrap it in a {@link BoostQuery}
+ * with a boost of {@code 0.0f},
* so that it does not affect the scores of the documents.
*
* @lucene.experimental
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/DrillSidewaysQuery.java b/lucene/facet/src/java/org/apache/lucene/facet/DrillSidewaysQuery.java
index 622ddda1698..01031636a8c 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/DrillSidewaysQuery.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/DrillSidewaysQuery.java
@@ -72,7 +72,7 @@ class DrillSidewaysQuery extends Query {
newQuery = rewrittenQuery;
}
if (newQuery == baseQuery) {
- return this;
+ return super.rewrite(reader);
} else {
return new DrillSidewaysQuery(newQuery, drillDownCollector, drillSidewaysCollectors, drillDownQueries, scoreSubDocsAtOnce);
}
@@ -101,8 +101,8 @@ class DrillSidewaysQuery extends Query {
}
@Override
- public void normalize(float norm, float topLevelBoost) {
- baseWeight.normalize(norm, topLevelBoost);
+ public void normalize(float norm, float boost) {
+ baseWeight.normalize(norm, boost);
}
@Override
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/range/DoubleRange.java b/lucene/facet/src/java/org/apache/lucene/facet/range/DoubleRange.java
index 26979f31b66..a819f9bcce7 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/range/DoubleRange.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/range/DoubleRange.java
@@ -143,9 +143,7 @@ public final class DoubleRange extends Range {
if (fastMatchQuery != null) {
final Query fastMatchRewritten = fastMatchQuery.rewrite(reader);
if (fastMatchRewritten != fastMatchQuery) {
- Query rewritten = new ValueSourceQuery(range, fastMatchRewritten, valueSource);
- rewritten.setBoost(getBoost());
- return rewritten;
+ return new ValueSourceQuery(range, fastMatchRewritten, valueSource);
}
}
return super.rewrite(reader);
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/range/LongRange.java b/lucene/facet/src/java/org/apache/lucene/facet/range/LongRange.java
index 82318cd11f5..66f6e2e81a8 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/range/LongRange.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/range/LongRange.java
@@ -135,9 +135,7 @@ public final class LongRange extends Range {
if (fastMatchQuery != null) {
final Query fastMatchRewritten = fastMatchQuery.rewrite(reader);
if (fastMatchRewritten != fastMatchQuery) {
- Query rewritten = new ValueSourceQuery(range, fastMatchRewritten, valueSource);
- rewritten.setBoost(getBoost());
- return rewritten;
+ return new ValueSourceQuery(range, fastMatchRewritten, valueSource);
}
}
return super.rewrite(reader);
diff --git a/lucene/facet/src/test/org/apache/lucene/facet/range/TestRangeFacetCounts.java b/lucene/facet/src/test/org/apache/lucene/facet/range/TestRangeFacetCounts.java
index 6e8e829b7ad..e46348b026e 100644
--- a/lucene/facet/src/test/org/apache/lucene/facet/range/TestRangeFacetCounts.java
+++ b/lucene/facet/src/test/org/apache/lucene/facet/range/TestRangeFacetCounts.java
@@ -56,7 +56,6 @@ import org.apache.lucene.queries.function.docvalues.DoubleDocValues;
import org.apache.lucene.queries.function.valuesource.DoubleFieldSource;
import org.apache.lucene.queries.function.valuesource.FloatFieldSource;
import org.apache.lucene.queries.function.valuesource.LongFieldSource;
-import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
@@ -65,7 +64,6 @@ import org.apache.lucene.search.Query;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.Weight;
import org.apache.lucene.store.Directory;
-import org.apache.lucene.util.Bits;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.TestUtil;
@@ -875,9 +873,7 @@ public class TestRangeFacetCounts extends FacetTestCase {
public Query rewrite(IndexReader reader) throws IOException {
final Query inRewritten = in.rewrite(reader);
if (in != inRewritten) {
- Query rewritten = new UsedQuery(inRewritten, used);
- rewritten.setBoost(getBoost());
- return rewritten;
+ return new UsedQuery(inRewritten, used);
}
return super.rewrite(reader);
}
diff --git a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetSumValueSource.java b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetSumValueSource.java
index 98694465b57..41fefc87350 100644
--- a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetSumValueSource.java
+++ b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetSumValueSource.java
@@ -51,6 +51,7 @@ import org.apache.lucene.queries.function.docvalues.DoubleDocValues;
import org.apache.lucene.queries.function.valuesource.FloatFieldSource;
import org.apache.lucene.queries.function.valuesource.IntFieldSource;
import org.apache.lucene.queries.function.valuesource.LongFieldSource;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
@@ -268,8 +269,7 @@ public class TestTaxonomyFacetSumValueSource extends FacetTestCase {
DirectoryTaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);
FacetsCollector fc = new FacetsCollector(true);
- ConstantScoreQuery csq = new ConstantScoreQuery(new MatchAllDocsQuery());
- csq.setBoost(2.0f);
+ BoostQuery csq = new BoostQuery(new ConstantScoreQuery(new MatchAllDocsQuery()), 2f);
TopDocs td = FacetsCollector.search(newSearcher(r), csq, 10, fc);
diff --git a/lucene/highlighter/src/java/org/apache/lucene/search/highlight/QueryScorer.java b/lucene/highlighter/src/java/org/apache/lucene/search/highlight/QueryScorer.java
index 7655e889233..56b4b2da6c2 100644
--- a/lucene/highlighter/src/java/org/apache/lucene/search/highlight/QueryScorer.java
+++ b/lucene/highlighter/src/java/org/apache/lucene/search/highlight/QueryScorer.java
@@ -216,10 +216,10 @@ public class QueryScorer implements Scorer {
qse.setWrapIfNotCachingTokenFilter(wrapToCaching);
qse.setUsePayloads(usePayloads);
if (reader == null) {
- this.fieldWeightedSpanTerms = qse.getWeightedSpanTerms(query,
+ this.fieldWeightedSpanTerms = qse.getWeightedSpanTerms(query, 1f,
tokenStream, field);
} else {
- this.fieldWeightedSpanTerms = qse.getWeightedSpanTermsWithScores(query,
+ this.fieldWeightedSpanTerms = qse.getWeightedSpanTermsWithScores(query, 1f,
tokenStream, field, reader);
}
if(qse.isCachedTokenStream()) {
diff --git a/lucene/highlighter/src/java/org/apache/lucene/search/highlight/QueryTermExtractor.java b/lucene/highlighter/src/java/org/apache/lucene/search/highlight/QueryTermExtractor.java
index ff7fc7b1b11..7ccf04aafc7 100644
--- a/lucene/highlighter/src/java/org/apache/lucene/search/highlight/QueryTermExtractor.java
+++ b/lucene/highlighter/src/java/org/apache/lucene/search/highlight/QueryTermExtractor.java
@@ -25,6 +25,7 @@ import org.apache.lucene.index.MultiReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
@@ -102,7 +103,7 @@ public final class QueryTermExtractor
public static final WeightedTerm[] getTerms(Query query, boolean prohibited, String fieldName)
{
HashSet<WeightedTerm> terms=new HashSet<>();
- getTerms(query,terms,prohibited,fieldName);
+ getTerms(query, 1f, terms,prohibited,fieldName);
return terms.toArray(new WeightedTerm[0]);
}
@@ -118,10 +119,13 @@ public final class QueryTermExtractor
return getTerms(query,prohibited,null);
}
- private static final void getTerms(Query query, HashSet<WeightedTerm> terms, boolean prohibited, String fieldName) {
+ private static final void getTerms(Query query, float boost, HashSet<WeightedTerm> terms, boolean prohibited, String fieldName) {
try {
- if (query instanceof BooleanQuery)
- getTermsFromBooleanQuery((BooleanQuery) query, terms, prohibited, fieldName);
+ if (query instanceof BoostQuery) {
+ BoostQuery boostQuery = (BoostQuery) query;
+ getTerms(boostQuery.getQuery(), boost * boostQuery.getBoost(), terms, prohibited, fieldName);
+ } else if (query instanceof BooleanQuery)
+ getTermsFromBooleanQuery((BooleanQuery) query, boost, terms, prohibited, fieldName);
else {
HashSet<Term> nonWeightedTerms = new HashSet<>();
try {
@@ -132,7 +136,7 @@ public final class QueryTermExtractor
for (Iterator<Term> iter = nonWeightedTerms.iterator(); iter.hasNext(); ) {
Term term = iter.next();
if ((fieldName == null) || (term.field().equals(fieldName))) {
- terms.add(new WeightedTerm(query.getBoost(), term.text()));
+ terms.add(new WeightedTerm(boost, term.text()));
}
}
}
@@ -152,12 +156,12 @@ public final class QueryTermExtractor
* something common which would allow access to child queries so what follows here are query-specific
* implementations for accessing embedded query elements.
*/
- private static final void getTermsFromBooleanQuery(BooleanQuery query, HashSet<WeightedTerm> terms, boolean prohibited, String fieldName)
+ private static final void getTermsFromBooleanQuery(BooleanQuery query, float boost, HashSet<WeightedTerm> terms, boolean prohibited, String fieldName)
{
for (BooleanClause clause : query)
{
if (prohibited || clause.getOccur()!=BooleanClause.Occur.MUST_NOT)
- getTerms(clause.getQuery(), terms, prohibited, fieldName);
+ getTerms(clause.getQuery(), boost, terms, prohibited, fieldName);
}
}
diff --git a/lucene/highlighter/src/java/org/apache/lucene/search/highlight/WeightedSpanTermExtractor.java b/lucene/highlighter/src/java/org/apache/lucene/search/highlight/WeightedSpanTermExtractor.java
index b6b991dd18d..8e8c8cb8637 100644
--- a/lucene/highlighter/src/java/org/apache/lucene/search/highlight/WeightedSpanTermExtractor.java
+++ b/lucene/highlighter/src/java/org/apache/lucene/search/highlight/WeightedSpanTermExtractor.java
@@ -35,6 +35,7 @@ import org.apache.lucene.queries.CommonTermsQuery;
import org.apache.lucene.queries.CustomScoreQuery;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.DisjunctionMaxQuery;
import org.apache.lucene.search.IndexSearcher;
@@ -103,11 +104,14 @@ public class WeightedSpanTermExtractor {
* Map to place created WeightedSpanTerms in
* @throws IOException If there is a low-level I/O error
*/
- protected void extract(Query query, Map<String,WeightedSpanTerm> terms) throws IOException {
- if (query instanceof BooleanQuery) {
+ protected void extract(Query query, float boost, Map<String,WeightedSpanTerm> terms) throws IOException {
+ if (query instanceof BoostQuery) {
+ BoostQuery boostQuery = (BoostQuery) query;
+ extract(boostQuery.getQuery(), boost * boostQuery.getBoost(), terms);
+ } else if (query instanceof BooleanQuery) {
for (BooleanClause clause : (BooleanQuery) query) {
if (!clause.isProhibited()) {
- extract(clause.getQuery(), terms);
+ extract(clause.getQuery(), boost, terms);
}
}
} else if (query instanceof PhraseQuery) {
@@ -144,29 +148,28 @@ public class WeightedSpanTermExtractor {
}
SpanNearQuery sp = new SpanNearQuery(clauses, slop, inorder);
- sp.setBoost(query.getBoost());
- extractWeightedSpanTerms(terms, sp);
+ extractWeightedSpanTerms(terms, sp, boost);
} else if (query instanceof TermQuery) {
- extractWeightedTerms(terms, query);
+ extractWeightedTerms(terms, query, boost);
} else if (query instanceof SpanQuery) {
- extractWeightedSpanTerms(terms, (SpanQuery) query);
+ extractWeightedSpanTerms(terms, (SpanQuery) query, boost);
} else if (query instanceof ConstantScoreQuery) {
final Query q = ((ConstantScoreQuery) query).getQuery();
if (q != null) {
- extract(q, terms);
+ extract(q, boost, terms);
}
} else if (query instanceof CommonTermsQuery) {
// specialized since rewriting would change the result query
// this query is TermContext sensitive.
- extractWeightedTerms(terms, query);
+ extractWeightedTerms(terms, query, boost);
} else if (query instanceof DisjunctionMaxQuery) {
for (Iterator<Query> iterator = ((DisjunctionMaxQuery) query).iterator(); iterator.hasNext();) {
- extract(iterator.next(), terms);
+ extract(iterator.next(), boost, terms);
}
} else if (query instanceof ToParentBlockJoinQuery) {
- extract(((ToParentBlockJoinQuery) query).getChildQuery(), terms);
+ extract(((ToParentBlockJoinQuery) query).getChildQuery(), boost, terms);
} else if (query instanceof ToChildBlockJoinQuery) {
- extract(((ToChildBlockJoinQuery) query).getParentQuery(), terms);
+ extract(((ToChildBlockJoinQuery) query).getParentQuery(), boost, terms);
} else if (query instanceof MultiPhraseQuery) {
final MultiPhraseQuery mpq = (MultiPhraseQuery) query;
final List<Term[]> termArrays = mpq.getTermArrays();
@@ -213,29 +216,28 @@ public class WeightedSpanTermExtractor {
final boolean inorder = (slop == 0);
SpanNearQuery sp = new SpanNearQuery(clauses, slop + positionGaps, inorder);
- sp.setBoost(query.getBoost());
- extractWeightedSpanTerms(terms, sp);
+ extractWeightedSpanTerms(terms, sp, boost);
}
} else if (query instanceof MatchAllDocsQuery) {
//nothing
} else if (query instanceof CustomScoreQuery){
- extract(((CustomScoreQuery) query).getSubQuery(), terms);
+ extract(((CustomScoreQuery) query).getSubQuery(), boost, terms);
} else {
Query origQuery = query;
+ final IndexReader reader = getLeafContext().reader();
+ Query rewritten;
if (query instanceof MultiTermQuery) {
if (!expandMultiTermQuery) {
return;
}
- MultiTermQuery copy = (MultiTermQuery) query.clone();
- copy.setRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_REWRITE);
- origQuery = copy;
+ rewritten = MultiTermQuery.SCORING_BOOLEAN_REWRITE.rewrite(reader, (MultiTermQuery) query);
+ } else {
+ rewritten = origQuery.rewrite(reader);
}
- final IndexReader reader = getLeafContext().reader();
- Query rewritten = origQuery.rewrite(reader);
if (rewritten != origQuery) {
// only rewrite once and then flatten again - the rewritten query could have a speacial treatment
// if this method is overwritten in a subclass or above in the next recursion
- extract(rewritten, terms);
+ extract(rewritten, boost, terms);
}
}
extractUnknownQuery(query, terms);
@@ -256,7 +258,7 @@ public class WeightedSpanTermExtractor {
* SpanQuery to extract Terms from
* @throws IOException If there is a low-level I/O error
*/
- protected void extractWeightedSpanTerms(Map<String,WeightedSpanTerm> terms, SpanQuery spanQuery) throws IOException {
+ protected void extractWeightedSpanTerms(Map<String,WeightedSpanTerm> terms, SpanQuery spanQuery, float boost) throws IOException {
Set<String> fieldNames;
if (fieldName == null) {
@@ -326,7 +328,7 @@ public class WeightedSpanTermExtractor {
WeightedSpanTerm weightedSpanTerm = terms.get(queryTerm.text());
if (weightedSpanTerm == null) {
- weightedSpanTerm = new WeightedSpanTerm(spanQuery.getBoost(), queryTerm.text());
+ weightedSpanTerm = new WeightedSpanTerm(boost, queryTerm.text());
weightedSpanTerm.addPositionSpans(spanPositions);
weightedSpanTerm.positionSensitive = true;
terms.put(queryTerm.text(), weightedSpanTerm);
@@ -348,7 +350,7 @@ public class WeightedSpanTermExtractor {
* Query to extract Terms from
* @throws IOException If there is a low-level I/O error
*/
- protected void extractWeightedTerms(Map<String,WeightedSpanTerm> terms, Query query) throws IOException {
+ protected void extractWeightedTerms(Map<String,WeightedSpanTerm> terms, Query query, float boost) throws IOException {
Set<Term> nonWeightedTerms = new HashSet<>();
final IndexSearcher searcher = new IndexSearcher(getLeafContext());
searcher.createNormalizedWeight(query, false).extractTerms(nonWeightedTerms);
@@ -356,7 +358,7 @@ public class WeightedSpanTermExtractor {
for (final Term queryTerm : nonWeightedTerms) {
if (fieldNameComparator(queryTerm.field())) {
- WeightedSpanTerm weightedSpanTerm = new WeightedSpanTerm(query.getBoost(), queryTerm.text());
+ WeightedSpanTerm weightedSpanTerm = new WeightedSpanTerm(boost, queryTerm.text());
terms.put(queryTerm.text(), weightedSpanTerm);
}
}
@@ -483,9 +485,9 @@ public class WeightedSpanTermExtractor {
* @return Map containing WeightedSpanTerms
* @throws IOException If there is a low-level I/O error
*/
- public Map<String,WeightedSpanTerm> getWeightedSpanTerms(Query query, TokenStream tokenStream)
+ public Map<String,WeightedSpanTerm> getWeightedSpanTerms(Query query, float boost, TokenStream tokenStream)
throws IOException {
- return getWeightedSpanTerms(query, tokenStream, null);
+ return getWeightedSpanTerms(query, boost, tokenStream, null);
}
/**
@@ -502,7 +504,7 @@ public class WeightedSpanTermExtractor {
* @return Map containing WeightedSpanTerms
* @throws IOException If there is a low-level I/O error
*/
- public Map<String,WeightedSpanTerm> getWeightedSpanTerms(Query query, TokenStream tokenStream,
+ public Map<String,WeightedSpanTerm> getWeightedSpanTerms(Query query, float boost, TokenStream tokenStream,
String fieldName) throws IOException {
if (fieldName != null) {
this.fieldName = fieldName;
@@ -513,7 +515,7 @@ public class WeightedSpanTermExtractor {
Map<String,WeightedSpanTerm> terms = new PositionCheckingMap<>();
this.tokenStream = tokenStream;
try {
- extract(query, terms);
+ extract(query, boost, terms);
} finally {
IOUtils.close(internalReader);
}
@@ -538,7 +540,7 @@ public class WeightedSpanTermExtractor {
* @return Map of WeightedSpanTerms with quasi tf/idf scores
* @throws IOException If there is a low-level I/O error
*/
- public Map<String,WeightedSpanTerm> getWeightedSpanTermsWithScores(Query query, TokenStream tokenStream, String fieldName,
+ public Map<String,WeightedSpanTerm> getWeightedSpanTermsWithScores(Query query, float boost, TokenStream tokenStream, String fieldName,
IndexReader reader) throws IOException {
if (fieldName != null) {
this.fieldName = fieldName;
@@ -548,7 +550,7 @@ public class WeightedSpanTermExtractor {
this.tokenStream = tokenStream;
Map<String,WeightedSpanTerm> terms = new PositionCheckingMap<>();
- extract(query, terms);
+ extract(query, boost, terms);
int totalNumDocs = reader.maxDoc();
Set<String> weightedTerms = terms.keySet();
diff --git a/lucene/highlighter/src/java/org/apache/lucene/search/vectorhighlight/FieldQuery.java b/lucene/highlighter/src/java/org/apache/lucene/search/vectorhighlight/FieldQuery.java
index 59f91da49e9..dc7c1a3e821 100644
--- a/lucene/highlighter/src/java/org/apache/lucene/search/vectorhighlight/FieldQuery.java
+++ b/lucene/highlighter/src/java/org/apache/lucene/search/vectorhighlight/FieldQuery.java
@@ -28,10 +28,10 @@ import java.util.Set;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
-import org.apache.lucene.queries.CommonTermsQuery;
import org.apache.lucene.queries.CustomScoreQuery;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.DisjunctionMaxQuery;
import org.apache.lucene.search.MultiTermQuery;
@@ -64,18 +64,24 @@ public class FieldQuery {
FieldQuery( Query query, IndexReader reader, boolean phraseHighlight, boolean fieldMatch ) throws IOException {
this.fieldMatch = fieldMatch;
Set<Query> flatQueries = new LinkedHashSet<>();
- flatten( query, reader, flatQueries );
+ flatten( query, reader, flatQueries, 1f );
saveTerms( flatQueries, reader );
Collection<Query> expandQueries = expand( flatQueries );
for( Query flatQuery : expandQueries ){
QueryPhraseMap rootMap = getRootMap( flatQuery );
rootMap.add( flatQuery, reader );
+ float boost = 1f;
+ while (flatQuery instanceof BoostQuery) {
+ BoostQuery bq = (BoostQuery) flatQuery;
+ flatQuery = bq.getQuery();
+ boost *= bq.getBoost();
+ }
if( !phraseHighlight && flatQuery instanceof PhraseQuery ){
PhraseQuery pq = (PhraseQuery)flatQuery;
if( pq.getTerms().length > 1 ){
for( Term term : pq.getTerms() )
- rootMap.addTerm( term, flatQuery.getBoost() );
+ rootMap.addTerm( term, boost );
}
}
}
@@ -88,75 +94,68 @@ public class FieldQuery {
this (query, null, phraseHighlight, fieldMatch);
}
- void flatten( Query sourceQuery, IndexReader reader, Collection<Query> flatQueries ) throws IOException{
+ void flatten( Query sourceQuery, IndexReader reader, Collection<Query> flatQueries, float boost ) throws IOException{
+ while (sourceQuery instanceof BoostQuery) {
+ BoostQuery bq = (BoostQuery) sourceQuery;
+ sourceQuery = bq.getQuery();
+ boost *= bq.getBoost();
+ }
if( sourceQuery instanceof BooleanQuery ){
BooleanQuery bq = (BooleanQuery)sourceQuery;
for( BooleanClause clause : bq ) {
if( !clause.isProhibited() ) {
- flatten( applyParentBoost( clause.getQuery(), bq ), reader, flatQueries );
+ flatten( clause.getQuery(), reader, flatQueries, boost );
}
}
} else if( sourceQuery instanceof DisjunctionMaxQuery ){
DisjunctionMaxQuery dmq = (DisjunctionMaxQuery)sourceQuery;
for( Query query : dmq ){
- flatten( applyParentBoost( query, dmq ), reader, flatQueries );
+ flatten( query, reader, flatQueries, boost );
}
}
else if( sourceQuery instanceof TermQuery ){
+ if (boost != 1f) {
+ sourceQuery = new BoostQuery(sourceQuery, boost);
+ }
if( !flatQueries.contains( sourceQuery ) )
flatQueries.add( sourceQuery );
}
else if( sourceQuery instanceof PhraseQuery ){
- if( !flatQueries.contains( sourceQuery ) ){
- PhraseQuery pq = (PhraseQuery)sourceQuery;
- if( pq.getTerms().length > 1 )
- flatQueries.add( pq );
- else if( pq.getTerms().length == 1 ){
- Query flat = new TermQuery( pq.getTerms()[0] );
- flat.setBoost( pq.getBoost() );
- flatQueries.add( flat );
- }
+ PhraseQuery pq = (PhraseQuery)sourceQuery;
+ if( pq.getTerms().length == 1 )
+ sourceQuery = new TermQuery( pq.getTerms()[0] );
+ if (boost != 1f) {
+ sourceQuery = new BoostQuery(sourceQuery, boost);
}
+ flatQueries.add(sourceQuery);
} else if (sourceQuery instanceof ConstantScoreQuery) {
final Query q = ((ConstantScoreQuery) sourceQuery).getQuery();
if (q != null) {
- flatten( applyParentBoost( q, sourceQuery ), reader, flatQueries);
+ flatten( q, reader, flatQueries, boost);
}
} else if (sourceQuery instanceof CustomScoreQuery) {
final Query q = ((CustomScoreQuery) sourceQuery).getSubQuery();
if (q != null) {
- flatten( applyParentBoost( q, sourceQuery ), reader, flatQueries);
+ flatten( q, reader, flatQueries, boost);
}
} else if (reader != null) {
Query query = sourceQuery;
+ Query rewritten;
if (sourceQuery instanceof MultiTermQuery) {
- MultiTermQuery copy = (MultiTermQuery) sourceQuery.clone();
- copy.setRewriteMethod(new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(MAX_MTQ_TERMS));
- query = copy;
+ rewritten = new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(MAX_MTQ_TERMS).rewrite(reader, (MultiTermQuery) query);
+ } else {
+ rewritten = query.rewrite(reader);
}
- Query rewritten = query.rewrite(reader);
if (rewritten != query) {
// only rewrite once and then flatten again - the rewritten query could have a speacial treatment
// if this method is overwritten in a subclass.
- flatten(rewritten, reader, flatQueries);
+ flatten(rewritten, reader, flatQueries, boost);
}
// if the query is already rewritten we discard it
}
// else discard queries
}
-
- /**
- * Push parent's boost into a clone of query if parent has a non 1 boost.
- */
- protected Query applyParentBoost( Query query, Query parent ) {
- if ( parent.getBoost() == 1 ) {
- return query;
- }
- Query cloned = query.clone();
- cloned.setBoost( query.getBoost() * parent.getBoost() );
- return cloned;
- }
/*
* Create expandQueries from flatQueries.
@@ -174,11 +173,23 @@ public class FieldQuery {
Query query = i.next();
i.remove();
expandQueries.add( query );
+ float queryBoost = 1f;
+ while (query instanceof BoostQuery) {
+ BoostQuery bq = (BoostQuery) query;
+ queryBoost *= bq.getBoost();
+ query = bq.getQuery();
+ }
if( !( query instanceof PhraseQuery ) ) continue;
for( Iterator<Query> j = flatQueries.iterator(); j.hasNext(); ){
Query qj = j.next();
+ float qjBoost = 1f;
+ while (qj instanceof BoostQuery) {
+ BoostQuery bq = (BoostQuery) qj;
+ qjBoost *= bq.getBoost();
+ qj = bq.getQuery();
+ }
if( !( qj instanceof PhraseQuery ) ) continue;
- checkOverlap( expandQueries, (PhraseQuery)query, (PhraseQuery)qj );
+ checkOverlap( expandQueries, (PhraseQuery)query, queryBoost, (PhraseQuery)qj, qjBoost );
}
}
return expandQueries;
@@ -191,13 +202,13 @@ public class FieldQuery {
* ex2) A="b c", B="a b" => overlap; expandQueries={"a b c"}
* ex3) A="a b", B="c d" => no overlap; expandQueries={}
*/
- private void checkOverlap( Collection<Query> expandQueries, PhraseQuery a, PhraseQuery b ){
+ private void checkOverlap( Collection<Query> expandQueries, PhraseQuery a, float aBoost, PhraseQuery b, float bBoost ){
if( a.getSlop() != b.getSlop() ) return;
Term[] ats = a.getTerms();
Term[] bts = b.getTerms();
if( fieldMatch && !ats[0].field().equals( bts[0].field() ) ) return;
- checkOverlap( expandQueries, ats, bts, a.getSlop(), a.getBoost() );
- checkOverlap( expandQueries, bts, ats, b.getSlop(), b.getBoost() );
+ checkOverlap( expandQueries, ats, bts, a.getSlop(), aBoost);
+ checkOverlap( expandQueries, bts, ats, b.getSlop(), bBoost );
}
/*
@@ -233,8 +244,10 @@ public class FieldQuery {
pqBuilder.add( new Term( src[0].field(), dest[k].text() ) );
}
pqBuilder.setSlop( slop );
- PhraseQuery pq = pqBuilder.build();
- pq.setBoost( boost );
+ Query pq = pqBuilder.build();
+ if (boost != 1f) {
+ pq = new BoostQuery(pq, 1f);
+ }
if(!expandQueries.contains( pq ) )
expandQueries.add( pq );
}
@@ -257,6 +270,9 @@ public class FieldQuery {
*/
private String getKey( Query query ){
if( !fieldMatch ) return null;
+ while (query instanceof BoostQuery) {
+ query = ((BoostQuery) query).getQuery();
+ }
if( query instanceof TermQuery )
return ((TermQuery)query).getTerm().field();
else if ( query instanceof PhraseQuery ){
@@ -293,8 +309,11 @@ public class FieldQuery {
* - fieldMatch==false
* termSetMap=Map<null,Set<"john","lennon">>
*/
- void saveTerms( Collection<Query> flatQueries, IndexReader reader ) throws IOException{
+ void saveTerms( Collection<Query> flatQueries, IndexReader reader ) throws IOException{
for( Query query : flatQueries ){
+ while (query instanceof BoostQuery) {
+ query = ((BoostQuery) query).getQuery();
+ }
Set<String> termSet = getTermSet( query );
if( query instanceof TermQuery )
termSet.add( ((TermQuery)query).getTerm().text() );
@@ -385,9 +404,15 @@ public class FieldQuery {
return map;
}
- void add( Query query, IndexReader reader ) {
+ void add( Query query, IndexReader reader ) {
+ float boost = 1f;
+ while (query instanceof BoostQuery) {
+ BoostQuery bq = (BoostQuery) query;
+ query = bq.getQuery();
+ boost = bq.getBoost();
+ }
if( query instanceof TermQuery ){
- addTerm( ((TermQuery)query).getTerm(), query.getBoost() );
+ addTerm( ((TermQuery)query).getTerm(), boost );
}
else if( query instanceof PhraseQuery ){
PhraseQuery pq = (PhraseQuery)query;
@@ -398,7 +423,7 @@ public class FieldQuery {
qpm = getOrNewMap( map, term.text() );
map = qpm.subMap;
}
- qpm.markTerminal( pq.getSlop(), pq.getBoost() );
+ qpm.markTerminal( pq.getSlop(), boost );
}
else
throw new RuntimeException( "query \"" + query.toString() + "\" must be flatten first." );
diff --git a/lucene/highlighter/src/test/org/apache/lucene/search/highlight/custom/HighlightCustomQueryTest.java b/lucene/highlighter/src/test/org/apache/lucene/search/highlight/custom/HighlightCustomQueryTest.java
index a52d9b77f06..a494e9e7732 100644
--- a/lucene/highlighter/src/test/org/apache/lucene/search/highlight/custom/HighlightCustomQueryTest.java
+++ b/lucene/highlighter/src/test/org/apache/lucene/search/highlight/custom/HighlightCustomQueryTest.java
@@ -22,6 +22,7 @@ import org.apache.lucene.analysis.MockTokenizer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.highlight.Highlighter;
@@ -114,8 +115,14 @@ public class HighlightCustomQueryTest extends LuceneTestCase {
@Override
protected void extractUnknownQuery(Query query,
Map<String, WeightedSpanTerm> terms) throws IOException {
+ float boost = 1f;
+ while (query instanceof BoostQuery) {
+ BoostQuery bq = (BoostQuery) query;
+ boost *= bq.getBoost();
+ query = bq.getQuery();
+ }
if (query instanceof CustomQuery) {
- extractWeightedTerms(terms, new TermQuery(((CustomQuery) query).term));
+ extractWeightedTerms(terms, new TermQuery(((CustomQuery) query).term), boost);
}
}
diff --git a/lucene/highlighter/src/test/org/apache/lucene/search/vectorhighlight/AbstractTestCase.java b/lucene/highlighter/src/test/org/apache/lucene/search/vectorhighlight/AbstractTestCase.java
index 2927c143186..67f0ab62f24 100644
--- a/lucene/highlighter/src/test/org/apache/lucene/search/vectorhighlight/AbstractTestCase.java
+++ b/lucene/highlighter/src/test/org/apache/lucene/search/vectorhighlight/AbstractTestCase.java
@@ -36,6 +36,7 @@ import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.DisjunctionMaxQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.Query;
@@ -113,7 +114,9 @@ public abstract class AbstractTestCase extends LuceneTestCase {
protected Query tq( float boost, String field, String text ){
Query query = new TermQuery( new Term( field, text ) );
- query.setBoost( boost );
+ if (boost != 1f) {
+ query = new BoostQuery( query, boost );
+ }
return query;
}
@@ -138,8 +141,10 @@ public abstract class AbstractTestCase extends LuceneTestCase {
}
protected Query pq( float boost, int slop, String field, String... texts ){
- PhraseQuery query = new PhraseQuery(slop, field, texts);
- query.setBoost( boost );
+ Query query = new PhraseQuery(slop, field, texts);
+ if (boost != 1f) {
+ query = new BoostQuery(query, boost);
+ }
return query;
}
diff --git a/lucene/highlighter/src/test/org/apache/lucene/search/vectorhighlight/FastVectorHighlighterTest.java b/lucene/highlighter/src/test/org/apache/lucene/search/vectorhighlight/FastVectorHighlighterTest.java
index 13ffeb5206d..e7d5368fec8 100644
--- a/lucene/highlighter/src/test/org/apache/lucene/search/vectorhighlight/FastVectorHighlighterTest.java
+++ b/lucene/highlighter/src/test/org/apache/lucene/search/vectorhighlight/FastVectorHighlighterTest.java
@@ -42,6 +42,7 @@ import org.apache.lucene.queries.CustomScoreQuery;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.Query;
@@ -305,7 +306,7 @@ public class FastVectorHighlighterTest extends LuceneTestCase {
BooleanQuery.Builder phraseB = new BooleanQuery.Builder();
phraseB.add( clause( "text", "highlight", "words", "together" ), Occur.MUST );
Query phrase = phraseB.build();
- phrase.setBoost( 100 );
+ phrase = new BoostQuery(phrase, 100f);
// Now combine those results in a boolean query which should pull the phrases to the front of the list of fragments
BooleanQuery.Builder query = new BooleanQuery.Builder();
query.add( phrase, Occur.MUST );
@@ -733,7 +734,7 @@ public class FastVectorHighlighterTest extends LuceneTestCase {
} else {
q = new PhraseQuery(field, terms);
}
- q.setBoost( boost );
+ q = new BoostQuery( q, boost );
return q;
}
diff --git a/lucene/highlighter/src/test/org/apache/lucene/search/vectorhighlight/FieldQueryTest.java b/lucene/highlighter/src/test/org/apache/lucene/search/vectorhighlight/FieldQueryTest.java
index fba2858cb20..32d881f1104 100644
--- a/lucene/highlighter/src/test/org/apache/lucene/search/vectorhighlight/FieldQueryTest.java
+++ b/lucene/highlighter/src/test/org/apache/lucene/search/vectorhighlight/FieldQueryTest.java
@@ -27,6 +27,7 @@ import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.Filter;
@@ -63,22 +64,22 @@ public class FieldQueryTest extends AbstractTestCase {
innerQuery.add(tq("E"), Occur.MUST);
booleanQueryB.add(innerQuery.build(), Occur.MUST_NOT);
- BooleanQuery booleanQuery = booleanQueryB.build();
- booleanQuery.setBoost(boost);
+ Query booleanQuery = booleanQueryB.build();
+ booleanQuery = new BoostQuery(booleanQuery, boost);
FieldQuery fq = new FieldQuery(booleanQuery, true, true );
Set<Query> flatQueries = new HashSet<>();
- fq.flatten(booleanQuery, reader, flatQueries);
+ fq.flatten(booleanQuery, reader, flatQueries, 1f);
assertCollectionQueries( flatQueries, tq( boost, "A" ), tq( boost, "B" ), tq( boost, "C" ) );
}
public void testFlattenDisjunctionMaxQuery() throws Exception {
initBoost();
Query query = dmq( tq( "A" ), tq( "B" ), pqF( "C", "D" ) );
- query.setBoost( boost );
+ query = new BoostQuery( query, boost );
FieldQuery fq = new FieldQuery( query, true, true );
Set<Query> flatQueries = new HashSet<>();
- fq.flatten( query, reader, flatQueries );
+ fq.flatten( query, reader, flatQueries, 1f );
assertCollectionQueries( flatQueries, tq( boost, "A" ), tq( boost, "B" ), pqF( boost, "C", "D" ) );
}
@@ -87,12 +88,12 @@ public class FieldQueryTest extends AbstractTestCase {
BooleanQuery.Builder booleanQueryB = new BooleanQuery.Builder();
booleanQueryB.add(tq("A"), Occur.MUST);
booleanQueryB.add(pqF("B", "C"), Occur.MUST);
- BooleanQuery booleanQuery = booleanQueryB.build();
- booleanQuery.setBoost(boost);
+ Query booleanQuery = booleanQueryB.build();
+ booleanQuery = new BoostQuery(booleanQuery, boost);
FieldQuery fq = new FieldQuery(booleanQuery, true, true );
Set<Query> flatQueries = new HashSet<>();
- fq.flatten(booleanQuery, reader, flatQueries);
+ fq.flatten(booleanQuery, reader, flatQueries, 1f);
assertCollectionQueries( flatQueries, tq( boost, "A" ), pqF( boost, "B", "C" ) );
}
@@ -104,7 +105,7 @@ public class FieldQueryTest extends AbstractTestCase {
FieldQuery fq = new FieldQuery( query.build(), true, true );
Set<Query> flatQueries = new HashSet<>();
- fq.flatten( query.build(), reader, flatQueries );
+ fq.flatten( query.build(), reader, flatQueries, 1f );
assertCollectionQueries( flatQueries, tq( "AA" ), pqF( "BC", "CD" ), pqF( "EF", "FG", "GH" ) );
}
@@ -112,7 +113,7 @@ public class FieldQueryTest extends AbstractTestCase {
Query query = pqF( "A" );
FieldQuery fq = new FieldQuery( query, true, true );
Set<Query> flatQueries = new HashSet<>();
- fq.flatten( query, reader, flatQueries );
+ fq.flatten( query, reader, flatQueries, 1f );
assertCollectionQueries( flatQueries, tq( "A" ) );
}
@@ -954,20 +955,20 @@ public class FieldQueryTest extends AbstractTestCase {
.add(pqF( "A" ), Occur.MUST)
.add(filter, Occur.FILTER)
.build();
- query.setBoost(boost);
+ query = new BoostQuery(query, boost);
FieldQuery fq = new FieldQuery( query, true, true );
Set<Query> flatQueries = new HashSet<>();
- fq.flatten( query, reader, flatQueries );
+ fq.flatten( query, reader, flatQueries, 1f );
assertCollectionQueries( flatQueries, tq( boost, "A" ) );
}
public void testFlattenConstantScoreQuery() throws Exception {
initBoost();
Query query = new ConstantScoreQuery(pqF( "A" ));
- query.setBoost(boost);
+ query = new BoostQuery(query, boost);
FieldQuery fq = new FieldQuery( query, true, true );
Set<Query> flatQueries = new HashSet<>();
- fq.flatten( query, reader, flatQueries );
+ fq.flatten( query, reader, flatQueries, 1f );
assertCollectionQueries( flatQueries, tq( boost, "A" ) );
}
diff --git a/lucene/join/src/java/org/apache/lucene/search/join/GlobalOrdinalsQuery.java b/lucene/join/src/java/org/apache/lucene/search/join/GlobalOrdinalsQuery.java
index a98b55ff1bc..366932b781a 100644
--- a/lucene/join/src/java/org/apache/lucene/search/join/GlobalOrdinalsQuery.java
+++ b/lucene/join/src/java/org/apache/lucene/search/join/GlobalOrdinalsQuery.java
@@ -26,6 +26,7 @@ import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.MultiDocValues;
import org.apache.lucene.index.SortedDocValues;
import org.apache.lucene.index.Term;
+import org.apache.lucene.search.ConstantScoreWeight;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.IndexSearcher;
@@ -97,13 +98,10 @@ final class GlobalOrdinalsQuery extends Query {
'}';
}
- final class W extends Weight {
+ final class W extends ConstantScoreWeight {
private final Weight approximationWeight;
- private float queryNorm;
- private float queryWeight;
-
W(Query query, Weight approximationWeight) {
super(query);
this.approximationWeight = approximationWeight;
@@ -119,24 +117,12 @@ final class GlobalOrdinalsQuery extends Query {
int segmentOrd = values.getOrd(doc);
if (segmentOrd != -1) {
BytesRef joinValue = values.lookupOrd(segmentOrd);
- return Explanation.match(queryNorm, "Score based on join value " + joinValue.utf8ToString());
+ return Explanation.match(score(), "Score based on join value " + joinValue.utf8ToString());
}
}
return Explanation.noMatch("Not a match");
}
- @Override
- public float getValueForNormalization() throws IOException {
- queryWeight = getBoost();
- return queryWeight * queryWeight;
- }
-
- @Override
- public void normalize(float norm, float topLevelBoost) {
- this.queryNorm = norm * topLevelBoost;
- queryWeight *= this.queryNorm;
- }
-
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
SortedDocValues values = DocValues.getSorted(context.reader(), joinField);
@@ -149,9 +135,9 @@ final class GlobalOrdinalsQuery extends Query {
return null;
}
if (globalOrds != null) {
- return new OrdinalMapScorer(this, queryNorm, foundOrds, values, approximationScorer, globalOrds.getGlobalOrds(context.ord));
+ return new OrdinalMapScorer(this, score(), foundOrds, values, approximationScorer, globalOrds.getGlobalOrds(context.ord));
} {
- return new SegmentOrdinalScorer(this, queryNorm, foundOrds, values, approximationScorer);
+ return new SegmentOrdinalScorer(this, score(), foundOrds, values, approximationScorer);
}
}
diff --git a/lucene/join/src/java/org/apache/lucene/search/join/GlobalOrdinalsWithScoreQuery.java b/lucene/join/src/java/org/apache/lucene/search/join/GlobalOrdinalsWithScoreQuery.java
index b0186d8572b..385b302c91b 100644
--- a/lucene/join/src/java/org/apache/lucene/search/join/GlobalOrdinalsWithScoreQuery.java
+++ b/lucene/join/src/java/org/apache/lucene/search/join/GlobalOrdinalsWithScoreQuery.java
@@ -30,7 +30,6 @@ import org.apache.lucene.search.Query;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.TwoPhaseIterator;
import org.apache.lucene.search.Weight;
-import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LongValues;
@@ -111,9 +110,6 @@ final class GlobalOrdinalsWithScoreQuery extends Query {
private final Weight approximationWeight;
- private float queryNorm;
- private float queryWeight;
-
W(Query query, Weight approximationWeight) {
super(query);
this.approximationWeight = approximationWeight;
@@ -144,14 +140,13 @@ final class GlobalOrdinalsWithScoreQuery extends Query {
@Override
public float getValueForNormalization() throws IOException {
- queryWeight = getBoost();
- return queryWeight * queryWeight;
+ return 1f;
}
@Override
- public void normalize(float norm, float topLevelBoost) {
- this.queryNorm = norm * topLevelBoost;
- queryWeight *= this.queryNorm;
+ public void normalize(float norm, float boost) {
+ // no normalization, we ignore the normalization process
+ // and produce scores based on the join
}
@Override
diff --git a/lucene/join/src/java/org/apache/lucene/search/join/TermsIncludingScoreQuery.java b/lucene/join/src/java/org/apache/lucene/search/join/TermsIncludingScoreQuery.java
index 0b38e0618dd..8ff17c6610a 100644
--- a/lucene/join/src/java/org/apache/lucene/search/join/TermsIncludingScoreQuery.java
+++ b/lucene/join/src/java/org/apache/lucene/search/join/TermsIncludingScoreQuery.java
@@ -34,7 +34,6 @@ import org.apache.lucene.search.Query;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.Weight;
import org.apache.lucene.util.BitSetIterator;
-import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefHash;
import org.apache.lucene.util.FixedBitSet;
@@ -78,12 +77,10 @@ class TermsIncludingScoreQuery extends Query {
public Query rewrite(IndexReader reader) throws IOException {
final Query originalQueryRewrite = originalQuery.rewrite(reader);
if (originalQueryRewrite != originalQuery) {
- Query rewritten = new TermsIncludingScoreQuery(field, multipleValuesPerDocument, terms, scores,
+ return new TermsIncludingScoreQuery(field, multipleValuesPerDocument, terms, scores,
ords, originalQueryRewrite, originalQuery);
- rewritten.setBoost(getBoost());
- return rewritten;
} else {
- return this;
+ return super.rewrite(reader);
}
}
@@ -146,12 +143,12 @@ class TermsIncludingScoreQuery extends Query {
@Override
public float getValueForNormalization() throws IOException {
- return originalWeight.getValueForNormalization() * TermsIncludingScoreQuery.this.getBoost() * TermsIncludingScoreQuery.this.getBoost();
+ return originalWeight.getValueForNormalization();
}
@Override
- public void normalize(float norm, float topLevelBoost) {
- originalWeight.normalize(norm, topLevelBoost * TermsIncludingScoreQuery.this.getBoost());
+ public void normalize(float norm, float boost) {
+ originalWeight.normalize(norm, boost);
}
@Override
diff --git a/lucene/join/src/java/org/apache/lucene/search/join/ToChildBlockJoinQuery.java b/lucene/join/src/java/org/apache/lucene/search/join/ToChildBlockJoinQuery.java
index 6e0d39e2031..efba048c991 100644
--- a/lucene/join/src/java/org/apache/lucene/search/join/ToChildBlockJoinQuery.java
+++ b/lucene/join/src/java/org/apache/lucene/search/join/ToChildBlockJoinQuery.java
@@ -91,14 +91,12 @@ public class ToChildBlockJoinQuery extends Query {
}
private static class ToChildBlockJoinWeight extends Weight {
- private final Query joinQuery;
private final Weight parentWeight;
private final BitSetProducer parentsFilter;
private final boolean doScores;
public ToChildBlockJoinWeight(Query joinQuery, Weight parentWeight, BitSetProducer parentsFilter, boolean doScores) {
super(joinQuery);
- this.joinQuery = joinQuery;
this.parentWeight = parentWeight;
this.parentsFilter = parentsFilter;
this.doScores = doScores;
@@ -109,12 +107,12 @@ public class ToChildBlockJoinQuery extends Query {
@Override
public float getValueForNormalization() throws IOException {
- return parentWeight.getValueForNormalization() * joinQuery.getBoost() * joinQuery.getBoost();
+ return parentWeight.getValueForNormalization();
}
@Override
- public void normalize(float norm, float topLevelBoost) {
- parentWeight.normalize(norm, topLevelBoost * joinQuery.getBoost());
+ public void normalize(float norm, float boost) {
+ parentWeight.normalize(norm, boost);
}
// NOTE: acceptDocs applies (and is checked) only in the
@@ -317,13 +315,11 @@ public class ToChildBlockJoinQuery extends Query {
public Query rewrite(IndexReader reader) throws IOException {
final Query parentRewrite = parentQuery.rewrite(reader);
if (parentRewrite != parentQuery) {
- Query rewritten = new ToChildBlockJoinQuery(parentQuery,
+ return new ToChildBlockJoinQuery(parentQuery,
parentRewrite,
parentsFilter);
- rewritten.setBoost(getBoost());
- return rewritten;
} else {
- return this;
+ return super.rewrite(reader);
}
}
@@ -352,10 +348,4 @@ public class ToChildBlockJoinQuery extends Query {
hash = prime * hash + parentsFilter.hashCode();
return hash;
}
-
- @Override
- public ToChildBlockJoinQuery clone() {
- return new ToChildBlockJoinQuery(origParentQuery.clone(),
- parentsFilter);
- }
}
diff --git a/lucene/join/src/java/org/apache/lucene/search/join/ToParentBlockJoinQuery.java b/lucene/join/src/java/org/apache/lucene/search/join/ToParentBlockJoinQuery.java
index 8d4d093c34c..ed555c91937 100644
--- a/lucene/join/src/java/org/apache/lucene/search/join/ToParentBlockJoinQuery.java
+++ b/lucene/join/src/java/org/apache/lucene/search/join/ToParentBlockJoinQuery.java
@@ -144,12 +144,12 @@ public class ToParentBlockJoinQuery extends Query {
@Override
public float getValueForNormalization() throws IOException {
- return childWeight.getValueForNormalization() * joinQuery.getBoost() * joinQuery.getBoost();
+ return childWeight.getValueForNormalization();
}
@Override
- public void normalize(float norm, float topLevelBoost) {
- childWeight.normalize(norm, topLevelBoost * joinQuery.getBoost());
+ public void normalize(float norm, float boost) {
+ childWeight.normalize(norm, boost);
}
// NOTE: acceptDocs applies (and is checked) only in the
@@ -413,14 +413,12 @@ public class ToParentBlockJoinQuery extends Query {
public Query rewrite(IndexReader reader) throws IOException {
final Query childRewrite = childQuery.rewrite(reader);
if (childRewrite != childQuery) {
- Query rewritten = new ToParentBlockJoinQuery(origChildQuery,
+ return new ToParentBlockJoinQuery(origChildQuery,
childRewrite,
parentsFilter,
scoreMode);
- rewritten.setBoost(getBoost());
- return rewritten;
} else {
- return this;
+ return super.rewrite(reader);
}
}
diff --git a/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoin.java b/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoin.java
index 52a2ed4e4bf..70fa6b0e18e 100644
--- a/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoin.java
+++ b/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoin.java
@@ -49,6 +49,7 @@ import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.FieldDoc;
@@ -441,8 +442,7 @@ public class TestBlockJoin extends LuceneTestCase {
BooleanQuery.Builder bqB = new BooleanQuery.Builder();
bqB.add(q, BooleanClause.Occur.MUST);
BooleanQuery bq = bqB.build();
- bq.setBoost(2f);
- s.search(bq, 10);
+ s.search(new BoostQuery(bq, 2f), 10);
r.close();
dir.close();
}
diff --git a/lucene/misc/src/test/org/apache/lucene/index/SorterTestBase.java b/lucene/misc/src/test/org/apache/lucene/index/SorterTestBase.java
index 4f59208de85..4d15644abeb 100644
--- a/lucene/misc/src/test/org/apache/lucene/index/SorterTestBase.java
+++ b/lucene/misc/src/test/org/apache/lucene/index/SorterTestBase.java
@@ -76,8 +76,8 @@ public abstract class SorterTestBase extends LuceneTestCase {
}
@Override
- public SimWeight computeWeight(float queryBoost, CollectionStatistics collectionStats, TermStatistics... termStats) {
- return in.computeWeight(queryBoost, collectionStats, termStats);
+ public SimWeight computeWeight(CollectionStatistics collectionStats, TermStatistics... termStats) {
+ return in.computeWeight(collectionStats, termStats);
}
@Override
diff --git a/lucene/misc/src/test/org/apache/lucene/search/TestDiversifiedTopDocsCollector.java b/lucene/misc/src/test/org/apache/lucene/search/TestDiversifiedTopDocsCollector.java
index 7eab069eaf1..853ccb2a303 100644
--- a/lucene/misc/src/test/org/apache/lucene/search/TestDiversifiedTopDocsCollector.java
+++ b/lucene/misc/src/test/org/apache/lucene/search/TestDiversifiedTopDocsCollector.java
@@ -423,9 +423,9 @@ public class TestDiversifiedTopDocsCollector extends LuceneTestCase {
}
@Override
- public SimWeight computeWeight(float queryBoost,
+ public SimWeight computeWeight(
CollectionStatistics collectionStats, TermStatistics... termStats) {
- return sim.computeWeight(queryBoost, collectionStats, termStats);
+ return sim.computeWeight(collectionStats, termStats);
}
@Override
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/BoostingQuery.java b/lucene/queries/src/java/org/apache/lucene/queries/BoostingQuery.java
index 43389d55ea9..7886e25970f 100644
--- a/lucene/queries/src/java/org/apache/lucene/queries/BoostingQuery.java
+++ b/lucene/queries/src/java/org/apache/lucene/queries/BoostingQuery.java
@@ -49,9 +49,8 @@ public class BoostingQuery extends Query {
public BoostingQuery(Query match, Query context, float boost) {
this.match = match;
- this.context = context.clone(); // clone before boost
+ this.context = context; // ignore context-only matches
this.boost = boost;
- this.context.setBoost(0.0f); // ignore context-only matches
}
@Override
@@ -59,9 +58,7 @@ public class BoostingQuery extends Query {
Query matchRewritten = match.rewrite(reader);
Query contextRewritten = context.rewrite(reader);
if (match != matchRewritten || context != contextRewritten) {
- BoostingQuery rewritten = new BoostingQuery(matchRewritten, contextRewritten, boost);
- rewritten.setBoost(getBoost());
- return rewritten;
+ return new BoostingQuery(matchRewritten, contextRewritten, boost);
}
return super.rewrite(reader);
}
@@ -101,8 +98,8 @@ public class BoostingQuery extends Query {
}
@Override
- public void normalize(float norm, float topLevelBoost) {
- matchWeight.normalize(norm, topLevelBoost);
+ public void normalize(float norm, float boost) {
+ matchWeight.normalize(norm, boost);
}
@Override
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/CommonTermsQuery.java b/lucene/queries/src/java/org/apache/lucene/queries/CommonTermsQuery.java
index 64396e0bb78..6dcae008d2f 100644
--- a/lucene/queries/src/java/org/apache/lucene/queries/CommonTermsQuery.java
+++ b/lucene/queries/src/java/org/apache/lucene/queries/CommonTermsQuery.java
@@ -29,11 +29,11 @@ import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.MatchNoDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.similarities.Similarity;
-import org.apache.lucene.util.ToStringUtils;
/**
* A query that executes high-frequency terms in a optional sub-query to prevent
@@ -148,9 +148,7 @@ public class CommonTermsQuery extends Query {
if (this.terms.isEmpty()) {
return new MatchNoDocsQuery();
} else if (this.terms.size() == 1) {
- final Query tq = newTermQuery(this.terms.get(0), null);
- tq.setBoost(getBoost());
- return tq;
+ return newTermQuery(this.terms.get(0), null);
}
final List<LeafReaderContext> leaves = reader.leaves();
final int maxDoc = reader.maxDoc();
@@ -226,8 +224,7 @@ public class CommonTermsQuery extends Query {
}
lowFreq.setMinimumNumberShouldMatch(lowFreqMinShouldMatch);
Query lowFreqQuery = lowFreq.build();
- lowFreqQuery.setBoost(lowFreqBoost);
- builder.add(lowFreqQuery, Occur.MUST);
+ builder.add(new BoostQuery(lowFreqQuery, lowFreqBoost), Occur.MUST);
}
if (highFreqQueries.isEmpty() == false) {
BooleanQuery.Builder highFreq = new BooleanQuery.Builder();
@@ -237,12 +234,9 @@ public class CommonTermsQuery extends Query {
}
highFreq.setMinimumNumberShouldMatch(highFreqMinShouldMatch);
Query highFreqQuery = highFreq.build();
- highFreqQuery.setBoost(highFreqBoost);
- builder.add(highFreqQuery, Occur.SHOULD);
+ builder.add(new BoostQuery(highFreqQuery, highFreqBoost), Occur.SHOULD);
}
- Query rewritten = builder.build();
- rewritten.setBoost(getBoost());
- return rewritten;
+ return builder.build();
}
public void collectTermContext(IndexReader reader,
@@ -347,8 +341,7 @@ public class CommonTermsQuery extends Query {
@Override
public String toString(String field) {
StringBuilder buffer = new StringBuilder();
- boolean needParens = (getBoost() != 1.0)
- || (getLowFreqMinimumNumberShouldMatch() > 0);
+ boolean needParens = (getLowFreqMinimumNumberShouldMatch() > 0);
if (needParens) {
buffer.append("(");
}
@@ -368,9 +361,6 @@ public class CommonTermsQuery extends Query {
buffer.append(getHighFreqMinimumNumberShouldMatch());
buffer.append(")");
}
- if (getBoost() != 1.0f) {
- buffer.append(ToStringUtils.boost(getBoost()));
- }
return buffer.toString();
}
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/CustomScoreQuery.java b/lucene/queries/src/java/org/apache/lucene/queries/CustomScoreQuery.java
index 5962351ca22..871da22862c 100644
--- a/lucene/queries/src/java/org/apache/lucene/queries/CustomScoreQuery.java
+++ b/lucene/queries/src/java/org/apache/lucene/queries/CustomScoreQuery.java
@@ -34,8 +34,6 @@ import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.Weight;
-import org.apache.lucene.util.Bits;
-import org.apache.lucene.util.ToStringUtils;
/**
* Query that sets document score as a programmatic function of several (sub) scores:
@@ -47,7 +45,7 @@ import org.apache.lucene.util.ToStringUtils;
*
* @lucene.experimental
*/
-public class CustomScoreQuery extends Query {
+public class CustomScoreQuery extends Query implements Cloneable {
private Query subQuery;
private Query[] scoringQueries; // never null (empty array if there are no valSrcQueries).
@@ -110,11 +108,17 @@ public class CustomScoreQuery extends Query {
/*(non-Javadoc) @see org.apache.lucene.search.Query#clone() */
@Override
public CustomScoreQuery clone() {
- CustomScoreQuery clone = (CustomScoreQuery)super.clone();
- clone.subQuery = subQuery.clone();
+ CustomScoreQuery clone;
+ try {
+ clone = (CustomScoreQuery)super.clone();
+ } catch (CloneNotSupportedException bogus) {
+ // cannot happen
+ throw new Error(bogus);
+ }
+ clone.subQuery = subQuery;
clone.scoringQueries = new Query[scoringQueries.length];
for(int i = 0; i < scoringQueries.length; i++) {
- clone.scoringQueries[i] = scoringQueries[i].clone();
+ clone.scoringQueries[i] = scoringQueries[i];
}
return clone;
}
@@ -129,7 +133,7 @@ public class CustomScoreQuery extends Query {
}
sb.append(")");
sb.append(strict?" STRICT" : "");
- return sb.toString() + ToStringUtils.boost(getBoost());
+ return sb.toString();
}
/** Returns true if <code>o</code> is equal to this. */
@@ -139,12 +143,8 @@ public class CustomScoreQuery extends Query {
return true;
if (!super.equals(o))
return false;
- if (getClass() != o.getClass()) {
- return false;
- }
CustomScoreQuery other = (CustomScoreQuery)o;
- if (this.getBoost() != other.getBoost() ||
- !this.subQuery.equals(other.subQuery) ||
+ if (!this.subQuery.equals(other.subQuery) ||
this.strict != other.strict ||
this.scoringQueries.length != other.scoringQueries.length) {
return false;
@@ -156,7 +156,7 @@ public class CustomScoreQuery extends Query {
@Override
public int hashCode() {
return (getClass().hashCode() + subQuery.hashCode() + Arrays.hashCode(scoringQueries))
- ^ Float.floatToIntBits(getBoost()) ^ (strict ? 1234 : 4321);
+ ^ (strict ? 1234 : 4321);
}
/**
@@ -199,9 +199,7 @@ public class CustomScoreQuery extends Query {
public float getValueForNormalization() throws IOException {
float sum = subQueryWeight.getValueForNormalization();
for (Weight valSrcWeight : valSrcWeights) {
- if (qStrict) {
- valSrcWeight.getValueForNormalization(); // do not include ValueSource part in the query normalization
- } else {
+ if (qStrict == false) { // otherwise do not include ValueSource part in the query normalization
sum += valSrcWeight.getValueForNormalization();
}
}
@@ -210,8 +208,8 @@ public class CustomScoreQuery extends Query {
/*(non-Javadoc) @see org.apache.lucene.search.Weight#normalize(float) */
@Override
- public void normalize(float norm, float topLevelBoost) {
- // note we DONT incorporate our boost, nor pass down any topLevelBoost
+ public void normalize(float norm, float boost) {
+ // note we DONT incorporate our boost, nor pass down any boost
// (e.g. from outer BQ), as there is no guarantee that the CustomScoreProvider's
// function obeys the distributive law... it might call sqrt() on the subQuery score
// or some other arbitrary function other than multiplication.
@@ -224,7 +222,7 @@ public class CustomScoreQuery extends Query {
valSrcWeight.normalize(norm, 1f);
}
}
- queryWeight = topLevelBoost * getBoost();
+ queryWeight = boost;
}
@Override
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/TermsQuery.java b/lucene/queries/src/java/org/apache/lucene/queries/TermsQuery.java
index d307a43d4d5..19484cebc57 100644
--- a/lucene/queries/src/java/org/apache/lucene/queries/TermsQuery.java
+++ b/lucene/queries/src/java/org/apache/lucene/queries/TermsQuery.java
@@ -56,7 +56,6 @@ import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.DocIdSetBuilder;
import org.apache.lucene.util.RamUsageEstimator;
-import org.apache.lucene.util.ToStringUtils;
/**
* Specialization for a disjunction over many terms that behaves like a
@@ -149,9 +148,7 @@ public class TermsQuery extends Query implements Accountable {
for (BytesRef term = iterator.next(); term != null; term = iterator.next()) {
bq.add(new TermQuery(new Term(iterator.field(), BytesRef.deepCopyOf(term))), Occur.SHOULD);
}
- ConstantScoreQuery csq = new ConstantScoreQuery(bq.build());
- csq.setBoost(getBoost());
- return csq;
+ return new ConstantScoreQuery(bq.build());
}
return super.rewrite(reader);
}
@@ -188,7 +185,6 @@ public class TermsQuery extends Query implements Accountable {
builder.append(iterator.field()).append(':');
builder.append(term.utf8ToString());
}
- builder.append(ToStringUtils.boost(getBoost()));
return builder.toString();
}
@@ -309,8 +305,9 @@ public class TermsQuery extends Query implements Accountable {
bq.add(new TermQuery(new Term(t.field, t.term), termContext), Occur.SHOULD);
}
Query q = new ConstantScoreQuery(bq.build());
- q.setBoost(score());
- return new WeightOrDocIdSet(searcher.rewrite(q).createWeight(searcher, needsScores));
+ final Weight weight = searcher.rewrite(q).createWeight(searcher, needsScores);
+ weight.normalize(1f, score());
+ return new WeightOrDocIdSet(weight);
} else {
assert builder != null;
return new WeightOrDocIdSet(builder.build());
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/function/BoostedQuery.java b/lucene/queries/src/java/org/apache/lucene/queries/function/BoostedQuery.java
index cf4fbf05017..ea126a28fdc 100644
--- a/lucene/queries/src/java/org/apache/lucene/queries/function/BoostedQuery.java
+++ b/lucene/queries/src/java/org/apache/lucene/queries/function/BoostedQuery.java
@@ -39,8 +39,8 @@ import org.apache.lucene.util.ToStringUtils;
*/
// TODO: BoostedQuery and BoostingQuery in the same module?
// something has to give
-public class BoostedQuery extends Query {
- private Query q;
+public final class BoostedQuery extends Query {
+ private final Query q;
private final ValueSource boostVal; // optional, can be null
public BoostedQuery(Query subQuery, ValueSource boostVal) {
@@ -54,10 +54,10 @@ public class BoostedQuery extends Query {
@Override
public Query rewrite(IndexReader reader) throws IOException {
Query newQ = q.rewrite(reader);
- if (newQ == q) return this;
- BoostedQuery bq = (BoostedQuery)this.clone();
- bq.q = newQ;
- return bq;
+ if (newQ != q) {
+ return new BoostedQuery(newQ, boostVal);
+ }
+ return super.rewrite(reader);
}
@Override
@@ -66,13 +66,11 @@ public class BoostedQuery extends Query {
}
private class BoostedWeight extends Weight {
- final IndexSearcher searcher;
Weight qWeight;
Map fcontext;
public BoostedWeight(IndexSearcher searcher, boolean needsScores) throws IOException {
super(BoostedQuery.this);
- this.searcher = searcher;
this.qWeight = searcher.createWeight(q, needsScores);
this.fcontext = ValueSource.newContext(searcher);
boostVal.createWeight(fcontext,searcher);
@@ -85,15 +83,12 @@ public class BoostedQuery extends Query {
@Override
public float getValueForNormalization() throws IOException {
- float sum = qWeight.getValueForNormalization();
- sum *= getBoost() * getBoost();
- return sum ;
+ return qWeight.getValueForNormalization();
}
@Override
- public void normalize(float norm, float topLevelBoost) {
- topLevelBoost *= getBoost();
- qWeight.normalize(norm, topLevelBoost);
+ public void normalize(float norm, float boost) {
+ qWeight.normalize(norm, boost);
}
@Override
@@ -102,7 +97,7 @@ public class BoostedQuery extends Query {
if (subQueryScorer == null) {
return null;
}
- return new BoostedQuery.CustomScorer(context, this, getBoost(), subQueryScorer, boostVal);
+ return new BoostedQuery.CustomScorer(context, this, subQueryScorer, boostVal);
}
@Override
@@ -120,22 +115,20 @@ public class BoostedQuery extends Query {
private class CustomScorer extends FilterScorer {
private final BoostedQuery.BoostedWeight weight;
- private final float qWeight;
private final FunctionValues vals;
private final LeafReaderContext readerContext;
- private CustomScorer(LeafReaderContext readerContext, BoostedQuery.BoostedWeight w, float qWeight,
+ private CustomScorer(LeafReaderContext readerContext, BoostedQuery.BoostedWeight w,
Scorer scorer, ValueSource vs) throws IOException {
super(scorer);
this.weight = w;
- this.qWeight = qWeight;
this.readerContext = readerContext;
this.vals = vs.getValues(weight.fcontext, readerContext);
}
@Override
public float score() throws IOException {
- float score = qWeight * in.score() * vals.floatVal(in.docID());
+ float score = in.score() * vals.floatVal(in.docID());
// Current Lucene priority queues can't handle NaN and -Infinity, so
// map to -Float.MAX_VALUE. This conditional handles both -infinity
@@ -164,7 +157,6 @@ public class BoostedQuery extends Query {
public String toString(String field) {
StringBuilder sb = new StringBuilder();
sb.append("boost(").append(q.toString(field)).append(',').append(boostVal).append(')');
- sb.append(ToStringUtils.boost(getBoost()));
return sb.toString();
}
@@ -178,11 +170,9 @@ public class BoostedQuery extends Query {
@Override
public int hashCode() {
- int h = q.hashCode();
- h ^= (h << 17) | (h >>> 16);
- h += boostVal.hashCode();
- h ^= (h << 8) | (h >>> 25);
- h += Float.floatToIntBits(getBoost());
+ int h = super.hashCode();
+ h = 31 * h + q.hashCode();
+ h = 31 * h + boostVal.hashCode();
return h;
}
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/function/FunctionQuery.java b/lucene/queries/src/java/org/apache/lucene/queries/function/FunctionQuery.java
index 2b85837d8ce..1e7b40f8610 100644
--- a/lucene/queries/src/java/org/apache/lucene/queries/function/FunctionQuery.java
+++ b/lucene/queries/src/java/org/apache/lucene/queries/function/FunctionQuery.java
@@ -53,15 +53,9 @@ public class FunctionQuery extends Query {
return func;
}
- @Override
- public Query rewrite(IndexReader reader) throws IOException {
- return this;
- }
-
protected class FunctionWeight extends Weight {
protected final IndexSearcher searcher;
- protected float queryNorm;
- protected float queryWeight;
+ protected float queryNorm = 1f;
protected final Map context;
public FunctionWeight(IndexSearcher searcher) throws IOException {
@@ -76,24 +70,22 @@ public class FunctionQuery extends Query {
@Override
public float getValueForNormalization() throws IOException {
- queryWeight = getBoost();
- return queryWeight * queryWeight;
+ return queryNorm * queryNorm;
}
@Override
- public void normalize(float norm, float topLevelBoost) {
- this.queryNorm = norm * topLevelBoost;
- queryWeight *= this.queryNorm;
+ public void normalize(float norm, float boost) {
+ this.queryNorm = norm * boost;
}
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
- return new AllScorer(context, this, queryWeight);
+ return new AllScorer(context, this, queryNorm);
}
@Override
public Explanation explain(LeafReaderContext context, int doc) throws IOException {
- return ((AllScorer)scorer(context)).explain(doc);
+ return ((AllScorer)scorer(context)).explain(doc, queryNorm);
}
}
@@ -157,13 +149,13 @@ public class FunctionQuery extends Query {
return 1;
}
- public Explanation explain(int doc) throws IOException {
+ public Explanation explain(int doc, float queryNorm) throws IOException {
float sc = qWeight * vals.floatVal(doc);
return Explanation.match(sc, "FunctionQuery(" + func + "), product of:",
vals.explain(doc),
- Explanation.match(getBoost(), "boost"),
- Explanation.match(weight.queryNorm, "queryNorm"));
+ Explanation.match(queryNorm, "boost"),
+ Explanation.match(weight.queryNorm = 1f, "queryNorm"));
}
}
@@ -179,9 +171,7 @@ public class FunctionQuery extends Query {
@Override
public String toString(String field)
{
- float boost = getBoost();
- return (boost!=1.0?"(":"") + func.toString()
- + (boost==1.0 ? "" : ")^"+boost);
+ return func.toString();
}
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/mlt/MoreLikeThis.java b/lucene/queries/src/java/org/apache/lucene/queries/mlt/MoreLikeThis.java
index 86fb0604c79..69a35b6e920 100644
--- a/lucene/queries/src/java/org/apache/lucene/queries/mlt/MoreLikeThis.java
+++ b/lucene/queries/src/java/org/apache/lucene/queries/mlt/MoreLikeThis.java
@@ -29,6 +29,7 @@ import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.similarities.DefaultSimilarity;
@@ -618,14 +619,14 @@ public final class MoreLikeThis {
float bestScore = -1;
while ((scoreTerm = q.pop()) != null) {
- TermQuery tq = new TermQuery(new Term(scoreTerm.topField, scoreTerm.word));
+ Query tq = new TermQuery(new Term(scoreTerm.topField, scoreTerm.word));
if (boost) {
if (bestScore == -1) {
bestScore = (scoreTerm.score);
}
float myScore = (scoreTerm.score);
- tq.setBoost(boostFactor * myScore / bestScore);
+ tq = new BoostQuery(tq, boostFactor * myScore / bestScore);
}
try {
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/mlt/MoreLikeThisQuery.java b/lucene/queries/src/java/org/apache/lucene/queries/mlt/MoreLikeThisQuery.java
index 9150f9050cd..a9d17c0d62f 100644
--- a/lucene/queries/src/java/org/apache/lucene/queries/mlt/MoreLikeThisQuery.java
+++ b/lucene/queries/src/java/org/apache/lucene/queries/mlt/MoreLikeThisQuery.java
@@ -78,9 +78,7 @@ public class MoreLikeThisQuery extends Query {
}
//make at least half the terms match
newBq.setMinimumNumberShouldMatch((int) (bq.clauses().size() * percentTermsToMatch));
- Query rewritten = newBq.build();
- rewritten.setBoost(bq.getBoost());
- return rewritten;
+ return newBq.build();
}
/* (non-Javadoc)
diff --git a/lucene/queries/src/test/org/apache/lucene/queries/BoostingQueryTest.java b/lucene/queries/src/test/org/apache/lucene/queries/BoostingQueryTest.java
index df9d1b7a0b7..4e7c45d4819 100644
--- a/lucene/queries/src/test/org/apache/lucene/queries/BoostingQueryTest.java
+++ b/lucene/queries/src/test/org/apache/lucene/queries/BoostingQueryTest.java
@@ -23,6 +23,7 @@ import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.MultiReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.MatchNoDocsQuery;
import org.apache.lucene.search.Query;
@@ -47,9 +48,10 @@ public class BoostingQueryTest extends LuceneTestCase {
public void testRewrite() throws IOException {
IndexReader reader = new MultiReader();
BoostingQuery q = new BoostingQuery(new MatchNoDocsQuery(), new MatchAllDocsQuery(), 3);
- Query rewritten = q.rewrite(reader);
+ Query rewritten = new IndexSearcher(reader).rewrite(q);
Query expectedRewritten = new BoostingQuery(new BooleanQuery.Builder().build(), new MatchAllDocsQuery(), 3);
assertEquals(expectedRewritten, rewritten);
assertSame(rewritten, rewritten.rewrite(reader));
}
+
}
diff --git a/lucene/queries/src/test/org/apache/lucene/queries/CommonTermsQueryTest.java b/lucene/queries/src/test/org/apache/lucene/queries/CommonTermsQueryTest.java
index 03299cf140d..aba7f6a60c2 100644
--- a/lucene/queries/src/test/org/apache/lucene/queries/CommonTermsQueryTest.java
+++ b/lucene/queries/src/test/org/apache/lucene/queries/CommonTermsQueryTest.java
@@ -41,6 +41,7 @@ import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.QueryUtils;
@@ -546,7 +547,7 @@ public class CommonTermsQueryTest extends LuceneTestCase {
protected Query newTermQuery(Term term, TermContext context) {
Query query = super.newTermQuery(term, context);
if (term.text().equals("universe")) {
- query.setBoost(100f);
+ query = new BoostQuery(query, 100f);
}
return query;
}
diff --git a/lucene/queries/src/test/org/apache/lucene/queries/TermsQueryTest.java b/lucene/queries/src/test/org/apache/lucene/queries/TermsQueryTest.java
index e48173a8e4a..bddd78ef3a5 100644
--- a/lucene/queries/src/test/org/apache/lucene/queries/TermsQueryTest.java
+++ b/lucene/queries/src/test/org/apache/lucene/queries/TermsQueryTest.java
@@ -42,6 +42,7 @@ import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
@@ -106,10 +107,8 @@ public class TermsQueryTest extends LuceneTestCase {
bq.add(new TermQuery(t), Occur.SHOULD);
}
final Query q1 = new ConstantScoreQuery(bq.build());
- q1.setBoost(boost);
final Query q2 = new TermsQuery(queryTerms);
- q2.setBoost(boost);
- assertSameMatches(searcher, q1, q2, true);
+ assertSameMatches(searcher, new BoostQuery(q1, boost), new BoostQuery(q2, boost), true);
}
reader.close();
diff --git a/lucene/queries/src/test/org/apache/lucene/queries/TestCustomScoreExplanations.java b/lucene/queries/src/test/org/apache/lucene/queries/TestCustomScoreExplanations.java
index 8e9b93f2449..b579ec925d7 100644
--- a/lucene/queries/src/test/org/apache/lucene/queries/TestCustomScoreExplanations.java
+++ b/lucene/queries/src/test/org/apache/lucene/queries/TestCustomScoreExplanations.java
@@ -23,6 +23,7 @@ import org.apache.lucene.queries.function.valuesource.ConstValueSource;
import org.apache.lucene.search.BaseExplanationTestCase;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
@@ -37,8 +38,7 @@ public class TestCustomScoreExplanations extends BaseExplanationTestCase {
public void testBoost() throws Exception {
Query q = new TermQuery(new Term(FIELD, "w1"));
CustomScoreQuery csq = new CustomScoreQuery(q, new FunctionQuery(new ConstValueSource(5)));
- csq.setBoost(4);
- qtest(csq, new int[] { 0,1,2,3 });
+ qtest(new BoostQuery(csq, 4), new int[] { 0,1,2,3 });
}
public void testTopLevelBoost() throws Exception {
@@ -48,7 +48,6 @@ public class TestCustomScoreExplanations extends BaseExplanationTestCase {
bqB.add(new MatchAllDocsQuery(), BooleanClause.Occur.MUST);
bqB.add(csq, BooleanClause.Occur.MUST);
BooleanQuery bq = bqB.build();
- bq.setBoost(6);
- qtest(bq, new int[] { 0,1,2,3 });
+ qtest(new BoostQuery(bq, 6), new int[] { 0,1,2,3 });
}
}
diff --git a/lucene/queries/src/test/org/apache/lucene/queries/TestCustomScoreQuery.java b/lucene/queries/src/test/org/apache/lucene/queries/TestCustomScoreQuery.java
index 0a5126fc612..9df2b3cb3ee 100644
--- a/lucene/queries/src/test/org/apache/lucene/queries/TestCustomScoreQuery.java
+++ b/lucene/queries/src/test/org/apache/lucene/queries/TestCustomScoreQuery.java
@@ -34,6 +34,7 @@ import org.apache.lucene.queries.function.FunctionTestSetup;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.CheckHits;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.IndexSearcher;
@@ -236,30 +237,41 @@ public class TestCustomScoreQuery extends FunctionTestSetup {
BooleanQuery.Builder q2CustomNeutralB = new BooleanQuery.Builder();
q2CustomNeutralB.setDisableCoord(true);
Query q2CustomNeutralInner = new CustomScoreQuery(q1);
- q2CustomNeutralInner.setBoost((float)Math.sqrt(dboost));
- q2CustomNeutralB.add(q2CustomNeutralInner, BooleanClause.Occur.SHOULD);
+ q2CustomNeutralB.add(new BoostQuery(q2CustomNeutralInner, (float)Math.sqrt(dboost)), BooleanClause.Occur.SHOULD);
// a little tricky: we split the boost across an outer BQ and CustomScoreQuery
// this ensures boosting is correct across all these functions (see LUCENE-4935)
Query q2CustomNeutral = q2CustomNeutralB.build();
- q2CustomNeutral.setBoost((float)Math.sqrt(dboost));
+ q2CustomNeutral = new BoostQuery(q2CustomNeutral, (float)Math.sqrt(dboost));
log(q2CustomNeutral);
// custom query, that should (by default) multiply the scores of q1 by that of the field
- CustomScoreQuery q3CustomMul = new CustomScoreQuery(q1, functionQuery);
- q3CustomMul.setStrict(true);
- q3CustomMul.setBoost(boost);
+ Query q3CustomMul;
+ {
+ CustomScoreQuery csq = new CustomScoreQuery(q1, functionQuery);
+ csq.setStrict(true);
+ q3CustomMul = csq;
+ }
+ q3CustomMul = new BoostQuery(q3CustomMul, boost);
log(q3CustomMul);
// custom query, that should add the scores of q1 to that of the field
- CustomScoreQuery q4CustomAdd = new CustomAddQuery(q1, functionQuery);
- q4CustomAdd.setStrict(true);
- q4CustomAdd.setBoost(boost);
+ Query q4CustomAdd;
+ {
+ CustomScoreQuery csq = new CustomAddQuery(q1, functionQuery);
+ csq.setStrict(true);
+ q4CustomAdd = csq;
+ }
+ q4CustomAdd = new BoostQuery(q4CustomAdd, boost);
log(q4CustomAdd);
// custom query, that multiplies and adds the field score to that of q1
- CustomScoreQuery q5CustomMulAdd = new CustomMulAddQuery(q1, functionQuery, functionQuery);
- q5CustomMulAdd.setStrict(true);
- q5CustomMulAdd.setBoost(boost);
+ Query q5CustomMulAdd;
+ {
+ CustomScoreQuery csq = new CustomMulAddQuery(q1, functionQuery, functionQuery);
+ csq.setStrict(true);
+ q5CustomMulAdd = csq;
+ }
+ q5CustomMulAdd = new BoostQuery(q5CustomMulAdd, boost);
log(q5CustomMulAdd);
// do al the searches
diff --git a/lucene/queries/src/test/org/apache/lucene/queries/function/TestFunctionQueryExplanations.java b/lucene/queries/src/test/org/apache/lucene/queries/function/TestFunctionQueryExplanations.java
new file mode 100644
index 00000000000..34dcc59349c
--- /dev/null
+++ b/lucene/queries/src/test/org/apache/lucene/queries/function/TestFunctionQueryExplanations.java
@@ -0,0 +1,36 @@
+package org.apache.lucene.queries.function;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import org.apache.lucene.queries.function.valuesource.ConstValueSource;
+import org.apache.lucene.search.BaseExplanationTestCase;
+import org.apache.lucene.search.BoostQuery;
+import org.apache.lucene.search.Query;
+
+public class TestFunctionQueryExplanations extends BaseExplanationTestCase {
+
+ public void testSimple() throws Exception {
+ Query q = new FunctionQuery(new ConstValueSource(5));
+ qtest(q, new int[] { 0,1,2,3 });
+ }
+
+ public void testBoost() throws Exception {
+ Query q = new BoostQuery(new FunctionQuery(new ConstValueSource(5)), 2);
+ qtest(q, new int[] { 0,1,2,3 });
+ }
+}
diff --git a/lucene/queries/src/test/org/apache/lucene/queries/mlt/TestMoreLikeThis.java b/lucene/queries/src/test/org/apache/lucene/queries/mlt/TestMoreLikeThis.java
index 4a189630f92..4690dc74c4d 100644
--- a/lucene/queries/src/test/org/apache/lucene/queries/mlt/TestMoreLikeThis.java
+++ b/lucene/queries/src/test/org/apache/lucene/queries/mlt/TestMoreLikeThis.java
@@ -34,6 +34,7 @@ import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.QueryUtils;
@@ -109,13 +110,14 @@ public class TestMoreLikeThis extends LuceneTestCase {
originalValues.size(), clauses.size());
for (BooleanClause clause : clauses) {
- TermQuery tq = (TermQuery) clause.getQuery();
+ BoostQuery bq = (BoostQuery) clause.getQuery();
+ TermQuery tq = (TermQuery) bq.getQuery();
Float termBoost = originalValues.get(tq.getTerm().text());
assertNotNull("Expected term " + tq.getTerm().text(), termBoost);
float totalBoost = termBoost * boostFactor;
assertEquals("Expected boost of " + totalBoost + " for term '"
- + tq.getTerm().text() + "' got " + tq.getBoost(), totalBoost, tq
+ + tq.getTerm().text() + "' got " + bq.getBoost(), totalBoost, bq
.getBoost(), 0.0001);
}
analyzer.close();
@@ -136,8 +138,9 @@ public class TestMoreLikeThis extends LuceneTestCase {
Collection<BooleanClause> clauses = query.clauses();
for (BooleanClause clause : clauses) {
- TermQuery tq = (TermQuery) clause.getQuery();
- originalValues.put(tq.getTerm().text(), tq.getBoost());
+ BoostQuery bq = (BoostQuery) clause.getQuery();
+ TermQuery tq = (TermQuery) bq.getQuery();
+ originalValues.put(tq.getTerm().text(), bq.getBoost());
}
analyzer.close();
return originalValues;
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/MultiFieldQueryParser.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/MultiFieldQueryParser.java
index 45193488865..b39279c927b 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/MultiFieldQueryParser.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/MultiFieldQueryParser.java
@@ -24,6 +24,7 @@ import java.util.Map;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.MultiPhraseQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.Query;
@@ -106,7 +107,7 @@ public class MultiFieldQueryParser extends QueryParser
//Get the boost from the map and apply them
Float boost = boosts.get(fields[i]);
if (boost != null) {
- q.setBoost(boost.floatValue());
+ q = new BoostQuery(q, boost.floatValue());
}
}
q = applySlop(q,slop);
@@ -133,7 +134,6 @@ public class MultiFieldQueryParser extends QueryParser
builder.add(terms[i], positions[i]);
}
q = builder.build();
- q.setBoost(pq.getBoost());
} else if (q instanceof MultiPhraseQuery) {
((MultiPhraseQuery) q).setSlop(slop);
}
@@ -153,7 +153,7 @@ public class MultiFieldQueryParser extends QueryParser
//Get the boost from the map and apply them
Float boost = boosts.get(fields[i]);
if (boost != null) {
- q.setBoost(boost.floatValue());
+ q = new BoostQuery(q, boost.floatValue());
}
}
clauses.add(new BooleanClause(q, BooleanClause.Occur.SHOULD));
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/QueryParserBase.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/QueryParserBase.java
index 49627291969..5d4f9668610 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/QueryParserBase.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/QueryParserBase.java
@@ -503,7 +503,6 @@ public abstract class QueryParserBase extends QueryBuilder implements CommonQuer
builder.add(terms[i], positions[i]);
}
query = builder.build();
- query.setBoost(pq.getBoost());
}
if (query instanceof MultiPhraseQuery) {
((MultiPhraseQuery) query).setSlop(slop);
@@ -902,7 +901,7 @@ public abstract class QueryParserBase extends QueryBuilder implements CommonQuer
// avoid boosting null queries, such as those caused by stop words
if (q != null) {
- q.setBoost(f);
+ q = new BoostQuery(q, f);
}
}
return q;
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/complexPhrase/ComplexPhraseQueryParser.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/complexPhrase/ComplexPhraseQueryParser.java
index 31bd3b6663e..f2737f8a013 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/complexPhrase/ComplexPhraseQueryParser.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/complexPhrase/ComplexPhraseQueryParser.java
@@ -29,11 +29,13 @@ import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MultiTermQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TermRangeQuery;
+import org.apache.lucene.search.spans.SpanBoostQuery;
import org.apache.lucene.search.spans.SpanNearQuery;
import org.apache.lucene.search.spans.SpanNotQuery;
import org.apache.lucene.search.spans.SpanOrQuery;
@@ -278,6 +280,10 @@ public class ComplexPhraseQueryParser extends QueryParser {
numNegatives++;
}
+ while (qc instanceof BoostQuery) {
+ qc = ((BoostQuery) qc).getQuery();
+ }
+
if (qc instanceof BooleanQuery) {
ArrayList<SpanQuery> sc = new ArrayList<>();
addComplexPhraseClause(sc, (BooleanQuery) qc);
@@ -347,6 +353,13 @@ public class ComplexPhraseQueryParser extends QueryParser {
for (BooleanClause clause : qc) {
Query childQuery = clause.getQuery();
+ float boost = 1f;
+ while (childQuery instanceof BoostQuery) {
+ BoostQuery bq = (BoostQuery) childQuery;
+ boost *= bq.getBoost();
+ childQuery = bq.getQuery();
+ }
+
// select the list to which we will add these options
ArrayList<SpanQuery> chosenList = ors;
if (clause.getOccur() == BooleanClause.Occur.MUST_NOT) {
@@ -355,8 +368,10 @@ public class ComplexPhraseQueryParser extends QueryParser {
if (childQuery instanceof TermQuery) {
TermQuery tq = (TermQuery) childQuery;
- SpanTermQuery stq = new SpanTermQuery(tq.getTerm());
- stq.setBoost(tq.getBoost());
+ SpanQuery stq = new SpanTermQuery(tq.getTerm());
+ if (boost != 1f) {
+ stq = new SpanBoostQuery(stq, boost);
+ }
chosenList.add(stq);
} else if (childQuery instanceof BooleanQuery) {
BooleanQuery cbq = (BooleanQuery) childQuery;
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/builders/BoostQueryNodeBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/builders/BoostQueryNodeBuilder.java
index 0330121c03f..239b09dfabd 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/builders/BoostQueryNodeBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/builders/BoostQueryNodeBuilder.java
@@ -21,6 +21,7 @@ import org.apache.lucene.queryparser.flexible.core.QueryNodeException;
import org.apache.lucene.queryparser.flexible.core.builders.QueryTreeBuilder;
import org.apache.lucene.queryparser.flexible.core.nodes.BoostQueryNode;
import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.Query;
/**
@@ -46,9 +47,8 @@ public class BoostQueryNodeBuilder implements StandardQueryBuilder {
Query query = (Query) child
.getTag(QueryTreeBuilder.QUERY_TREE_BUILDER_TAGID);
- query.setBoost(boostNode.getValue());
- return query;
+ return new BoostQuery(query, boostNode.getValue());
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/builders/SlopQueryNodeBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/builders/SlopQueryNodeBuilder.java
index 5aea2680fc8..47dcbe0ab48 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/builders/SlopQueryNodeBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/builders/SlopQueryNodeBuilder.java
@@ -54,7 +54,6 @@ public class SlopQueryNodeBuilder implements StandardQueryBuilder {
builder.add(terms[i], positions[i]);
}
query = builder.build();
- query.setBoost(pq.getBoost());
} else {
((MultiPhraseQuery) query).setSlop(phraseSlopNode.getValue());
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/simple/SimpleQueryParser.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/simple/SimpleQueryParser.java
index 4975c30ed14..fc104b30f7f 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/simple/SimpleQueryParser.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/simple/SimpleQueryParser.java
@@ -21,6 +21,7 @@ import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.MatchNoDocsQuery;
@@ -534,7 +535,10 @@ public class SimpleQueryParser extends QueryBuilder {
for (Map.Entry<String,Float> entry : weights.entrySet()) {
Query q = createBooleanQuery(entry.getKey(), text, defaultOperator);
if (q != null) {
- q.setBoost(entry.getValue());
+ float boost = entry.getValue();
+ if (boost != 1f) {
+ q = new BoostQuery(q, boost);
+ }
bq.add(q, BooleanClause.Occur.SHOULD);
}
}
@@ -549,10 +553,11 @@ public class SimpleQueryParser extends QueryBuilder {
bq.setDisableCoord(true);
for (Map.Entry<String,Float> entry : weights.entrySet()) {
Query q = new FuzzyQuery(new Term(entry.getKey(), text), fuzziness);
- if (q != null) {
- q.setBoost(entry.getValue());
- bq.add(q, BooleanClause.Occur.SHOULD);
+ float boost = entry.getValue();
+ if (boost != 1f) {
+ q = new BoostQuery(q, boost);
}
+ bq.add(q, BooleanClause.Occur.SHOULD);
}
return simplify(bq.build());
}
@@ -566,7 +571,10 @@ public class SimpleQueryParser extends QueryBuilder {
for (Map.Entry<String,Float> entry : weights.entrySet()) {
Query q = createPhraseQuery(entry.getKey(), text, slop);
if (q != null) {
- q.setBoost(entry.getValue());
+ float boost = entry.getValue();
+ if (boost != 1f) {
+ q = new BoostQuery(q, boost);
+ }
bq.add(q, BooleanClause.Occur.SHOULD);
}
}
@@ -580,9 +588,12 @@ public class SimpleQueryParser extends QueryBuilder {
BooleanQuery.Builder bq = new BooleanQuery.Builder();
bq.setDisableCoord(true);
for (Map.Entry<String,Float> entry : weights.entrySet()) {
- PrefixQuery prefix = new PrefixQuery(new Term(entry.getKey(), text));
- prefix.setBoost(entry.getValue());
- bq.add(prefix, BooleanClause.Occur.SHOULD);
+ Query q = new PrefixQuery(new Term(entry.getKey(), text));
+ float boost = entry.getValue();
+ if (boost != 1f) {
+ q = new BoostQuery(q, boost);
+ }
+ bq.add(q, BooleanClause.Occur.SHOULD);
}
return simplify(bq.build());
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/DistanceQuery.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/DistanceQuery.java
index 5845771c16e..62bc6454220 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/DistanceQuery.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/DistanceQuery.java
@@ -68,7 +68,6 @@ public class DistanceQuery extends ComposedQuery implements DistanceSubQuery {
public void addSpanQueries(SpanNearClauseFactory sncf) throws IOException {
Query snq = getSpanNearQuery(sncf.getIndexReader(),
sncf.getFieldName(),
- getWeight(),
sncf.getBasicQueryFactory());
sncf.addSpanQuery(snq);
}
@@ -76,7 +75,6 @@ public class DistanceQuery extends ComposedQuery implements DistanceSubQuery {
public Query getSpanNearQuery(
IndexReader reader,
String fieldName,
- float boost,
BasicQueryFactory qf) throws IOException {
SpanQuery[] spanClauses = new SpanQuery[getNrSubQueries()];
Iterator<?> sqi = getSubQueriesIterator();
@@ -97,9 +95,7 @@ public class DistanceQuery extends ComposedQuery implements DistanceSubQuery {
qi++;
}
- SpanNearQuery r = new SpanNearQuery(spanClauses, getOpDistance() - 1, subQueriesOrdered());
- r.setBoost(boost);
- return r;
+ return new SpanNearQuery(spanClauses, getOpDistance() - 1, subQueriesOrdered());
}
@Override
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/DistanceRewriteQuery.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/DistanceRewriteQuery.java
index 9110e326816..f54a0b5e3bc 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/DistanceRewriteQuery.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/DistanceRewriteQuery.java
@@ -32,7 +32,7 @@ class DistanceRewriteQuery extends RewriteQuery<DistanceQuery> {
@Override
public Query rewrite(IndexReader reader) throws IOException {
- return srndQuery.getSpanNearQuery(reader, fieldName, getBoost(), qf);
+ return srndQuery.getSpanNearQuery(reader, fieldName, qf);
}
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/SpanNearClauseFactory.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/SpanNearClauseFactory.java
index 88e2f6c0465..0566d043290 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/SpanNearClauseFactory.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/SpanNearClauseFactory.java
@@ -60,6 +60,7 @@ import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.MatchNoDocsQuery;
import org.apache.lucene.search.Query;
+import org.apache.lucene.search.spans.SpanBoostQuery;
import org.apache.lucene.search.spans.SpanOrQuery;
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.search.spans.SpanTermQuery;
@@ -110,7 +111,13 @@ public class SpanNearClauseFactory { // FIXME: rename to SpanClauseFactory
return;
if (! (q instanceof SpanQuery))
throw new AssertionError("Expected SpanQuery: " + q.toString(getFieldName()));
- addSpanQueryWeighted((SpanQuery)q, q.getBoost());
+ float boost = 1f;
+ if (q instanceof SpanBoostQuery) {
+ SpanBoostQuery bq = (SpanBoostQuery) q;
+ boost = bq.getBoost();
+ q = bq.getQuery();
+ }
+ addSpanQueryWeighted((SpanQuery)q, boost);
}
public SpanQuery makeSpanClause() {
@@ -119,7 +126,10 @@ public class SpanNearClauseFactory { // FIXME: rename to SpanClauseFactory
int i = 0;
while (sqi.hasNext()) {
SpanQuery sq = sqi.next();
- sq.setBoost(weightBySpanQuery.get(sq).floatValue());
+ float boost = weightBySpanQuery.get(sq);
+ if (boost != 1f) {
+ sq = new SpanBoostQuery(sq, boost);
+ }
spanQueries[i++] = sq;
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/SrndQuery.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/SrndQuery.java
index 11b67fe3e8c..cfbb9f4b9ef 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/SrndQuery.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/SrndQuery.java
@@ -16,8 +16,7 @@ package org.apache.lucene.queryparser.surround.query;
* limitations under the License.
*/
-import org.apache.lucene.search.BooleanClause;
-import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.Query;
/** Lowest level base class for surround queries */
@@ -47,7 +46,7 @@ public abstract class SrndQuery implements Cloneable {
public Query makeLuceneQueryField(String fieldName, BasicQueryFactory qf){
Query q = makeLuceneQueryFieldNoBoost(fieldName, qf);
if (isWeighted()) {
- q.setBoost(getWeight() * q.getBoost()); /* weight may be at any level in a SrndQuery */
+ q = new BoostQuery(q, getWeight()); /* weight may be at any level in a SrndQuery */
}
return q;
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/BooleanQueryBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/BooleanQueryBuilder.java
index 7c36aabeab3..b89f6365133 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/BooleanQueryBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/BooleanQueryBuilder.java
@@ -5,6 +5,7 @@ package org.apache.lucene.queryparser.xml.builders;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.queryparser.xml.DOMUtils;
import org.apache.lucene.queryparser.xml.ParserException;
@@ -63,8 +64,11 @@ public class BooleanQueryBuilder implements QueryBuilder {
}
}
- BooleanQuery q = bq.build();
- q.setBoost(DOMUtils.getAttribute(e, "boost", 1.0f));
+ Query q = bq.build();
+ float boost = DOMUtils.getAttribute(e, "boost", 1.0f);
+ if (boost != 1f) {
+ q = new BoostQuery(q, boost);
+ }
return q;
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/BoostingQueryBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/BoostingQueryBuilder.java
index 5b962dc39f7..f5fc5232106 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/BoostingQueryBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/BoostingQueryBuilder.java
@@ -1,6 +1,7 @@
package org.apache.lucene.queryparser.xml.builders;
import org.apache.lucene.queries.BoostingQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.queryparser.xml.DOMUtils;
import org.apache.lucene.queryparser.xml.ParserException;
@@ -47,10 +48,12 @@ public class BoostingQueryBuilder implements QueryBuilder {
boostQueryElem = DOMUtils.getFirstChildOrFail(boostQueryElem);
Query boostQuery = factory.getQuery(boostQueryElem);
- BoostingQuery bq = new BoostingQuery(mainQuery, boostQuery, boost);
+ Query bq = new BoostingQuery(mainQuery, boostQuery, boost);
- bq.setBoost(DOMUtils.getAttribute(e, "boost", 1.0f));
+ boost = DOMUtils.getAttribute(e, "boost", 1.0f);
+ if (boost != 1f) {
+ return new BoostQuery(bq, boost);
+ }
return bq;
-
}
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/BoostingTermBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/BoostingTermBuilder.java
index 4d4b3c8e1d8..ba169bd8a82 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/BoostingTermBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/BoostingTermBuilder.java
@@ -5,6 +5,7 @@ import org.apache.lucene.queryparser.xml.DOMUtils;
import org.apache.lucene.queryparser.xml.ParserException;
import org.apache.lucene.search.payloads.AveragePayloadFunction;
import org.apache.lucene.search.payloads.PayloadScoreQuery;
+import org.apache.lucene.search.spans.SpanBoostQuery;
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.search.spans.SpanTermQuery;
import org.w3c.dom.Element;
@@ -36,9 +37,9 @@ public class BoostingTermBuilder extends SpanBuilderBase {
String fieldName = DOMUtils.getAttributeWithInheritanceOrFail(e, "fieldName");
String value = DOMUtils.getNonBlankTextOrFail(e);
- PayloadScoreQuery btq = new PayloadScoreQuery(new SpanTermQuery(new Term(fieldName, value)),
+ SpanQuery btq = new PayloadScoreQuery(new SpanTermQuery(new Term(fieldName, value)),
new AveragePayloadFunction());
- btq.setBoost(DOMUtils.getAttribute(e, "boost", 1.0f));
+ btq = new SpanBoostQuery(btq, DOMUtils.getAttribute(e, "boost", 1.0f));
return btq;
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/ConstantScoreQueryBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/ConstantScoreQueryBuilder.java
index a09253b1119..ef618471405 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/ConstantScoreQueryBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/ConstantScoreQueryBuilder.java
@@ -4,6 +4,7 @@ import org.apache.lucene.queryparser.xml.DOMUtils;
import org.apache.lucene.queryparser.xml.ParserException;
import org.apache.lucene.queryparser.xml.QueryBuilder;
import org.apache.lucene.queryparser.xml.QueryBuilderFactory;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.Query;
import org.w3c.dom.Element;
@@ -40,7 +41,10 @@ public class ConstantScoreQueryBuilder implements QueryBuilder {
Element queryElem = DOMUtils.getFirstChildOrFail(e);
Query q = new ConstantScoreQuery(queryFactory.getQuery(queryElem));
- q.setBoost(DOMUtils.getAttribute(e, "boost", 1.0f));
+ float boost = DOMUtils.getAttribute(e, "boost", 1.0f);
+ if (boost != 1f) {
+ q = new BoostQuery(q, boost);
+ }
return q;
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/DisjunctionMaxQueryBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/DisjunctionMaxQueryBuilder.java
index 16861e3a86f..48944f8c5a4 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/DisjunctionMaxQueryBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/DisjunctionMaxQueryBuilder.java
@@ -19,6 +19,7 @@ package org.apache.lucene.queryparser.xml.builders;
import org.apache.lucene.queryparser.xml.DOMUtils;
import org.apache.lucene.queryparser.xml.ParserException;
import org.apache.lucene.queryparser.xml.QueryBuilder;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.DisjunctionMaxQuery;
import org.apache.lucene.search.Query;
import org.w3c.dom.Element;
@@ -44,7 +45,6 @@ public class DisjunctionMaxQueryBuilder implements QueryBuilder {
public Query getQuery(Element e) throws ParserException {
float tieBreaker = DOMUtils.getAttribute(e, "tieBreaker", 0.0f);
DisjunctionMaxQuery dq = new DisjunctionMaxQuery(tieBreaker);
- dq.setBoost(DOMUtils.getAttribute(e, "boost", 1.0f));
NodeList nl = e.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
@@ -56,6 +56,11 @@ public class DisjunctionMaxQueryBuilder implements QueryBuilder {
}
}
- return dq;
+ Query q = dq;
+ float boost = DOMUtils.getAttribute(e, "boost", 1.0f);
+ if (boost != 1f) {
+ q = new BoostQuery(dq, boost);
+ }
+ return q;
}
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/FuzzyLikeThisQueryBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/FuzzyLikeThisQueryBuilder.java
index c333815e338..7592251ab80 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/FuzzyLikeThisQueryBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/FuzzyLikeThisQueryBuilder.java
@@ -6,6 +6,7 @@ import org.apache.lucene.queryparser.xml.ParserException;
import org.apache.lucene.queryparser.xml.QueryBuilder;
import org.apache.lucene.sandbox.queries.FuzzyLikeThisQuery;
import org.apache.lucene.sandbox.queries.SlowFuzzyQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.Query;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
@@ -60,8 +61,12 @@ public class FuzzyLikeThisQueryBuilder implements QueryBuilder {
fbq.addTerms(value, fieldName, minSimilarity, prefixLength);
}
- fbq.setBoost(DOMUtils.getAttribute(e, "boost", 1.0f));
- return fbq;
+ Query q = fbq;
+ float boost = DOMUtils.getAttribute(e, "boost", 1.0f);
+ if (boost != 1f) {
+ q = new BoostQuery(fbq, boost);
+ }
+ return q;
}
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/LikeThisQueryBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/LikeThisQueryBuilder.java
index fe784a555c7..98dfc3ccfe4 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/LikeThisQueryBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/LikeThisQueryBuilder.java
@@ -12,6 +12,7 @@ import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.queries.mlt.MoreLikeThisQuery;
import org.apache.lucene.queryparser.xml.QueryBuilder;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.queryparser.xml.DOMUtils;
import org.apache.lucene.queryparser.xml.ParserException;
@@ -98,9 +99,12 @@ public class LikeThisQueryBuilder implements QueryBuilder {
mlt.setMinDocFreq(minDocFreq);
}
- mlt.setBoost(DOMUtils.getAttribute(e, "boost", 1.0f));
-
- return mlt;
+ Query q = mlt;
+ float boost = DOMUtils.getAttribute(e, "boost", 1.0f);
+ if (boost != 1f) {
+ q = new BoostQuery(mlt, boost);
+ }
+ return q;
}
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanFirstBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanFirstBuilder.java
index d2288b4ea04..dccec2f587f 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanFirstBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanFirstBuilder.java
@@ -1,5 +1,6 @@
package org.apache.lucene.queryparser.xml.builders;
+import org.apache.lucene.search.spans.SpanBoostQuery;
import org.apache.lucene.search.spans.SpanFirstQuery;
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.queryparser.xml.DOMUtils;
@@ -41,8 +42,8 @@ public class SpanFirstBuilder extends SpanBuilderBase {
SpanFirstQuery sfq = new SpanFirstQuery(q, end);
- sfq.setBoost(DOMUtils.getAttribute(e, "boost", 1.0f));
- return sfq;
+ float boost = DOMUtils.getAttribute(e, "boost", 1.0f);
+ return new SpanBoostQuery(sfq, boost);
}
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanNearBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanNearBuilder.java
index e26735fa2b0..d81953a3262 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanNearBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanNearBuilder.java
@@ -1,5 +1,6 @@
package org.apache.lucene.queryparser.xml.builders;
+import org.apache.lucene.search.spans.SpanBoostQuery;
import org.apache.lucene.search.spans.SpanNearQuery;
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.queryparser.xml.DOMUtils;
@@ -49,7 +50,9 @@ public class SpanNearBuilder extends SpanBuilderBase {
}
}
SpanQuery[] spanQueries = spans.toArray(new SpanQuery[spans.size()]);
- return new SpanNearQuery(spanQueries, slop, inOrder);
+ SpanQuery snq = new SpanNearQuery(spanQueries, slop, inOrder);
+ float boost = DOMUtils.getAttribute(e, "boost", 1.0f);
+ return new SpanBoostQuery(snq, boost);
}
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanNotBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanNotBuilder.java
index 0be6dc81ed0..1a9b7846285 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanNotBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanNotBuilder.java
@@ -1,5 +1,6 @@
package org.apache.lucene.queryparser.xml.builders;
+import org.apache.lucene.search.spans.SpanBoostQuery;
import org.apache.lucene.search.spans.SpanNotQuery;
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.queryparser.xml.DOMUtils;
@@ -46,8 +47,8 @@ public class SpanNotBuilder extends SpanBuilderBase {
SpanNotQuery snq = new SpanNotQuery(include, exclude);
- snq.setBoost(DOMUtils.getAttribute(e, "boost", 1.0f));
- return snq;
+ float boost = DOMUtils.getAttribute(e, "boost", 1.0f);
+ return new SpanBoostQuery(snq, boost);
}
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanOrBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanOrBuilder.java
index ce48d00a590..367754bb17a 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanOrBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanOrBuilder.java
@@ -1,5 +1,6 @@
package org.apache.lucene.queryparser.xml.builders;
+import org.apache.lucene.search.spans.SpanBoostQuery;
import org.apache.lucene.search.spans.SpanOrQuery;
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.queryparser.xml.DOMUtils;
@@ -48,8 +49,8 @@ public class SpanOrBuilder extends SpanBuilderBase {
}
SpanQuery[] clauses = clausesList.toArray(new SpanQuery[clausesList.size()]);
SpanOrQuery soq = new SpanOrQuery(clauses);
- soq.setBoost(DOMUtils.getAttribute(e, "boost", 1.0f));
- return soq;
+ float boost = DOMUtils.getAttribute(e, "boost", 1.0f);
+ return new SpanBoostQuery(soq, boost);
}
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanOrTermsBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanOrTermsBuilder.java
index 7a59d619f06..785b644d880 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanOrTermsBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanOrTermsBuilder.java
@@ -4,6 +4,7 @@ import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.TermToBytesRefAttribute;
import org.apache.lucene.index.Term;
+import org.apache.lucene.search.spans.SpanBoostQuery;
import org.apache.lucene.search.spans.SpanOrQuery;
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.search.spans.SpanTermQuery;
@@ -60,8 +61,8 @@ public class SpanOrTermsBuilder extends SpanBuilderBase {
}
ts.end();
SpanOrQuery soq = new SpanOrQuery(clausesList.toArray(new SpanQuery[clausesList.size()]));
- soq.setBoost(DOMUtils.getAttribute(e, "boost", 1.0f));
- return soq;
+ float boost = DOMUtils.getAttribute(e, "boost", 1.0f);
+ return new SpanBoostQuery(soq, boost);
}
catch (IOException ioe) {
throw new ParserException("IOException parsing value:" + value);
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanQueryBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanQueryBuilder.java
index 8bbaa1cf825..1b694f3c0ae 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanQueryBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanQueryBuilder.java
@@ -15,6 +15,7 @@ package org.apache.lucene.queryparser.xml.builders;
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.queryparser.xml.ParserException;
import org.apache.lucene.queryparser.xml.QueryBuilder;
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanTermBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanTermBuilder.java
index bc16975b453..9148ef88e5f 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanTermBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanTermBuilder.java
@@ -1,6 +1,7 @@
package org.apache.lucene.queryparser.xml.builders;
import org.apache.lucene.index.Term;
+import org.apache.lucene.search.spans.SpanBoostQuery;
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.search.spans.SpanTermQuery;
import org.apache.lucene.queryparser.xml.DOMUtils;
@@ -34,8 +35,8 @@ public class SpanTermBuilder extends SpanBuilderBase {
String value = DOMUtils.getNonBlankTextOrFail(e);
SpanTermQuery stq = new SpanTermQuery(new Term(fieldName, value));
- stq.setBoost(DOMUtils.getAttribute(e, "boost", 1.0f));
- return stq;
+ float boost = DOMUtils.getAttribute(e, "boost", 1.0f);
+ return new SpanBoostQuery(stq, boost);
}
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/TermQueryBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/TermQueryBuilder.java
index d949b3b8303..8751eb39ac7 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/TermQueryBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/TermQueryBuilder.java
@@ -1,6 +1,7 @@
package org.apache.lucene.queryparser.xml.builders;
import org.apache.lucene.index.Term;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.queryparser.xml.DOMUtils;
@@ -33,8 +34,11 @@ public class TermQueryBuilder implements QueryBuilder {
public Query getQuery(Element e) throws ParserException {
String field = DOMUtils.getAttributeWithInheritanceOrFail(e, "fieldName");
String value = DOMUtils.getNonBlankTextOrFail(e);
- TermQuery tq = new TermQuery(new Term(field, value));
- tq.setBoost(DOMUtils.getAttribute(e, "boost", 1.0f));
+ Query tq = new TermQuery(new Term(field, value));
+ float boost = DOMUtils.getAttribute(e, "boost", 1.0f);
+ if (boost != 1f) {
+ tq = new BoostQuery(tq, boost);
+ }
return tq;
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/TermsQueryBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/TermsQueryBuilder.java
index bb95bc7446e..70085561be2 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/TermsQueryBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/TermsQueryBuilder.java
@@ -6,6 +6,7 @@ import org.apache.lucene.analysis.tokenattributes.TermToBytesRefAttribute;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.util.BytesRef;
@@ -67,8 +68,8 @@ public class TermsQueryBuilder implements QueryBuilder {
}
Query q = bq.build();
- q.setBoost(DOMUtils.getAttribute(e, "boost", 1.0f));
- return q;
+ float boost = DOMUtils.getAttribute(e, "boost", 1.0f);
+ return new BoostQuery(q, boost);
}
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/UserInputQueryBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/UserInputQueryBuilder.java
index 21e9eeb238f..09a7afd8831 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/UserInputQueryBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/UserInputQueryBuilder.java
@@ -3,8 +3,8 @@ package org.apache.lucene.queryparser.xml.builders;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.Query;
-import org.apache.lucene.util.Version;
import org.apache.lucene.queryparser.xml.DOMUtils;
import org.apache.lucene.queryparser.xml.ParserException;
import org.apache.lucene.queryparser.xml.QueryBuilder;
@@ -73,8 +73,8 @@ public class UserInputQueryBuilder implements QueryBuilder {
QueryParser parser = createQueryParser(fieldName, analyzer);
q = parser.parse(text);
}
- q.setBoost(DOMUtils.getAttribute(e, "boost", 1.0f));
- return q;
+ float boost = DOMUtils.getAttribute(e, "boost", 1.0f);
+ return new BoostQuery(q, boost);
} catch (ParseException e1) {
throw new ParserException(e1.getMessage());
}
diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestMultiFieldQueryParser.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestMultiFieldQueryParser.java
index 811f6313a02..2285143c615 100644
--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestMultiFieldQueryParser.java
+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestMultiFieldQueryParser.java
@@ -88,13 +88,13 @@ public class TestMultiFieldQueryParser extends LuceneTestCase {
assertEquals("+(b:one t:one) -(b:two t:two) -(b:three t:three)", q.toString());
q = mfqp.parse("one^2 two");
- assertEquals("((b:one t:one)^2.0) (b:two t:two)", q.toString());
+ assertEquals("(b:one t:one)^2.0 (b:two t:two)", q.toString());
q = mfqp.parse("one~ two");
assertEquals("(b:one~2 t:one~2) (b:two t:two)", q.toString());
q = mfqp.parse("one~0.8 two^2");
- assertEquals("(b:one~0 t:one~0) ((b:two t:two)^2.0)", q.toString());
+ assertEquals("(b:one~0 t:one~0) (b:two t:two)^2.0", q.toString());
q = mfqp.parse("one* two*");
assertEquals("(b:one* t:one*) (b:two* t:two*)", q.toString());
@@ -156,7 +156,7 @@ public class TestMultiFieldQueryParser extends LuceneTestCase {
assertEquals("+(b:one^5.0 t:one^10.0) +(b:two^5.0 t:two^10.0) +foo:test", q.toString());
q = mfqp.parse("one^3 AND two^4");
- assertEquals("+((b:one^5.0 t:one^10.0)^3.0) +((b:two^5.0 t:two^10.0)^4.0)", q.toString());
+ assertEquals("+(b:one^5.0 t:one^10.0)^3.0 +(b:two^5.0 t:two^10.0)^4.0", q.toString());
}
public void testStaticMethod1() throws ParseException {
diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestQueryParser.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestQueryParser.java
index efef8fa3d07..0bc541013df 100644
--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestQueryParser.java
+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestQueryParser.java
@@ -32,6 +32,7 @@ import org.apache.lucene.queryparser.flexible.standard.CommonQueryParserConfigur
import org.apache.lucene.queryparser.util.QueryParserTestBase;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.MultiPhraseQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
@@ -223,20 +224,22 @@ public class TestQueryParser extends QueryParserTestBase {
tq = (TermQuery) qp.parse("foo:zoo*");
assertEquals("zoo", tq.getTerm().text());
assertEquals(2, type[0]);
-
- tq = (TermQuery) qp.parse("foo:zoo*^2");
+
+ BoostQuery bq = (BoostQuery) qp.parse("foo:zoo*^2");
+ tq = (TermQuery) bq.getQuery();
assertEquals("zoo", tq.getTerm().text());
assertEquals(2, type[0]);
- assertEquals(tq.getBoost(), 2, 0);
+ assertEquals(bq.getBoost(), 2, 0);
tq = (TermQuery) qp.parse("foo:*");
assertEquals("*", tq.getTerm().text());
assertEquals(1, type[0]); // could be a valid prefix query in the future too
- tq = (TermQuery) qp.parse("foo:*^2");
+ bq = (BoostQuery) qp.parse("foo:*^2");
+ tq = (TermQuery) bq.getQuery();
assertEquals("*", tq.getTerm().text());
assertEquals(1, type[0]);
- assertEquals(tq.getBoost(), 2, 0);
+ assertEquals(bq.getBoost(), 2, 0);
tq = (TermQuery) qp.parse("*:foo");
assertEquals("*", tq.getTerm().field());
@@ -341,23 +344,23 @@ public class TestQueryParser extends QueryParserTestBase {
qp.setDefaultOperator(Operator.AND);
assertEquals(expected, qp.parse("dogs"));
assertEquals(expected, qp.parse("\"dogs\""));
- expected.setBoost(2.0f);
+ expected = new BoostQuery(expected, 2f);
assertEquals(expected, qp.parse("dogs^2"));
assertEquals(expected, qp.parse("\"dogs\"^2"));
}
/** forms multiphrase query */
public void testSynonymsPhrase() throws Exception {
- MultiPhraseQuery expected = new MultiPhraseQuery();
- expected.add(new Term("field", "old"));
- expected.add(new Term[] { new Term("field", "dogs"), new Term("field", "dog") });
+ MultiPhraseQuery expectedQ = new MultiPhraseQuery();
+ expectedQ.add(new Term("field", "old"));
+ expectedQ.add(new Term[] { new Term("field", "dogs"), new Term("field", "dog") });
QueryParser qp = new QueryParser("field", new MockSynonymAnalyzer());
- assertEquals(expected, qp.parse("\"old dogs\""));
+ assertEquals(expectedQ, qp.parse("\"old dogs\""));
qp.setDefaultOperator(Operator.AND);
- assertEquals(expected, qp.parse("\"old dogs\""));
- expected.setBoost(2.0f);
+ assertEquals(expectedQ, qp.parse("\"old dogs\""));
+ BoostQuery expected = new BoostQuery(expectedQ, 2f);
assertEquals(expected, qp.parse("\"old dogs\"^2"));
- expected.setSlop(3);
+ expectedQ.setSlop(3);
assertEquals(expected, qp.parse("\"old dogs\"~3^2"));
}
@@ -411,7 +414,7 @@ public class TestQueryParser extends QueryParserTestBase {
assertEquals(expected, qp.parse("国"));
qp.setDefaultOperator(Operator.AND);
assertEquals(expected, qp.parse("国"));
- expected.setBoost(2.0f);
+ expected = new BoostQuery(expected, 2f);
assertEquals(expected, qp.parse("国^2"));
}
@@ -427,7 +430,7 @@ public class TestQueryParser extends QueryParserTestBase {
Query expected = expectedB.build();
QueryParser qp = new QueryParser("field", new MockCJKSynonymAnalyzer());
assertEquals(expected, qp.parse("中国"));
- expected.setBoost(2.0f);
+ expected = new BoostQuery(expected, 2f);
assertEquals(expected, qp.parse("中国^2"));
}
@@ -448,7 +451,7 @@ public class TestQueryParser extends QueryParserTestBase {
Query expected = expectedB.build();
QueryParser qp = new QueryParser("field", new MockCJKSynonymAnalyzer());
assertEquals(expected, qp.parse("中国国"));
- expected.setBoost(2.0f);
+ expected = new BoostQuery(expected, 2f);
assertEquals(expected, qp.parse("中国国^2"));
}
@@ -465,7 +468,7 @@ public class TestQueryParser extends QueryParserTestBase {
QueryParser qp = new QueryParser("field", new MockCJKSynonymAnalyzer());
qp.setDefaultOperator(Operator.AND);
assertEquals(expected, qp.parse("中国"));
- expected.setBoost(2.0f);
+ expected = new BoostQuery(expected, 2f);
assertEquals(expected, qp.parse("中国^2"));
}
@@ -487,21 +490,21 @@ public class TestQueryParser extends QueryParserTestBase {
QueryParser qp = new QueryParser("field", new MockCJKSynonymAnalyzer());
qp.setDefaultOperator(Operator.AND);
assertEquals(expected, qp.parse("中国国"));
- expected.setBoost(2.0f);
+ expected = new BoostQuery(expected, 2f);
assertEquals(expected, qp.parse("中国国^2"));
}
/** forms multiphrase query */
public void testCJKSynonymsPhrase() throws Exception {
- MultiPhraseQuery expected = new MultiPhraseQuery();
- expected.add(new Term("field", "中"));
- expected.add(new Term[] { new Term("field", "国"), new Term("field", "國")});
+ MultiPhraseQuery expectedQ = new MultiPhraseQuery();
+ expectedQ.add(new Term("field", "中"));
+ expectedQ.add(new Term[] { new Term("field", "国"), new Term("field", "國")});
QueryParser qp = new QueryParser("field", new MockCJKSynonymAnalyzer());
qp.setDefaultOperator(Operator.AND);
- assertEquals(expected, qp.parse("\"中国\""));
- expected.setBoost(2.0f);
+ assertEquals(expectedQ, qp.parse("\"中国\""));
+ Query expected = new BoostQuery(expectedQ, 2f);
assertEquals(expected, qp.parse("\"中国\"^2"));
- expected.setSlop(3);
+ expectedQ.setSlop(3);
assertEquals(expected, qp.parse("\"中国\"~3^2"));
}
diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/precedence/TestPrecedenceQueryParser.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/precedence/TestPrecedenceQueryParser.java
index aca90f5d292..4fe78490ddc 100644
--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/precedence/TestPrecedenceQueryParser.java
+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/precedence/TestPrecedenceQueryParser.java
@@ -38,6 +38,7 @@ import org.apache.lucene.queryparser.flexible.standard.config.StandardQueryConfi
import org.apache.lucene.queryparser.flexible.standard.parser.ParseException;
import org.apache.lucene.queryparser.util.QueryParserTestBase; // javadocs
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.PrefixQuery;
@@ -304,7 +305,8 @@ public class TestPrecedenceQueryParser extends LuceneTestCase {
assertQueryEquals("term*germ^3", null, "term*germ^3.0");
assertTrue(getQuery("term*", null) instanceof PrefixQuery);
- assertTrue(getQuery("term*^2", null) instanceof PrefixQuery);
+ assertTrue(getQuery("term*^2", null) instanceof BoostQuery);
+ assertTrue(((BoostQuery) getQuery("term*^2", null)).getQuery() instanceof PrefixQuery);
assertTrue(getQuery("term~", null) instanceof FuzzyQuery);
assertTrue(getQuery("term~0.7", null) instanceof FuzzyQuery);
FuzzyQuery fq = (FuzzyQuery) getQuery("term~0.7", null);
@@ -566,10 +568,10 @@ public class TestPrecedenceQueryParser extends LuceneTestCase {
assertNotNull(q);
q = qp.parse("\"hello\"^2.0", "field");
assertNotNull(q);
- assertEquals(q.getBoost(), (float) 2.0, (float) 0.5);
+ assertEquals(((BoostQuery) q).getBoost(), (float) 2.0, (float) 0.5);
q = qp.parse("hello^2.0", "field");
assertNotNull(q);
- assertEquals(q.getBoost(), (float) 2.0, (float) 0.5);
+ assertEquals(((BoostQuery) q).getBoost(), (float) 2.0, (float) 0.5);
q = qp.parse("\"on\"^1.0", "field");
assertNotNull(q);
diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestMultiFieldQPHelper.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestMultiFieldQPHelper.java
index 89a4574e51a..7950e94b418 100644
--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestMultiFieldQPHelper.java
+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestMultiFieldQPHelper.java
@@ -98,13 +98,13 @@ public class TestMultiFieldQPHelper extends LuceneTestCase {
.toString());
q = mfqp.parse("one^2 two", null);
- assertEquals("((b:one t:one)^2.0) (b:two t:two)", q.toString());
+ assertEquals("(b:one t:one)^2.0 (b:two t:two)", q.toString());
q = mfqp.parse("one~ two", null);
assertEquals("(b:one~2 t:one~2) (b:two t:two)", q.toString());
q = mfqp.parse("one~0.8 two^2", null);
- assertEquals("(b:one~0 t:one~0) ((b:two t:two)^2.0)", q.toString());
+ assertEquals("(b:one~0 t:one~0) (b:two t:two)^2.0", q.toString());
q = mfqp.parse("one* two*", null);
assertEquals("(b:one* t:one*) (b:two* t:two*)", q.toString());
@@ -173,7 +173,7 @@ public class TestMultiFieldQPHelper extends LuceneTestCase {
.toString());
q = mfqp.parse("one^3 AND two^4", null);
- assertEquals("+((b:one^5.0 t:one^10.0)^3.0) +((b:two^5.0 t:two^10.0)^4.0)",
+ assertEquals("+(b:one^5.0 t:one^10.0)^3.0 +(b:two^5.0 t:two^10.0)^4.0",
q.toString());
}
diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestQPHelper.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestQPHelper.java
index 2da38997753..8e6fde3e90f 100644
--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestQPHelper.java
+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestQPHelper.java
@@ -57,6 +57,7 @@ import org.apache.lucene.queryparser.flexible.standard.nodes.WildcardQueryNode;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
@@ -400,7 +401,7 @@ public class TestQPHelper extends LuceneTestCase {
expectedB.add(new TermQuery(new Term("field", "中")), BooleanClause.Occur.SHOULD);
expectedB.add(new TermQuery(new Term("field", "国")), BooleanClause.Occur.SHOULD);
Query expected = expectedB.build();
- expected.setBoost(0.5f);
+ expected = new BoostQuery(expected, 0.5f);
assertEquals(expected, getQuery("中国^0.5", analyzer));
}
@@ -417,8 +418,8 @@ public class TestQPHelper extends LuceneTestCase {
// individual CJK chars as terms
SimpleCJKAnalyzer analyzer = new SimpleCJKAnalyzer();
- PhraseQuery expected = new PhraseQuery("field", "中", "国");
- expected.setBoost(0.5f);
+ Query expected = new PhraseQuery("field", "中", "国");
+ expected = new BoostQuery(expected, 0.5f);
assertEquals(expected, getQuery("\"中国\"^0.5", analyzer));
}
@@ -508,7 +509,7 @@ public class TestQPHelper extends LuceneTestCase {
assertQueryEquals("((a AND b) AND c)", null, "+(+a +b) +c");
assertQueryEquals("(a AND b) AND c", null, "+(+a +b) +c");
assertQueryEquals("b !(a AND b)", null, "b -(+a +b)");
- assertQueryEquals("(a AND b)^4 OR c", null, "((+a +b)^4.0) c");
+ assertQueryEquals("(a AND b)^4 OR c", null, "(+a +b)^4.0 c");
}
public void testSlop() throws Exception {
@@ -551,7 +552,8 @@ public class TestQPHelper extends LuceneTestCase {
assertQueryEquals("term*germ^3", null, "term*germ^3.0");
assertTrue(getQuery("term*", null) instanceof PrefixQuery);
- assertTrue(getQuery("term*^2", null) instanceof PrefixQuery);
+ assertTrue(getQuery("term*^2", null) instanceof BoostQuery);
+ assertTrue(((BoostQuery) getQuery("term*^2", null)).getQuery() instanceof PrefixQuery);
assertTrue(getQuery("term~", null) instanceof FuzzyQuery);
assertTrue(getQuery("term~0.7", null) instanceof FuzzyQuery);
FuzzyQuery fq = (FuzzyQuery) getQuery("term~0.7", null);
@@ -971,10 +973,10 @@ public class TestQPHelper extends LuceneTestCase {
assertNotNull(q);
q = qp.parse("\"hello\"^2.0", "field");
assertNotNull(q);
- assertEquals(q.getBoost(), (float) 2.0, (float) 0.5);
+ assertEquals(((BoostQuery) q).getBoost(), (float) 2.0, (float) 0.5);
q = qp.parse("hello^2.0", "field");
assertNotNull(q);
- assertEquals(q.getBoost(), (float) 2.0, (float) 0.5);
+ assertEquals(((BoostQuery) q).getBoost(), (float) 2.0, (float) 0.5);
q = qp.parse("\"on\"^1.0", "field");
assertNotNull(q);
@@ -985,7 +987,7 @@ public class TestQPHelper extends LuceneTestCase {
// "the" is a stop word so the result is an empty query:
assertNotNull(q);
assertEquals("", q.toString());
- assertEquals(1.0f, q.getBoost(), 0.01f);
+ assertFalse(q instanceof BoostQuery);
}
public void assertQueryNodeException(String queryString) throws Exception {
@@ -1151,13 +1153,11 @@ public class TestQPHelper extends LuceneTestCase {
assertEquals(q, qp.parse("/[a-z][123]/", df));
qp.setLowercaseExpandedTerms(true);
assertEquals(q, qp.parse("/[A-Z][123]/", df));
- q.setBoost(0.5f);
- assertEquals(q, qp.parse("/[A-Z][123]/^0.5", df));
+ assertEquals(new BoostQuery(q, 0.5f), qp.parse("/[A-Z][123]/^0.5", df));
qp.setMultiTermRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_REWRITE);
q.setRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_REWRITE);
- assertTrue(qp.parse("/[A-Z][123]/^0.5", df) instanceof RegexpQuery);
- assertEquals(q, qp.parse("/[A-Z][123]/^0.5", df));
- assertEquals(MultiTermQuery.SCORING_BOOLEAN_REWRITE, ((RegexpQuery)qp.parse("/[A-Z][123]/^0.5", df)).getRewriteMethod());
+ assertEquals(new BoostQuery(q, 0.5f), qp.parse("/[A-Z][123]/^0.5", df));
+ assertEquals(MultiTermQuery.SCORING_BOOLEAN_REWRITE, ((RegexpQuery) (((BoostQuery) qp.parse("/[A-Z][123]/^0.5", df)).getQuery())).getRewriteMethod());
qp.setMultiTermRewriteMethod(MultiTermQuery.CONSTANT_SCORE_REWRITE);
Query escaped = new RegexpQuery(new Term("field", "[a-z]\\/[123]"));
@@ -1207,12 +1207,12 @@ public class TestQPHelper extends LuceneTestCase {
result = qp.parse(
"(fieldX:xxxxx OR fieldy:xxxxxxxx)^2 AND (fieldx:the OR fieldy:foo)",
"a");
- assertNotNull("result is null and it shouldn't be", result);
- assertTrue("result is not a BooleanQuery", result instanceof BooleanQuery);
- if (VERBOSE)
- System.out.println("Result: " + result);
- assertTrue(((BooleanQuery) result).clauses().size() + " does not equal: "
- + 2, ((BooleanQuery) result).clauses().size() == 2);
+ Query expected = new BooleanQuery.Builder()
+ .add(new TermQuery(new Term("fieldX", "xxxxx")), Occur.SHOULD)
+ .add(new TermQuery(new Term("fieldy", "xxxxxxxx")), Occur.SHOULD)
+ .build();
+ expected = new BoostQuery(expected, 2f);
+ assertEquals(expected, result);
}
public void testPositionIncrement() throws Exception {
diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/simple/TestSimpleQueryParser.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/simple/TestSimpleQueryParser.java
index fc0b53fa9ad..b03fb4fbcad 100644
--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/simple/TestSimpleQueryParser.java
+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/simple/TestSimpleQueryParser.java
@@ -27,6 +27,7 @@ import org.apache.lucene.analysis.MockTokenizer;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.MatchNoDocsQuery;
@@ -480,10 +481,10 @@ public class TestSimpleQueryParser extends LuceneTestCase {
BooleanQuery.Builder expected = new BooleanQuery.Builder();
expected.setDisableCoord(true);
Query field0 = new TermQuery(new Term("field0", "foo"));
- field0.setBoost(5f);
+ field0 = new BoostQuery(field0, 5f);
expected.add(field0, Occur.SHOULD);
Query field1 = new TermQuery(new Term("field1", "foo"));
- field1.setBoost(10f);
+ field1 = new BoostQuery(field1, 10f);
expected.add(field1, Occur.SHOULD);
Analyzer analyzer = new MockAnalyzer(random());
@@ -501,20 +502,20 @@ public class TestSimpleQueryParser extends LuceneTestCase {
BooleanQuery.Builder foo = new BooleanQuery.Builder();
foo.setDisableCoord(true);
Query field0 = new TermQuery(new Term("field0", "foo"));
- field0.setBoost(5f);
+ field0 = new BoostQuery(field0, 5f);
foo.add(field0, Occur.SHOULD);
Query field1 = new TermQuery(new Term("field1", "foo"));
- field1.setBoost(10f);
+ field1 = new BoostQuery(field1, 10f);
foo.add(field1, Occur.SHOULD);
expected.add(foo.build(), Occur.SHOULD);
BooleanQuery.Builder bar = new BooleanQuery.Builder();
bar.setDisableCoord(true);
field0 = new TermQuery(new Term("field0", "bar"));
- field0.setBoost(5f);
+ field0 = new BoostQuery(field0, 5f);
bar.add(field0, Occur.SHOULD);
field1 = new TermQuery(new Term("field1", "bar"));
- field1.setBoost(10f);
+ field1 = new BoostQuery(field1, 10f);
bar.add(field1, Occur.SHOULD);
expected.add(bar.build(), Occur.SHOULD);
diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/util/QueryParserTestBase.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/util/QueryParserTestBase.java
index 043da77c238..2663f90f22b 100644
--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/util/QueryParserTestBase.java
+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/util/QueryParserTestBase.java
@@ -290,7 +290,7 @@ public abstract class QueryParserTestBase extends LuceneTestCase {
expectedB.add(new TermQuery(new Term("field", "中")), BooleanClause.Occur.SHOULD);
expectedB.add(new TermQuery(new Term("field", "国")), BooleanClause.Occur.SHOULD);
Query expected = expectedB.build();
- expected.setBoost(0.5f);
+ expected = new BoostQuery(expected, 0.5f);
assertEquals(expected, getQuery("中国^0.5", analyzer));
}
@@ -308,8 +308,8 @@ public abstract class QueryParserTestBase extends LuceneTestCase {
// individual CJK chars as terms
SimpleCJKAnalyzer analyzer = new SimpleCJKAnalyzer();
- PhraseQuery expected = new PhraseQuery("field", "中", "国");
- expected.setBoost(0.5f);
+ Query expected = new PhraseQuery("field", "中", "国");
+ expected = new BoostQuery(expected, 0.5f);
assertEquals(expected, getQuery("\"中国\"^0.5", analyzer));
}
@@ -442,7 +442,8 @@ public abstract class QueryParserTestBase extends LuceneTestCase {
assertQueryEquals("term*germ^3", null, "term*germ^3.0");
assertTrue(getQuery("term*") instanceof PrefixQuery);
- assertTrue(getQuery("term*^2") instanceof PrefixQuery);
+ assertTrue(getQuery("term*^2") instanceof BoostQuery);
+ assertTrue(((BoostQuery) getQuery("term*^2")).getQuery() instanceof PrefixQuery);
assertTrue(getQuery("term~") instanceof FuzzyQuery);
assertTrue(getQuery("term~0.7") instanceof FuzzyQuery);
FuzzyQuery fq = (FuzzyQuery)getQuery("term~0.7");
@@ -867,10 +868,10 @@ public abstract class QueryParserTestBase extends LuceneTestCase {
assertNotNull(q);
q = getQuery("\"hello\"^2.0",qp);
assertNotNull(q);
- assertEquals(q.getBoost(), (float) 2.0, (float) 0.5);
+ assertEquals(((BoostQuery) q).getBoost(), (float) 2.0, (float) 0.5);
q = getQuery("hello^2.0",qp);
assertNotNull(q);
- assertEquals(q.getBoost(), (float) 2.0, (float) 0.5);
+ assertEquals(((BoostQuery) q).getBoost(), (float) 2.0, (float) 0.5);
q = getQuery("\"on\"^1.0",qp);
assertNotNull(q);
@@ -880,7 +881,7 @@ public abstract class QueryParserTestBase extends LuceneTestCase {
// "the" is a stop word so the result is an empty query:
assertNotNull(q);
assertEquals("", q.toString());
- assertEquals(1.0f, q.getBoost(), 0.01f);
+ assertFalse(q instanceof BoostQuery);
}
public void assertParseException(String queryString) throws Exception {
@@ -972,13 +973,13 @@ public abstract class QueryParserTestBase extends LuceneTestCase {
assertEquals(q, getQuery("/[a-z][123]/",qp));
qp.setLowercaseExpandedTerms(true);
assertEquals(q, getQuery("/[A-Z][123]/",qp));
- q.setBoost(0.5f);
- assertEquals(q, getQuery("/[A-Z][123]/^0.5",qp));
+ assertEquals(new BoostQuery(q, 0.5f), getQuery("/[A-Z][123]/^0.5",qp));
qp.setMultiTermRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_REWRITE);
q.setRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_REWRITE);
- assertTrue(getQuery("/[A-Z][123]/^0.5",qp) instanceof RegexpQuery);
- assertEquals(MultiTermQuery.SCORING_BOOLEAN_REWRITE, ((RegexpQuery)getQuery("/[A-Z][123]/^0.5",qp)).getRewriteMethod());
- assertEquals(q, getQuery("/[A-Z][123]/^0.5",qp));
+ assertTrue(getQuery("/[A-Z][123]/^0.5",qp) instanceof BoostQuery);
+ assertTrue(((BoostQuery) getQuery("/[A-Z][123]/^0.5",qp)).getQuery() instanceof RegexpQuery);
+ assertEquals(MultiTermQuery.SCORING_BOOLEAN_REWRITE, ((RegexpQuery) ((BoostQuery) getQuery("/[A-Z][123]/^0.5",qp)).getQuery()).getRewriteMethod());
+ assertEquals(new BoostQuery(q, 0.5f), getQuery("/[A-Z][123]/^0.5",qp));
qp.setMultiTermRewriteMethod(MultiTermQuery.CONSTANT_SCORE_REWRITE);
Query escaped = new RegexpQuery(new Term("field", "[a-z]\\/[123]"));
@@ -1028,6 +1029,8 @@ public abstract class QueryParserTestBase extends LuceneTestCase {
assertTrue("result is not a TermQuery", result instanceof TermQuery);
result = getQuery("(fieldX:xxxxx OR fieldy:xxxxxxxx)^2 AND (fieldx:the OR fieldy:foo)",qp);
assertNotNull("result is null and it shouldn't be", result);
+ assertTrue("result is not a BoostQuery", result instanceof BoostQuery);
+ result = ((BoostQuery) result).getQuery();
assertTrue("result is not a BooleanQuery", result instanceof BooleanQuery);
if (VERBOSE) System.out.println("Result: " + result);
assertTrue(((BooleanQuery) result).clauses().size() + " does not equal: " + 2, ((BooleanQuery) result).clauses().size() == 2);
@@ -1269,8 +1272,8 @@ public abstract class QueryParserTestBase extends LuceneTestCase {
assertEquals(new MatchAllDocsQuery(), getQuery(new MatchAllDocsQuery().toString(),qp));
// test parsing with non-default boost
- MatchAllDocsQuery query = new MatchAllDocsQuery();
- query.setBoost(2.3f);
+ Query query = new MatchAllDocsQuery();
+ query = new BoostQuery(query, 2.3f);
assertEquals(query, getQuery(query.toString(),qp));
setDefaultField(oldDefaultField);
}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDPointInBBoxQuery.java b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDPointInBBoxQuery.java
index 87eb05f85ac..a28d8f0e56a 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDPointInBBoxQuery.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDPointInBBoxQuery.java
@@ -17,12 +17,15 @@ package org.apache.lucene.bkdtree;
* limitations under the License.
*/
+import java.io.IOException;
+
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.ConstantScoreScorer;
import org.apache.lucene.search.ConstantScoreWeight;
import org.apache.lucene.search.DocIdSet;
@@ -31,9 +34,6 @@ import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.Weight;
-import org.apache.lucene.util.ToStringUtils;
-
-import java.io.IOException;
/** Finds all previously indexed points that fall within the specified boundings box.
*
@@ -114,14 +114,12 @@ public class BKDPointInBBoxQuery extends Query {
// E.g.: maxLon = -179, minLon = 179
BKDPointInBBoxQuery left = new BKDPointInBBoxQuery(field, minLat, maxLat, BKDTreeWriter.MIN_LON_INCL, maxLon);
- left.setBoost(getBoost());
q.add(new BooleanClause(left, BooleanClause.Occur.SHOULD));
BKDPointInBBoxQuery right = new BKDPointInBBoxQuery(field, minLat, maxLat, minLon, BKDTreeWriter.MAX_LON_INCL);
- right.setBoost(getBoost());
q.add(new BooleanClause(right, BooleanClause.Occur.SHOULD));
- return q.build();
+ return new ConstantScoreQuery(q.build());
} else {
- return this;
+ return super.rewrite(reader);
}
}
@@ -170,7 +168,6 @@ public class BKDPointInBBoxQuery extends Query {
.append(',')
.append(maxLat)
.append("]")
- .append(ToStringUtils.boost(getBoost()))
.toString();
}
}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDPointInPolygonQuery.java b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDPointInPolygonQuery.java
index 189fa462503..33126ac299f 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDPointInPolygonQuery.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/bkdtree/BKDPointInPolygonQuery.java
@@ -17,23 +17,21 @@ package org.apache.lucene.bkdtree;
* limitations under the License.
*/
+import java.io.IOException;
+import java.util.Arrays;
+
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.SortedNumericDocValues;
-import org.apache.lucene.index.Term;
+import org.apache.lucene.search.ConstantScoreScorer;
+import org.apache.lucene.search.ConstantScoreWeight;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.DocIdSetIterator;
-import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.Weight;
import org.apache.lucene.util.GeoUtils;
-import org.apache.lucene.util.ToStringUtils;
-
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Set;
/** Finds all previously indexed points that fall within the specified polygon.
*
@@ -109,38 +107,7 @@ public class BKDPointInPolygonQuery extends Query {
// TODO: except that the polygon verify is costly! The approximation should be all docs in all overlapping cells, and matches() should
// then check the polygon
- return new Weight(this) {
- private float queryNorm;
- private float queryWeight;
-
- @Override
- public void extractTerms(Set<Term> terms) {
- }
-
- @Override
- public float getValueForNormalization() throws IOException {
- queryWeight = getBoost();
- return queryWeight * queryWeight;
- }
-
- @Override
- public void normalize(float norm, float topLevelBoost) {
- queryNorm = norm * topLevelBoost;
- queryWeight *= queryNorm;
- }
-
- @Override
- public Explanation explain(LeafReaderContext context, int doc) throws IOException {
- final Scorer s = scorer(context);
- final boolean exists = s != null && s.advance(doc) == doc;
-
- if (exists) {
- return Explanation.match(queryWeight, BKDPointInPolygonQuery.this.toString() + ", product of:",
- Explanation.match(getBoost(), "boost"), Explanation.match(queryNorm, "queryNorm"));
- } else {
- return Explanation.noMatch(BKDPointInPolygonQuery.this.toString() + " doesn't match id " + doc);
- }
- }
+ return new ConstantScoreWeight(this) {
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
@@ -182,38 +149,7 @@ public class BKDPointInPolygonQuery extends Query {
final DocIdSetIterator disi = result.iterator();
- return new Scorer(this) {
-
- @Override
- public float score() throws IOException {
- return queryWeight;
- }
-
- @Override
- public int freq() throws IOException {
- return 1;
- }
-
- @Override
- public int docID() {
- return disi.docID();
- }
-
- @Override
- public int nextDoc() throws IOException {
- return disi.nextDoc();
- }
-
- @Override
- public int advance(int target) throws IOException {
- return disi.advance(target);
- }
-
- @Override
- public long cost() {
- return disi.cost();
- }
- };
+ return new ConstantScoreScorer(this, score(), disi);
}
};
}
@@ -263,7 +199,6 @@ public class BKDPointInPolygonQuery extends Query {
.append(polyLats[i])
.append("] ");
}
- sb.append(ToStringUtils.boost(getBoost()));
return sb.toString();
}
}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/rangetree/NumericRangeTreeQuery.java b/lucene/sandbox/src/java/org/apache/lucene/rangetree/NumericRangeTreeQuery.java
index d2118b9f24a..34723a0fe3a 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/rangetree/NumericRangeTreeQuery.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/rangetree/NumericRangeTreeQuery.java
@@ -29,7 +29,6 @@ import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.Weight;
-import org.apache.lucene.util.ToStringUtils;
import java.io.IOException;
@@ -153,7 +152,6 @@ public class NumericRangeTreeQuery extends Query {
.append(" TO ")
.append((maxValue == null) ? "*" : maxValue.toString())
.append(maxInclusive ? ']' : '}')
- .append(ToStringUtils.boost(getBoost()))
.toString();
}
}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/rangetree/SortedSetRangeTreeQuery.java b/lucene/sandbox/src/java/org/apache/lucene/rangetree/SortedSetRangeTreeQuery.java
index 348af84ae7e..07c36e9f4db 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/rangetree/SortedSetRangeTreeQuery.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/rangetree/SortedSetRangeTreeQuery.java
@@ -32,7 +32,6 @@ import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.Weight;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.ToStringUtils;
import java.io.IOException;
@@ -213,7 +212,6 @@ public class SortedSetRangeTreeQuery extends Query {
.append(" TO ")
.append((maxValue == null) ? "*" : maxValue.toString())
.append(maxInclusive ? ']' : '}')
- .append(ToStringUtils.boost(getBoost()))
.toString();
}
}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/FuzzyLikeThisQuery.java b/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/FuzzyLikeThisQuery.java
index 22d7be93dbf..0d32a82ef67 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/FuzzyLikeThisQuery.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/FuzzyLikeThisQuery.java
@@ -36,6 +36,7 @@ import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.BoostAttribute;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.MaxNonCompetitiveBoostAttribute;
import org.apache.lucene.search.Query;
@@ -329,8 +330,8 @@ public class FuzzyLikeThisQuery extends Query
//optimize where only one selected variant
ScoreTerm st= variants.get(0);
Query tq = newTermQuery(reader, st.term);
- tq.setBoost(st.score); // set the boost to a mix of IDF and score
- bq.add(tq, BooleanClause.Occur.SHOULD);
+ // set the boost to a mix of IDF and score
+ bq.add(new BoostQuery(tq, st.score), BooleanClause.Occur.SHOULD);
}
else
{
@@ -342,8 +343,8 @@ public class FuzzyLikeThisQuery extends Query
ScoreTerm st = iterator2.next();
// found a match
Query tq = newTermQuery(reader, st.term);
- tq.setBoost(st.score); // set the boost using the ScoreTerm's score
- termVariants.add(tq, BooleanClause.Occur.SHOULD); // add to query
+ // set the boost using the ScoreTerm's score
+ termVariants.add(new BoostQuery(tq, st.score), BooleanClause.Occur.SHOULD); // add to query
}
bq.add(termVariants.build(), BooleanClause.Occur.SHOULD); // add to query
}
@@ -351,7 +352,6 @@ public class FuzzyLikeThisQuery extends Query
//TODO possible alternative step 3 - organize above booleans into a new layer of field-based
// booleans with a minimum-should-match of NumFields-1?
Query q = bq.build();
- q.setBoost(getBoost());
this.rewrittenQuery=q;
return q;
}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/SlowFuzzyQuery.java b/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/SlowFuzzyQuery.java
index e50ab728432..42098c1887a 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/SlowFuzzyQuery.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/SlowFuzzyQuery.java
@@ -27,7 +27,6 @@ import org.apache.lucene.search.BooleanQuery; // javadocs
import org.apache.lucene.search.FuzzyQuery; // javadocs
import org.apache.lucene.search.MultiTermQuery;
import org.apache.lucene.util.AttributeSource;
-import org.apache.lucene.util.ToStringUtils;
import org.apache.lucene.util.automaton.LevenshteinAutomata;
/** Implements the classic fuzzy search query. The similarity measurement
@@ -166,7 +165,6 @@ public class SlowFuzzyQuery extends MultiTermQuery {
buffer.append(term.text());
buffer.append('~');
buffer.append(Float.toString(minimumSimilarity));
- buffer.append(ToStringUtils.boost(getBoost()));
return buffer.toString();
}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/regex/RegexQuery.java b/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/regex/RegexQuery.java
index 90fdbf158ac..45da11ba4be 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/regex/RegexQuery.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/regex/RegexQuery.java
@@ -74,7 +74,6 @@ public class RegexQuery extends MultiTermQuery implements RegexQueryCapable {
buffer.append(":");
}
buffer.append(term.text());
- buffer.append(ToStringUtils.boost(getBoost()));
return buffer.toString();
}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/search/DocValuesNumbersQuery.java b/lucene/sandbox/src/java/org/apache/lucene/search/DocValuesNumbersQuery.java
index ebd99f297e0..f48b96ca38e 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/search/DocValuesNumbersQuery.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/search/DocValuesNumbersQuery.java
@@ -73,7 +73,7 @@ public class DocValuesNumbersQuery extends Query {
@Override
public int hashCode() {
- return Objects.hash(field, numbers, getBoost());
+ return 31 * super.hashCode() + Objects.hash(field, numbers);
}
@Override
diff --git a/lucene/sandbox/src/java/org/apache/lucene/search/DocValuesRangeQuery.java b/lucene/sandbox/src/java/org/apache/lucene/search/DocValuesRangeQuery.java
index 2e463a1d440..6a6eae972e9 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/search/DocValuesRangeQuery.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/search/DocValuesRangeQuery.java
@@ -28,7 +28,6 @@ import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.ToStringUtils;
/**
* A range query that works on top of the doc values APIs. Such queries are
@@ -81,7 +80,7 @@ public final class DocValuesRangeQuery extends Query {
@Override
public boolean equals(Object obj) {
- if (obj instanceof DocValuesRangeQuery == false) {
+ if (super.equals(obj) == false) {
return false;
}
final DocValuesRangeQuery that = (DocValuesRangeQuery) obj;
@@ -95,7 +94,7 @@ public final class DocValuesRangeQuery extends Query {
@Override
public int hashCode() {
- return Objects.hash(field, lowerVal, upperVal, includeLower, includeUpper, getBoost());
+ return 31 * super.hashCode() + Objects.hash(field, lowerVal, upperVal, includeLower, includeUpper);
}
@Override
@@ -109,18 +108,15 @@ public final class DocValuesRangeQuery extends Query {
sb.append(" TO ");
sb.append(upperVal == null ? "*" : upperVal.toString());
sb.append(includeUpper ? ']' : '}');
- sb.append(ToStringUtils.boost(getBoost()));
return sb.toString();
}
@Override
public Query rewrite(IndexReader reader) throws IOException {
if (lowerVal == null && upperVal == null) {
- final FieldValueQuery rewritten = new FieldValueQuery(field);
- rewritten.setBoost(getBoost());
- return rewritten;
+ return new FieldValueQuery(field);
}
- return this;
+ return super.rewrite(reader);
}
@Override
diff --git a/lucene/sandbox/src/java/org/apache/lucene/search/DocValuesTermsQuery.java b/lucene/sandbox/src/java/org/apache/lucene/search/DocValuesTermsQuery.java
index 80326280aea..7a0ea8eb6da 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/search/DocValuesTermsQuery.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/search/DocValuesTermsQuery.java
@@ -121,13 +121,10 @@ public class DocValuesTermsQuery extends Query {
@Override
public boolean equals(Object obj) {
- if (obj instanceof DocValuesTermsQuery == false) {
+ if (super.equals(obj) == false) {
return false;
}
DocValuesTermsQuery that = (DocValuesTermsQuery) obj;
- if (!super.equals(obj)) {
- return false;
- }
if (!field.equals(that.field)) {
return false;
}
@@ -136,7 +133,7 @@ public class DocValuesTermsQuery extends Query {
@Override
public int hashCode() {
- return Objects.hash(field, Arrays.asList(terms), getBoost());
+ return 31 * super.hashCode() + Objects.hash(field, Arrays.asList(terms));
}
@Override
diff --git a/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointDistanceQuery.java b/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointDistanceQuery.java
index 4ff86d3f394..a0f3afd65fb 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointDistanceQuery.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointDistanceQuery.java
@@ -20,7 +20,6 @@ package org.apache.lucene.search;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.util.GeoProjectionUtils;
import org.apache.lucene.util.GeoUtils;
-import org.apache.lucene.util.ToStringUtils;
/** Implements a simple point distance query on a GeoPoint field. This is based on
* {@link org.apache.lucene.search.GeoPointInBBoxQuery} and is implemented using a two phase approach. First,
@@ -74,11 +73,9 @@ public final class GeoPointDistanceQuery extends GeoPointInBBoxQuery {
GeoPointDistanceQueryImpl left = new GeoPointDistanceQueryImpl(field, this, new GeoBoundingBox(-180.0D, maxLon,
minLat, maxLat));
- left.setBoost(getBoost());
bqb.add(new BooleanClause(left, BooleanClause.Occur.SHOULD));
GeoPointDistanceQueryImpl right = new GeoPointDistanceQueryImpl(field, this, new GeoBoundingBox(minLon, 180.0D,
minLat, maxLat));
- right.setBoost(getBoost());
bqb.add(new BooleanClause(right, BooleanClause.Occur.SHOULD));
return bqb.build();
}
@@ -151,7 +148,6 @@ public final class GeoPointDistanceQuery extends GeoPointInBBoxQuery {
.append(',')
.append(maxLat)
.append("]")
- .append(ToStringUtils.boost(getBoost()))
.toString();
}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointInBBoxQuery.java b/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointInBBoxQuery.java
index a943c5d1966..e776a491939 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointInBBoxQuery.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointInBBoxQuery.java
@@ -18,7 +18,6 @@ package org.apache.lucene.search;
*/
import org.apache.lucene.index.IndexReader;
-import org.apache.lucene.util.ToStringUtils;
/** Implements a simple bounding box query on a GeoPoint field. This is inspired by
* {@link org.apache.lucene.search.NumericRangeQuery} and is implemented using a
@@ -60,10 +59,8 @@ public class GeoPointInBBoxQuery extends Query {
BooleanQuery.Builder bqb = new BooleanQuery.Builder();
GeoPointInBBoxQueryImpl left = new GeoPointInBBoxQueryImpl(field, -180.0D, minLat, maxLon, maxLat);
- left.setBoost(getBoost());
bqb.add(new BooleanClause(left, BooleanClause.Occur.SHOULD));
GeoPointInBBoxQueryImpl right = new GeoPointInBBoxQueryImpl(field, minLon, minLat, 180.0D, maxLat);
- right.setBoost(getBoost());
bqb.add(new BooleanClause(right, BooleanClause.Occur.SHOULD));
return bqb.build();
}
@@ -90,7 +87,6 @@ public class GeoPointInBBoxQuery extends Query {
.append(',')
.append(maxLat)
.append("]")
- .append(ToStringUtils.boost(getBoost()))
.toString();
}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointInBBoxQueryImpl.java b/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointInBBoxQueryImpl.java
index b052a81eb7d..b794d3fcae4 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointInBBoxQueryImpl.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointInBBoxQueryImpl.java
@@ -138,7 +138,6 @@ class GeoPointInBBoxQueryImpl extends GeoPointTermQuery {
.append(',')
.append(maxLat)
.append("]")
- .append(ToStringUtils.boost(getBoost()))
.toString();
}
}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointInPolygonQuery.java b/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointInPolygonQuery.java
index cb446672a4b..dcccd10ce21 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointInPolygonQuery.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointInPolygonQuery.java
@@ -139,7 +139,6 @@ public final class GeoPointInPolygonQuery extends GeoPointInBBoxQueryImpl {
.append(y[i])
.append("] ");
}
- sb.append(ToStringUtils.boost(getBoost()));
return sb.toString();
}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointTermQuery.java b/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointTermQuery.java
index 7f7fd13746a..48de1ccb2c5 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointTermQuery.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointTermQuery.java
@@ -63,9 +63,7 @@ abstract class GeoPointTermQuery extends MultiTermQuery {
public static final RewriteMethod GEO_CONSTANT_SCORE_REWRITE = new RewriteMethod() {
@Override
public Query rewrite(IndexReader reader, MultiTermQuery query) {
- Query result = new GeoPointTermQueryConstantScoreWrapper<>((GeoPointTermQuery)query);
- result.setBoost(query.getBoost());
- return result;
+ return new GeoPointTermQueryConstantScoreWrapper<>((GeoPointTermQuery)query);
}
};
diff --git a/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointTermQueryConstantScoreWrapper.java b/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointTermQueryConstantScoreWrapper.java
index a3cd4821c19..81f64c2dce9 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointTermQueryConstantScoreWrapper.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/search/GeoPointTermQueryConstantScoreWrapper.java
@@ -51,7 +51,7 @@ final class GeoPointTermQueryConstantScoreWrapper <Q extends GeoPointTermQuery>
return false;
}
final GeoPointTermQueryConstantScoreWrapper<?> that = (GeoPointTermQueryConstantScoreWrapper<?>) o;
- return this.query.equals(that.query) && this.getBoost() == that.getBoost();
+ return this.query.equals(that.query);
}
@Override
diff --git a/lucene/sandbox/src/java/org/apache/lucene/search/TermAutomatonQuery.java b/lucene/sandbox/src/java/org/apache/lucene/search/TermAutomatonQuery.java
index 2a172d9af36..60b1e682b1c 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/search/TermAutomatonQuery.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/search/TermAutomatonQuery.java
@@ -350,8 +350,7 @@ public class TermAutomatonQuery extends Query {
}
}
- stats = similarity.computeWeight(getBoost(),
- searcher.collectionStatistics(field),
+ stats = similarity.computeWeight(searcher.collectionStatistics(field),
allTermStats.toArray(new TermStatistics[allTermStats.size()]));
}
@@ -375,8 +374,8 @@ public class TermAutomatonQuery extends Query {
}
@Override
- public void normalize(float queryNorm, float topLevelBoost) {
- stats.normalize(queryNorm, topLevelBoost);
+ public void normalize(float queryNorm, float boost) {
+ stats.normalize(queryNorm, boost);
}
@Override
diff --git a/lucene/sandbox/src/test/org/apache/lucene/search/TestDocValuesNumbersQuery.java b/lucene/sandbox/src/test/org/apache/lucene/search/TestDocValuesNumbersQuery.java
index 771e2cea95d..65ae541de5f 100644
--- a/lucene/sandbox/src/test/org/apache/lucene/search/TestDocValuesNumbersQuery.java
+++ b/lucene/sandbox/src/test/org/apache/lucene/search/TestDocValuesNumbersQuery.java
@@ -94,19 +94,15 @@ public class TestDocValuesNumbersQuery extends LuceneTestCase {
for (Long number : queryNumbers) {
bq.add(new TermQuery(new Term("text", number.toString())), Occur.SHOULD);
}
- Query q1 = new ConstantScoreQuery(bq.build());
- q1.setBoost(boost);
+ Query q1 = new BoostQuery(new ConstantScoreQuery(bq.build()), boost);
- Query q2 = new DocValuesNumbersQuery("long", queryNumbers);
- q2.setBoost(boost);
+ Query q2 = new BoostQuery(new DocValuesNumbersQuery("long", queryNumbers), boost);
assertSameMatches(searcher, q1, q2, true);
- Query q3 = new DocValuesNumbersQuery("twolongs", queryNumbers);
- q3.setBoost(boost);
+ Query q3 = new BoostQuery(new DocValuesNumbersQuery("twolongs", queryNumbers), boost);
assertSameMatches(searcher, q1, q3, true);
- Query q4 = new DocValuesNumbersQuery("twolongs", queryNumbersX2);
- q4.setBoost(boost);
+ Query q4 = new BoostQuery(new DocValuesNumbersQuery("twolongs", queryNumbersX2), boost);
assertSameMatches(searcher, q1, q4, true);
}
@@ -158,10 +154,8 @@ public class TestDocValuesNumbersQuery extends LuceneTestCase {
for (Long number : queryNumbers) {
bq.add(new TermQuery(new Term("text", number.toString())), Occur.SHOULD);
}
- Query q1 = new ConstantScoreQuery(bq.build());
- q1.setBoost(boost);
- final Query q2 = new DocValuesNumbersQuery("long", queryNumbers);
- q2.setBoost(boost);
+ Query q1 = new BoostQuery(new ConstantScoreQuery(bq.build()), boost);
+ final Query q2 = new BoostQuery(new DocValuesNumbersQuery("long", queryNumbers), boost);
BooleanQuery.Builder bq1 = new BooleanQuery.Builder();
bq1.add(q1, Occur.MUST);
diff --git a/lucene/sandbox/src/test/org/apache/lucene/search/TestDocValuesRangeQuery.java b/lucene/sandbox/src/test/org/apache/lucene/search/TestDocValuesRangeQuery.java
index b6cf38f070a..288849e8925 100644
--- a/lucene/sandbox/src/test/org/apache/lucene/search/TestDocValuesRangeQuery.java
+++ b/lucene/sandbox/src/test/org/apache/lucene/search/TestDocValuesRangeQuery.java
@@ -156,16 +156,12 @@ public class TestDocValuesRangeQuery extends LuceneTestCase {
final float boost = random().nextFloat() * 10;
- final Query q1 = DocValuesRangeQuery.newLongRange("dv1", min, max, minInclusive, maxInclusive);
- q1.setBoost(boost);
- final ConstantScoreQuery csq1 = new ConstantScoreQuery(DocValuesRangeQuery.newLongRange("dv1", min, max, minInclusive, maxInclusive));
- csq1.setBoost(boost);
+ final Query q1 = new BoostQuery(DocValuesRangeQuery.newLongRange("dv1", min, max, minInclusive, maxInclusive), boost);
+ final Query csq1 = new BoostQuery(new ConstantScoreQuery(DocValuesRangeQuery.newLongRange("dv1", min, max, minInclusive, maxInclusive)), boost);
assertSameMatches(searcher, q1, csq1, true);
- final Query q2 = DocValuesRangeQuery.newBytesRefRange("dv2", toSortableBytes(min), toSortableBytes(max), minInclusive, maxInclusive);
- q2.setBoost(boost);
- final ConstantScoreQuery csq2 = new ConstantScoreQuery(DocValuesRangeQuery.newBytesRefRange("dv2", toSortableBytes(min), toSortableBytes(max), minInclusive, maxInclusive));
- csq2.setBoost(boost);
+ final Query q2 = new BoostQuery(DocValuesRangeQuery.newBytesRefRange("dv2", toSortableBytes(min), toSortableBytes(max), minInclusive, maxInclusive), boost);
+ final Query csq2 = new BoostQuery(new ConstantScoreQuery(DocValuesRangeQuery.newBytesRefRange("dv2", toSortableBytes(min), toSortableBytes(max), minInclusive, maxInclusive)), boost);
assertSameMatches(searcher, q2, csq2, true);
}
diff --git a/lucene/sandbox/src/test/org/apache/lucene/search/TestDocValuesTermsQuery.java b/lucene/sandbox/src/test/org/apache/lucene/search/TestDocValuesTermsQuery.java
index c9cc6a96a1f..5f4c63c5987 100644
--- a/lucene/sandbox/src/test/org/apache/lucene/search/TestDocValuesTermsQuery.java
+++ b/lucene/sandbox/src/test/org/apache/lucene/search/TestDocValuesTermsQuery.java
@@ -88,14 +88,12 @@ public class TestDocValuesTermsQuery extends LuceneTestCase {
for (Term term : queryTerms) {
bq.add(new TermQuery(term), Occur.SHOULD);
}
- Query q1 = new ConstantScoreQuery(bq.build());
- q1.setBoost(boost);
+ Query q1 = new BoostQuery(new ConstantScoreQuery(bq.build()), boost);
List<String> bytesTerms = new ArrayList<>();
for (Term term : queryTerms) {
bytesTerms.add(term.text());
}
- final Query q2 = new DocValuesTermsQuery("f", bytesTerms.toArray(new String[0]));
- q2.setBoost(boost);
+ final Query q2 = new BoostQuery(new DocValuesTermsQuery("f", bytesTerms.toArray(new String[0])), boost);
assertSameMatches(searcher, q1, q2, true);
}
@@ -148,14 +146,12 @@ public class TestDocValuesTermsQuery extends LuceneTestCase {
for (Term term : queryTerms) {
bq.add(new TermQuery(term), Occur.SHOULD);
}
- Query q1 = new ConstantScoreQuery(bq.build());
- q1.setBoost(boost);
+ Query q1 = new BoostQuery(new ConstantScoreQuery(bq.build()), boost);
List<String> bytesTerms = new ArrayList<>();
for (Term term : queryTerms) {
bytesTerms.add(term.text());
}
- final Query q2 = new DocValuesTermsQuery("f", bytesTerms.toArray(new String[0]));
- q2.setBoost(boost);
+ final Query q2 = new BoostQuery(new DocValuesTermsQuery("f", bytesTerms.toArray(new String[0])), boost);
BooleanQuery.Builder bq1 = new BooleanQuery.Builder();
bq1.add(q1, Occur.MUST);
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/composite/CompositeVerifyQuery.java b/lucene/spatial/src/java/org/apache/lucene/spatial/composite/CompositeVerifyQuery.java
index 0db2c0db680..d49fb4108b0 100644
--- a/lucene/spatial/src/java/org/apache/lucene/spatial/composite/CompositeVerifyQuery.java
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/composite/CompositeVerifyQuery.java
@@ -55,7 +55,7 @@ public class CompositeVerifyQuery extends Query {
if (rewritten != indexQuery) {
return new CompositeVerifyQuery(rewritten, predicateValueSource);
}
- return this;
+ return super.rewrite(reader);
}
@Override
diff --git a/lucene/spatial3d/src/java/org/apache/lucene/bkdtree3d/PointInGeo3DShapeQuery.java b/lucene/spatial3d/src/java/org/apache/lucene/bkdtree3d/PointInGeo3DShapeQuery.java
index 960e9c59b70..7db4972adf7 100644
--- a/lucene/spatial3d/src/java/org/apache/lucene/bkdtree3d/PointInGeo3DShapeQuery.java
+++ b/lucene/spatial3d/src/java/org/apache/lucene/bkdtree3d/PointInGeo3DShapeQuery.java
@@ -34,7 +34,6 @@ import org.apache.lucene.search.Query;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.Weight;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.ToStringUtils;
import java.io.IOException;
@@ -218,7 +217,6 @@ public class PointInGeo3DShapeQuery extends Query {
sb.append(planetModel);
sb.append(" Shape: ");
sb.append(shape);
- sb.append(ToStringUtils.boost(getBoost()));
return sb.toString();
}
}
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/spell/SpellChecker.java b/lucene/suggest/src/java/org/apache/lucene/search/spell/SpellChecker.java
index e3e76519276..d90fcf6fb52 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/spell/SpellChecker.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/spell/SpellChecker.java
@@ -38,6 +38,7 @@ import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
@@ -417,8 +418,7 @@ public class SpellChecker implements java.io.Closeable {
*/
private static void add(BooleanQuery.Builder q, String name, String value, float boost) {
Query tq = new TermQuery(new Term(name, value));
- tq.setBoost(boost);
- q.add(new BooleanClause(tq, BooleanClause.Occur.SHOULD));
+ q.add(new BooleanClause(new BoostQuery(tq, boost), BooleanClause.Occur.SHOULD));
}
/**
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionQuery.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionQuery.java
index 464fbf522b2..9c8d5f0cbb4 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionQuery.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionQuery.java
@@ -132,7 +132,7 @@ public abstract class CompletionQuery extends Query {
}
}
}
- return this;
+ return super.rewrite(reader);
}
@Override
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionWeight.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionWeight.java
index 19171b6239d..95166a841ae 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionWeight.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionWeight.java
@@ -150,6 +150,6 @@ public class CompletionWeight extends Weight {
}
@Override
- public void normalize(float norm, float topLevelBoost) {
+ public void normalize(float norm, float boost) {
}
}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/index/BaseNormsFormatTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/index/BaseNormsFormatTestCase.java
index 8f566c6b693..f2676bb2e74 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/index/BaseNormsFormatTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/index/BaseNormsFormatTestCase.java
@@ -322,7 +322,7 @@ public abstract class BaseNormsFormatTestCase extends BaseIndexFileFormatTestCas
}
@Override
- public SimWeight computeWeight(float queryBoost, CollectionStatistics collectionStats, TermStatistics... termStats) {
+ public SimWeight computeWeight(CollectionStatistics collectionStats, TermStatistics... termStats) {
throw new UnsupportedOperationException();
}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/search/AssertingIndexSearcher.java b/lucene/test-framework/src/java/org/apache/lucene/search/AssertingIndexSearcher.java
index 38909f7ba02..43d07d610c8 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/search/AssertingIndexSearcher.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/search/AssertingIndexSearcher.java
@@ -59,7 +59,7 @@ public class AssertingIndexSearcher extends IndexSearcher {
return new AssertingWeight(random, w, needsScores) {
@Override
- public void normalize(float norm, float topLevelBoost) {
+ public void normalize(float norm, float boost) {
throw new IllegalStateException("Weight already normalized.");
}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/search/AssertingQuery.java b/lucene/test-framework/src/java/org/apache/lucene/search/AssertingQuery.java
index 76567e670c5..24672ea5947 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/search/AssertingQuery.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/search/AssertingQuery.java
@@ -23,7 +23,7 @@ import java.util.Random;
import org.apache.lucene.index.IndexReader;
/** Assertion-enabled query. */
-public class AssertingQuery extends Query {
+public final class AssertingQuery extends Query {
private final Random random;
private final Query in;
@@ -63,29 +63,14 @@ public class AssertingQuery extends Query {
return -in.hashCode();
}
- @Override
- public Query clone() {
- return wrap(new Random(random.nextLong()), in.clone());
- }
-
@Override
public Query rewrite(IndexReader reader) throws IOException {
final Query rewritten = in.rewrite(reader);
if (rewritten == in) {
- return this;
+ return super.rewrite(reader);
} else {
return wrap(new Random(random.nextLong()), rewritten);
}
}
- @Override
- public float getBoost() {
- return in.getBoost();
- }
-
- @Override
- public void setBoost(float b) {
- in.setBoost(b);
- }
-
}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/search/AssertingWeight.java b/lucene/test-framework/src/java/org/apache/lucene/search/AssertingWeight.java
index 4616166037f..6ab520d1976 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/search/AssertingWeight.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/search/AssertingWeight.java
@@ -53,8 +53,8 @@ class AssertingWeight extends Weight {
}
@Override
- public void normalize(float norm, float topLevelBoost) {
- in.normalize(norm, topLevelBoost);
+ public void normalize(float norm, float boost) {
+ in.normalize(norm, boost);
}
@Override
diff --git a/lucene/test-framework/src/java/org/apache/lucene/search/QueryUtils.java b/lucene/test-framework/src/java/org/apache/lucene/search/QueryUtils.java
index aa93e701e47..3bd884c5459 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/search/QueryUtils.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/search/QueryUtils.java
@@ -58,12 +58,7 @@ public class QueryUtils {
/** check very basic hashCode and equals */
public static void checkHashEquals(Query q) {
- Query q2 = q.clone();
- checkEqual(q,q2);
-
- Query q3 = q.clone();
- q3.setBoost(7.21792348f);
- checkUnequal(q,q3);
+ checkEqual(q,q);
// test that a class check is done so that no exception is thrown
// in the implementation of equals()
@@ -73,7 +68,6 @@ public class QueryUtils {
return "My Whacky Query";
}
};
- whacky.setBoost(q.getBoost());
checkUnequal(q, whacky);
// null test
@@ -125,10 +119,6 @@ public class QueryUtils {
check(random, q1, wrapUnderlyingReader(random, s, +1), false);
}
checkExplanations(q1,s);
-
- Query q2 = q1.clone();
- checkEqual(s.rewrite(q1),
- s.rewrite(q2));
}
} catch (IOException e) {
throw new RuntimeException(e);
diff --git a/lucene/test-framework/src/java/org/apache/lucene/search/RandomApproximationQuery.java b/lucene/test-framework/src/java/org/apache/lucene/search/RandomApproximationQuery.java
index 02616b8f9e9..88cfd77cb4a 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/search/RandomApproximationQuery.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/search/RandomApproximationQuery.java
@@ -47,18 +47,15 @@ public class RandomApproximationQuery extends Query {
if (rewritten != query) {
return new RandomApproximationQuery(rewritten, random);
}
- return this;
+ return super.rewrite(reader);
}
@Override
public boolean equals(Object obj) {
- if (obj instanceof RandomApproximationQuery == false) {
+ if (super.equals(obj) == false) {
return false;
}
final RandomApproximationQuery that = (RandomApproximationQuery) obj;
- if (this.getBoost() != that.getBoost()) {
- return false;
- }
if (this.query.equals(that.query) == false) {
return false;
}
@@ -67,7 +64,7 @@ public class RandomApproximationQuery extends Query {
@Override
public int hashCode() {
- return 31 * query.hashCode() + Float.floatToIntBits(getBoost());
+ return 31 * super.hashCode() + query.hashCode();
}
@Override
@@ -108,8 +105,8 @@ public class RandomApproximationQuery extends Query {
}
@Override
- public void normalize(float norm, float topLevelBoost) {
- weight.normalize(norm, topLevelBoost);
+ public void normalize(float norm, float boost) {
+ weight.normalize(norm, boost);
}
@Override
diff --git a/lucene/test-framework/src/java/org/apache/lucene/search/spans/AssertingSpanQuery.java b/lucene/test-framework/src/java/org/apache/lucene/search/spans/AssertingSpanQuery.java
index 8131491edf6..b1766bcbe18 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/search/spans/AssertingSpanQuery.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/search/spans/AssertingSpanQuery.java
@@ -47,21 +47,11 @@ public class AssertingSpanQuery extends SpanQuery {
return new AssertingSpanWeight(searcher, weight);
}
- @Override
- public void setBoost(float b) {
- in.setBoost(b);
- }
-
- @Override
- public float getBoost() {
- return in.getBoost();
- }
-
@Override
public Query rewrite(IndexReader reader) throws IOException {
Query q = in.rewrite(reader);
if (q == in) {
- return this;
+ return super.rewrite(reader);
} else if (q instanceof SpanQuery) {
return new AssertingSpanQuery((SpanQuery) q);
} else {
@@ -71,7 +61,7 @@ public class AssertingSpanQuery extends SpanQuery {
@Override
public Query clone() {
- return new AssertingSpanQuery((SpanQuery) in.clone());
+ return new AssertingSpanQuery((SpanQuery) in);
}
@Override
diff --git a/lucene/test-framework/src/java/org/apache/lucene/search/spans/AssertingSpanWeight.java b/lucene/test-framework/src/java/org/apache/lucene/search/spans/AssertingSpanWeight.java
index c180b3e6666..5c8197d325e 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/search/spans/AssertingSpanWeight.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/search/spans/AssertingSpanWeight.java
@@ -69,8 +69,8 @@ public class AssertingSpanWeight extends SpanWeight {
}
@Override
- public void normalize(float queryNorm, float topLevelBoost) {
- in.normalize(queryNorm, topLevelBoost);
+ public void normalize(float queryNorm, float boost) {
+ in.normalize(queryNorm, boost);
}
@Override
diff --git a/solr/core/src/java/org/apache/solr/handler/MoreLikeThisHandler.java b/solr/core/src/java/org/apache/solr/handler/MoreLikeThisHandler.java
index 6df2de5221f..cfa0a67a790 100644
--- a/solr/core/src/java/org/apache/solr/handler/MoreLikeThisHandler.java
+++ b/solr/core/src/java/org/apache/solr/handler/MoreLikeThisHandler.java
@@ -24,6 +24,7 @@ import org.apache.lucene.index.Term;
import org.apache.lucene.queries.mlt.MoreLikeThis;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.solr.common.SolrException;
@@ -372,17 +373,16 @@ public class MoreLikeThisHandler extends RequestHandlerBase
}
private Query getBoostedQuery(Query mltquery) {
- BooleanQuery boostedQuery = (BooleanQuery)mltquery.clone();
+ BooleanQuery boostedQuery = (BooleanQuery)mltquery;
if (boostFields.size() > 0) {
BooleanQuery.Builder newQ = new BooleanQuery.Builder();
newQ.setDisableCoord(boostedQuery.isCoordDisabled());
newQ.setMinimumNumberShouldMatch(boostedQuery.getMinimumNumberShouldMatch());
for (BooleanClause clause : boostedQuery) {
- TermQuery q = (TermQuery) clause.getQuery();
- Float b = this.boostFields.get(q.getTerm().field());
+ Query q = clause.getQuery();
+ Float b = this.boostFields.get(((TermQuery) q).getTerm().field());
if (b != null) {
- q = (TermQuery) q.clone();
- q.setBoost(b*q.getBoost());
+ q = new BoostQuery(q, b);
}
newQ.add(q, clause.getOccur());
}
@@ -482,10 +482,16 @@ public class MoreLikeThisHandler extends RequestHandlerBase
{
Collection<BooleanClause> clauses = ((BooleanQuery)query).clauses();
for( BooleanClause o : clauses ) {
- TermQuery q = (TermQuery) o.getQuery();
+ Query q = o.getQuery();
+ float boost = 1f;
+ if (query instanceof BoostQuery) {
+ BoostQuery bq = (BoostQuery) q;
+ q = bq.getQuery();
+ boost = bq.getBoost();
+ }
InterestingTerm it = new InterestingTerm();
- it.boost = q.getBoost();
- it.term = q.getTerm();
+ it.boost = boost;
+ it.term = ((TermQuery) q).getTerm();
terms.add( it );
}
// alternatively we could use
diff --git a/solr/core/src/java/org/apache/solr/handler/component/QueryElevationComponent.java b/solr/core/src/java/org/apache/solr/handler/component/QueryElevationComponent.java
index 1ee1f26c359..e12a8f35b69 100644
--- a/solr/core/src/java/org/apache/solr/handler/component/QueryElevationComponent.java
+++ b/solr/core/src/java/org/apache/solr/handler/component/QueryElevationComponent.java
@@ -30,6 +30,7 @@ import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.FieldComparator;
import org.apache.lucene.search.FieldComparatorSource;
@@ -153,7 +154,6 @@ public class QueryElevationComponent extends SearchComponent implements SolrCore
this.priority.put(new BytesRef(id), max--);
}
this.include = include.build();
- this.include.setBoost(0);
if (exclude == null || exclude.isEmpty()) {
this.exclude = null;
@@ -420,12 +420,12 @@ public class QueryElevationComponent extends SearchComponent implements SolrCore
// Change the query to insert forced documents
if (exclusive == true) {
//we only want these results
- rb.setQuery(booster.include);
+ rb.setQuery(new BoostQuery(booster.include, 0f));
} else {
BooleanQuery.Builder newq = new BooleanQuery.Builder();
newq.setDisableCoord(true);
newq.add(query, BooleanClause.Occur.SHOULD);
- newq.add(booster.include, BooleanClause.Occur.SHOULD);
+ newq.add(new BoostQuery(booster.include, 0f), BooleanClause.Occur.SHOULD);
if (booster.exclude != null) {
if (markExcludes == false) {
for (TermQuery tq : booster.exclude) {
diff --git a/solr/core/src/java/org/apache/solr/parser/SolrQueryParserBase.java b/solr/core/src/java/org/apache/solr/parser/SolrQueryParserBase.java
index 91f6ddde8f2..2ddcabe3cf8 100644
--- a/solr/core/src/java/org/apache/solr/parser/SolrQueryParserBase.java
+++ b/solr/core/src/java/org/apache/solr/parser/SolrQueryParserBase.java
@@ -29,6 +29,7 @@ import org.apache.lucene.index.Term;
import org.apache.lucene.search.AutomatonQuery;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
@@ -398,7 +399,6 @@ public abstract class SolrQueryParserBase extends QueryBuilder {
}
builder.setSlop(slop);
query = builder.build();
- query.setBoost(pq.getBoost());
}
if (query instanceof MultiPhraseQuery) {
((MultiPhraseQuery) query).setSlop(slop);
@@ -572,19 +572,17 @@ public abstract class SolrQueryParserBase extends QueryBuilder {
// syntax looks like foo:x^=3
float val = Float.parseFloat(boost.image.substring(1));
Query newQ = q;
- if (q instanceof FilterQuery || q instanceof ConstantScoreQuery || q instanceof SolrConstantScoreQuery) {
- newQ.setBoost(val);
+ if (q instanceof ConstantScoreQuery || q instanceof SolrConstantScoreQuery) {
+ // skip
} else {
newQ = new ConstantScoreQuery(q);
- newQ.setBoost(val);
}
- return newQ;
+ return new BoostQuery(newQ, val);
}
float boostVal = Float.parseFloat(boost.image);
- q.setBoost(q.getBoost() * boostVal);
- return q;
+ return new BoostQuery(q, boostVal);
}
@@ -821,7 +819,6 @@ public abstract class SolrQueryParserBase extends QueryBuilder {
buffer.append(":");
}
buffer.append(term.text());
- buffer.append(ToStringUtils.boost(getBoost()));
return buffer.toString();
}
};
diff --git a/solr/core/src/java/org/apache/solr/query/FilterQuery.java b/solr/core/src/java/org/apache/solr/query/FilterQuery.java
index dc7105a57aa..970e0ff1a44 100644
--- a/solr/core/src/java/org/apache/solr/query/FilterQuery.java
+++ b/solr/core/src/java/org/apache/solr/query/FilterQuery.java
@@ -20,11 +20,11 @@ package org.apache.solr.query;
import java.io.IOException;
import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Weight;
-import org.apache.lucene.util.ToStringUtils;
import org.apache.solr.search.DocSet;
import org.apache.solr.search.ExtendedQueryBase;
import org.apache.solr.search.SolrConstantScoreQuery;
@@ -35,7 +35,6 @@ public class FilterQuery extends ExtendedQueryBase {
public FilterQuery(Query q) {
this.q = q;
- setBoost(0); // default boost is 0;
}
public Query getQuery() {
@@ -51,16 +50,15 @@ public class FilterQuery extends ExtendedQueryBase {
public boolean equals(Object obj) {
if (!(obj instanceof FilterQuery)) return false;
FilterQuery fq = (FilterQuery)obj;
- return this.q.equals(fq.q) && this.getBoost() == fq.getBoost();
+ return this.q.equals(fq.q);
}
@Override
public String toString(String field) {
StringBuilder sb = new StringBuilder();
- sb.append("field(");
+ sb.append("filter(");
sb.append(q.toString(""));
sb.append(')');
- sb.append(ToStringUtils.boost(getBoost()));
return sb.toString();
}
@@ -69,9 +67,7 @@ public class FilterQuery extends ExtendedQueryBase {
public Query rewrite(IndexReader reader) throws IOException {
Query newQ = q.rewrite(reader);
if (newQ != q) {
- FilterQuery fq = new FilterQuery(newQ);
- fq.setBoost(this.getBoost());
- return fq;
+ return new FilterQuery(newQ);
} else {
return this;
}
@@ -83,17 +79,13 @@ public class FilterQuery extends ExtendedQueryBase {
if (!(searcher instanceof SolrIndexSearcher)) {
// delete-by-query won't have SolrIndexSearcher
- ConstantScoreQuery csq = new ConstantScoreQuery(q);
- csq.setBoost(this.getBoost());
- return csq.createWeight(searcher, needScores);
+ return new BoostQuery(new ConstantScoreQuery(q), 0).createWeight(searcher, needScores);
}
SolrIndexSearcher solrSearcher = (SolrIndexSearcher)searcher;
DocSet docs = solrSearcher.getDocSet(q);
// reqInfo.addCloseHook(docs); // needed for off-heap refcounting
- SolrConstantScoreQuery csq = new SolrConstantScoreQuery( docs.getTopFilter() );
- csq.setBoost( this.getBoost() );
- return csq.createWeight(searcher, needScores);
+ return new BoostQuery(new SolrConstantScoreQuery(docs.getTopFilter()), 0).createWeight(searcher, needScores);
}
}
diff --git a/solr/core/src/java/org/apache/solr/schema/LatLonType.java b/solr/core/src/java/org/apache/solr/schema/LatLonType.java
index ec157df6043..83bee0a4594 100644
--- a/solr/core/src/java/org/apache/solr/schema/LatLonType.java
+++ b/solr/core/src/java/org/apache/solr/schema/LatLonType.java
@@ -20,7 +20,6 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-import java.util.Set;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.index.IndexReader;
@@ -31,6 +30,7 @@ import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.valuesource.VectorValueSource;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.ConstantScoreWeight;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
@@ -38,7 +38,6 @@ import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.Weight;
import org.apache.lucene.uninverting.UninvertingReader.Type;
-import org.apache.lucene.util.Bits;
import org.apache.solr.common.SolrException;
import org.apache.solr.response.TextResponseWriter;
import org.apache.solr.search.DelegatingCollector;
@@ -308,10 +307,8 @@ class SpatialDistanceQuery extends ExtendedQueryBase implements PostFilter {
return bboxQuery != null ? bboxQuery.rewrite(reader) : this;
}
- protected class SpatialWeight extends Weight {
+ protected class SpatialWeight extends ConstantScoreWeight {
protected IndexSearcher searcher;
- protected float queryNorm;
- protected float queryWeight;
protected Map latContext;
protected Map lonContext;
@@ -324,29 +321,14 @@ class SpatialDistanceQuery extends ExtendedQueryBase implements PostFilter {
lonSource.createWeight(lonContext, searcher);
}
- @Override
- public void extractTerms(Set terms) {}
-
- @Override
- public float getValueForNormalization() throws IOException {
- queryWeight = getBoost();
- return queryWeight * queryWeight;
- }
-
- @Override
- public void normalize(float norm, float topLevelBoost) {
- this.queryNorm = norm * topLevelBoost;
- queryWeight *= this.queryNorm;
- }
-
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
- return new SpatialScorer(context, this, queryWeight);
+ return new SpatialScorer(context, this, score());
}
@Override
public Explanation explain(LeafReaderContext context, int doc) throws IOException {
- return ((SpatialScorer)scorer(context)).explain(doc);
+ return ((SpatialScorer)scorer(context)).explain(super.explain(context, doc), doc);
}
}
@@ -484,24 +466,15 @@ class SpatialDistanceQuery extends ExtendedQueryBase implements PostFilter {
return maxDoc;
}
- public Explanation explain(int doc) throws IOException {
- advance(doc);
- boolean matched = this.doc == doc;
- this.doc = doc;
-
- float sc = matched ? score() : 0;
+ public Explanation explain(Explanation base, int doc) throws IOException {
+ if (base.isMatch() == false) {
+ return base;
+ }
double dist = dist(latVals.doubleVal(doc), lonVals.doubleVal(doc));
String description = SpatialDistanceQuery.this.toString();
-
- if (matched) {
- return Explanation.match(sc, description + " product of:",
- Explanation.match((float) dist, "hsin("+latVals.doubleVal(doc)+","+lonVals.doubleVal(doc)),
- Explanation.match(getBoost(), "boost"),
- Explanation.match(weight.queryNorm,"queryNorm"));
- } else {
- return Explanation.noMatch("No match");
- }
+ return Explanation.match((float) (base.getValue() * dist), description + " product of:",
+ base, Explanation.match((float) dist, "hsin("+latVals.doubleVal(doc)+","+lonVals.doubleVal(doc)));
}
}
@@ -552,8 +525,7 @@ class SpatialDistanceQuery extends ExtendedQueryBase implements PostFilter {
@Override
public String toString(String field)
{
- float boost = getBoost();
- return super.getOptions() + (boost!=1.0?"(":"") +
+ return super.getOptions() +
(calcDist ? "geofilt" : "bbox") + "(latlonSource="+origField +"(" + latSource + "," + lonSource + ")"
+",latCenter="+latCenter+",lonCenter="+lonCenter
+",dist=" + dist
@@ -563,8 +535,7 @@ class SpatialDistanceQuery extends ExtendedQueryBase implements PostFilter {
+",calcDist="+calcDist
+",planetRadius="+planetRadius
// + (bboxQuery == null ? "" : ",bboxQuery="+bboxQuery)
- +")"
- + (boost==1.0 ? "" : ")^"+boost);
+ +")";
}
@@ -586,7 +557,6 @@ class SpatialDistanceQuery extends ExtendedQueryBase implements PostFilter {
&& this.calcDist == other.calcDist
&& this.lonSource.equals(other.lonSource)
&& this.latSource.equals(other.latSource)
- && this.getBoost() == other.getBoost()
;
}
diff --git a/solr/core/src/java/org/apache/solr/search/CollapsingQParserPlugin.java b/solr/core/src/java/org/apache/solr/search/CollapsingQParserPlugin.java
index cb1097ee243..6cdfa645667 100644
--- a/solr/core/src/java/org/apache/solr/search/CollapsingQParserPlugin.java
+++ b/solr/core/src/java/org/apache/solr/search/CollapsingQParserPlugin.java
@@ -171,11 +171,11 @@ public class CollapsingQParserPlugin extends QParserPlugin {
}
public int hashCode() {
- int hashCode = collapseField.hashCode();
+ int hashCode = super.hashCode();
+ hashCode = 31 * hashCode + collapseField.hashCode();
hashCode = max!=null ? hashCode+max.hashCode():hashCode;
hashCode = min!=null ? hashCode+min.hashCode():hashCode;
hashCode = hashCode+nullPolicy;
- hashCode = hashCode*((1+Float.floatToIntBits(this.getBoost()))*31);
return hashCode;
}
@@ -186,8 +186,7 @@ public class CollapsingQParserPlugin extends QParserPlugin {
if(this.collapseField.equals(c.collapseField) &&
((this.max == null && c.max == null) || (this.max != null && c.max != null && this.max.equals(c.max))) &&
((this.min == null && c.min == null) || (this.min != null && c.min != null && this.min.equals(c.min))) &&
- this.nullPolicy == c.nullPolicy &&
- this.getBoost()==c.getBoost()) {
+ this.nullPolicy == c.nullPolicy) {
return true;
}
}
diff --git a/solr/core/src/java/org/apache/solr/search/DisMaxQParser.java b/solr/core/src/java/org/apache/solr/search/DisMaxQParser.java
index eaee8b80ee4..e45a99ee3ef 100644
--- a/solr/core/src/java/org/apache/solr/search/DisMaxQParser.java
+++ b/solr/core/src/java/org/apache/solr/search/DisMaxQParser.java
@@ -18,6 +18,7 @@ package org.apache.solr.search;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.Query;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.parser.QueryParser;
@@ -127,7 +128,7 @@ public class DisMaxQParser extends QParser {
Query fq = subQuery(f, FunctionQParserPlugin.NAME).getQuery();
Float b = ff.get(f);
if (null != b) {
- fq.setBoost(b);
+ fq = new BoostQuery(fq, b);
}
query.add(fq, BooleanClause.Occur.SHOULD);
}
@@ -151,7 +152,15 @@ public class DisMaxQParser extends QParser {
if (1 == boostQueries.size() && 1 == boostParams.length) {
/* legacy logic */
Query f = boostQueries.get(0);
- if (1.0f == f.getBoost() && f instanceof BooleanQuery) {
+ while (f instanceof BoostQuery) {
+ BoostQuery bq = (BoostQuery) f;
+ if (bq .getBoost() == 1f) {
+ f = bq.getQuery();
+ } else {
+ break;
+ }
+ }
+ if (f instanceof BooleanQuery) {
/* if the default boost was used, and we've got a BooleanQuery
* extract the subqueries out and use them directly
*/
diff --git a/solr/core/src/java/org/apache/solr/search/ExportQParserPlugin.java b/solr/core/src/java/org/apache/solr/search/ExportQParserPlugin.java
index 9a6d74b6177..0a7294901c5 100644
--- a/solr/core/src/java/org/apache/solr/search/ExportQParserPlugin.java
+++ b/solr/core/src/java/org/apache/solr/search/ExportQParserPlugin.java
@@ -87,7 +87,7 @@ public class ExportQParserPlugin extends QParserPlugin {
public Query rewrite(IndexReader reader) throws IOException {
Query q = mainQuery.rewrite(reader);
if(q == mainQuery) {
- return this;
+ return super.rewrite(reader);
} else {
return clone().wrap(q);
}
@@ -102,16 +102,15 @@ public class ExportQParserPlugin extends QParserPlugin {
}
public int hashCode() {
- return id.hashCode()+((int)getBoost());
+ return 31 * super.hashCode() + id.hashCode();
}
public boolean equals(Object o) {
- if(o instanceof ExportQuery) {
- ExportQuery q = (ExportQuery)o;
- return (this.id == q.id && getBoost() == q.getBoost());
- } else {
+ if (super.equals(o) == false) {
return false;
}
+ ExportQuery q = (ExportQuery)o;
+ return id == q.id;
}
public String toString(String s) {
diff --git a/solr/core/src/java/org/apache/solr/search/ExtendedDismaxQParser.java b/solr/core/src/java/org/apache/solr/search/ExtendedDismaxQParser.java
index 4eef5d5075a..0d7851f0d9b 100644
--- a/solr/core/src/java/org/apache/solr/search/ExtendedDismaxQParser.java
+++ b/solr/core/src/java/org/apache/solr/search/ExtendedDismaxQParser.java
@@ -40,6 +40,7 @@ import org.apache.lucene.queries.function.valuesource.ProductFloatFunction;
import org.apache.lucene.queries.function.valuesource.QueryValueSource;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.DisjunctionMaxQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.MultiPhraseQuery;
@@ -473,8 +474,8 @@ public class ExtendedDismaxQParser extends QParser {
for (String f : ff.keySet()) {
Query fq = subQuery(f, FunctionQParserPlugin.NAME).getQuery();
Float b = ff.get(f);
- if (null != b) {
- fq.setBoost(b);
+ if (null != b && b.floatValue() != 1f) {
+ fq = new BoostQuery(fq, b);
}
boostFunctions.add(fq);
}
@@ -1213,8 +1214,8 @@ public class ExtendedDismaxQParser extends QParser {
Query sub = getAliasedQuery();
if (sub != null) {
Float boost = a.fields.get(f);
- if (boost != null) {
- sub.setBoost(boost);
+ if (boost != null && boost.floatValue() != 1f) {
+ sub = new BoostQuery(sub, boost);
}
lst.add(sub);
}
diff --git a/solr/core/src/java/org/apache/solr/search/HashQParserPlugin.java b/solr/core/src/java/org/apache/solr/search/HashQParserPlugin.java
index 5a33deca8b6..fa8edc751df 100644
--- a/solr/core/src/java/org/apache/solr/search/HashQParserPlugin.java
+++ b/solr/core/src/java/org/apache/solr/search/HashQParserPlugin.java
@@ -108,18 +108,15 @@ public class HashQParserPlugin extends QParserPlugin {
}
public int hashCode() {
- return keysParam.hashCode()+workers+worker+(int)getBoost();
+ return 31 * super.hashCode() + keysParam.hashCode()+workers+worker;
}
public boolean equals(Object o) {
- if (o instanceof HashQuery) {
- HashQuery h = (HashQuery)o;
- if(keysParam.equals(h.keysParam) && workers == h.workers && worker == h.worker && getBoost() == h.getBoost()) {
- return true;
- }
+ if (super.equals(o) == false) {
+ return false;
}
-
- return false;
+ HashQuery h = (HashQuery)o;
+ return keysParam.equals(h.keysParam) && workers == h.workers && worker == h.worker;
}
public HashQuery(String keysParam, int workers, int worker) {
diff --git a/solr/core/src/java/org/apache/solr/search/JoinQParserPlugin.java b/solr/core/src/java/org/apache/solr/search/JoinQParserPlugin.java
index af3b0490c97..44e7e663131 100644
--- a/solr/core/src/java/org/apache/solr/search/JoinQParserPlugin.java
+++ b/solr/core/src/java/org/apache/solr/search/JoinQParserPlugin.java
@@ -147,7 +147,7 @@ class JoinQuery extends Query {
@Override
public Query rewrite(IndexReader reader) throws IOException {
// don't rewrite the subQuery
- return this;
+ return super.rewrite(reader);
}
@Override
@@ -515,7 +515,6 @@ class JoinQuery extends Query {
JoinQuery other = (JoinQuery)o;
return this.fromField.equals(other.fromField)
&& this.toField.equals(other.toField)
- && this.getBoost() == other.getBoost()
&& this.q.equals(other.q)
&& (this.fromIndex == other.fromIndex || this.fromIndex != null && this.fromIndex.equals(other.fromIndex))
&& this.fromCoreOpenTime == other.fromCoreOpenTime
diff --git a/solr/core/src/java/org/apache/solr/search/MaxScoreQParser.java b/solr/core/src/java/org/apache/solr/search/MaxScoreQParser.java
index 07efde59697..1e1f89a6703 100644
--- a/solr/core/src/java/org/apache/solr/search/MaxScoreQParser.java
+++ b/solr/core/src/java/org/apache/solr/search/MaxScoreQParser.java
@@ -18,6 +18,7 @@ package org.apache.solr.search;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.DisjunctionMaxQuery;
import org.apache.lucene.search.Query;
import org.apache.solr.common.params.SolrParams;
@@ -54,7 +55,16 @@ public class MaxScoreQParser extends LuceneQParser {
@Override
public Query parse() throws SyntaxError {
Query q = super.parse();
- if (!(q instanceof BooleanQuery)) {
+ float boost = 1f;
+ if (q instanceof BoostQuery) {
+ BoostQuery bq = (BoostQuery) q;
+ boost = bq.getBoost();
+ q = bq.getQuery();
+ }
+ if (q instanceof BooleanQuery == false) {
+ if (boost != 1f) {
+ q = new BoostQuery(q, boost);
+ }
return q;
}
BooleanQuery obq = (BooleanQuery)q;
@@ -79,7 +89,9 @@ public class MaxScoreQParser extends LuceneQParser {
newqb.add(c);
}
Query newq = newqb.build();
- newq.setBoost(obq.getBoost());
+ if (boost != 1f) {
+ newq = new BoostQuery(newq, boost);
+ }
return newq;
}
}
\ No newline at end of file
diff --git a/solr/core/src/java/org/apache/solr/search/QueryParsing.java b/solr/core/src/java/org/apache/solr/search/QueryParsing.java
index a67432e27ea..0bdfacb8bae 100644
--- a/solr/core/src/java/org/apache/solr/search/QueryParsing.java
+++ b/solr/core/src/java/org/apache/solr/search/QueryParsing.java
@@ -22,6 +22,7 @@ import org.apache.lucene.queries.function.FunctionQuery;
import org.apache.lucene.queries.function.valuesource.QueryValueSource;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.NumericRangeQuery;
@@ -430,6 +431,13 @@ public class QueryParsing {
public static void toString(Query query, IndexSchema schema, Appendable out, int flags) throws IOException {
boolean writeBoost = true;
+ float boost = 1f;
+ if (query instanceof BoostQuery) {
+ BoostQuery bq = (BoostQuery) query;
+ query = bq.getQuery();
+ boost = bq.getBoost();
+ }
+
if (query instanceof TermQuery) {
TermQuery q = (TermQuery) query;
Term t = q.getTerm();
@@ -483,7 +491,7 @@ public class QueryParsing {
BooleanQuery q = (BooleanQuery) query;
boolean needParens = false;
- if (q.getBoost() != 1.0 || q.getMinimumNumberShouldMatch() != 0 || q.isCoordDisabled()) {
+ if (q.getMinimumNumberShouldMatch() != 0 || q.isCoordDisabled()) {
needParens = true;
}
if (needParens) {
@@ -559,9 +567,9 @@ public class QueryParsing {
writeBoost = false;
}
- if (writeBoost && query.getBoost() != 1.0f) {
+ if (writeBoost && boost != 1.0f) {
out.append("^");
- out.append(Float.toString(query.getBoost()));
+ out.append(Float.toString(boost));
}
}
diff --git a/solr/core/src/java/org/apache/solr/search/QueryUtils.java b/solr/core/src/java/org/apache/solr/search/QueryUtils.java
index 01d2a730610..8a4685cc964 100644
--- a/solr/core/src/java/org/apache/solr/search/QueryUtils.java
+++ b/solr/core/src/java/org/apache/solr/search/QueryUtils.java
@@ -20,6 +20,7 @@ package org.apache.solr.search;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
@@ -53,13 +54,19 @@ public class QueryUtils {
* @return Absolute version of the Query
*/
public static Query getAbs(Query q) {
+ if (q instanceof BoostQuery) {
+ BoostQuery bq = (BoostQuery) q;
+ Query subQ = bq.getQuery();
+ Query absSubQ = getAbs(subQ);
+ if (absSubQ == subQ) return q;
+ return new BoostQuery(absSubQ, bq.getBoost());
+ }
+
if (q instanceof WrappedQuery) {
Query subQ = ((WrappedQuery)q).getWrappedQuery();
Query absSubQ = getAbs(subQ);
if (absSubQ == subQ) return q;
- WrappedQuery newQ = (WrappedQuery)q.clone();
- newQ.setWrappedQuery(absSubQ);
- return newQ;
+ return new WrappedQuery(absSubQ);
}
if (!(q instanceof BooleanQuery)) return q;
@@ -89,9 +96,7 @@ public class QueryUtils {
for (BooleanClause clause : clauses) {
newBqB.add(clause.getQuery(), BooleanClause.Occur.SHOULD);
}
- Query newBq = newBqB.build();
- newBq.setBoost(bq.getBoost());
- return newBq;
+ return newBqB.build();
}
}
@@ -109,6 +114,12 @@ public class QueryUtils {
* The query passed in *must* be a negative query.
*/
public static Query fixNegativeQuery(Query q) {
+ float boost = 1f;
+ if (q instanceof BoostQuery) {
+ BoostQuery bq = (BoostQuery) q;
+ boost = bq.getBoost();
+ q = bq.getQuery();
+ }
BooleanQuery bq = (BooleanQuery) q;
BooleanQuery.Builder newBqB = new BooleanQuery.Builder();
newBqB.setDisableCoord(bq.isCoordDisabled());
@@ -118,8 +129,7 @@ public class QueryUtils {
}
newBqB.add(new MatchAllDocsQuery(), Occur.MUST);
BooleanQuery newBq = newBqB.build();
- newBq.setBoost(bq.getBoost());
- return newBq;
+ return new BoostQuery(newBq, boost);
}
}
diff --git a/solr/core/src/java/org/apache/solr/search/ReRankQParserPlugin.java b/solr/core/src/java/org/apache/solr/search/ReRankQParserPlugin.java
index dc3e81754d0..4d7dfd12345 100644
--- a/solr/core/src/java/org/apache/solr/search/ReRankQParserPlugin.java
+++ b/solr/core/src/java/org/apache/solr/search/ReRankQParserPlugin.java
@@ -97,7 +97,7 @@ public class ReRankQParserPlugin extends QParserPlugin {
}
}
- private class ReRankQuery extends RankQuery {
+ private final class ReRankQuery extends RankQuery {
private Query mainQuery = defaultQuery;
private Query reRankQuery;
private int reRankDocs;
@@ -106,19 +106,18 @@ public class ReRankQParserPlugin extends QParserPlugin {
private Map<BytesRef, Integer> boostedPriority;
public int hashCode() {
- return mainQuery.hashCode()+reRankQuery.hashCode()+(int)reRankWeight+reRankDocs+(int)getBoost();
+ return 31 * super.hashCode() + mainQuery.hashCode()+reRankQuery.hashCode()+(int)reRankWeight+reRankDocs;
}
public boolean equals(Object o) {
- if(o instanceof ReRankQuery) {
- ReRankQuery rrq = (ReRankQuery)o;
- return (mainQuery.equals(rrq.mainQuery) &&
- reRankQuery.equals(rrq.reRankQuery) &&
- reRankWeight == rrq.reRankWeight &&
- reRankDocs == rrq.reRankDocs &&
- getBoost() == rrq.getBoost());
+ if (super.equals(o) == false) {
+ return false;
}
- return false;
+ ReRankQuery rrq = (ReRankQuery)o;
+ return mainQuery.equals(rrq.mainQuery) &&
+ reRankQuery.equals(rrq.reRankQuery) &&
+ reRankWeight == rrq.reRankWeight &&
+ reRankDocs == rrq.reRankDocs;
}
public ReRankQuery(Query reRankQuery, int reRankDocs, double reRankWeight, int length) {
@@ -162,17 +161,10 @@ public class ReRankQParserPlugin extends QParserPlugin {
public Query rewrite(IndexReader reader) throws IOException {
Query q = mainQuery.rewrite(reader);
- if(q == mainQuery) {
- return this;
- } else {
- return clone().wrap(q);
+ if (q != mainQuery) {
+ return new ReRankQuery(reRankQuery, reRankDocs, reRankWeight, length).wrap(q);
}
- }
-
- public ReRankQuery clone() {
- ReRankQuery clonedQuery = new ReRankQuery(reRankQuery, reRankDocs, reRankWeight, length);
- clonedQuery.setBoost(getBoost());
- return clonedQuery;
+ return super.rewrite(reader);
}
public Weight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException{
diff --git a/solr/core/src/java/org/apache/solr/search/SimpleQParserPlugin.java b/solr/core/src/java/org/apache/solr/search/SimpleQParserPlugin.java
index 220b0e484ea..5960e4fa1f3 100644
--- a/solr/core/src/java/org/apache/solr/search/SimpleQParserPlugin.java
+++ b/solr/core/src/java/org/apache/solr/search/SimpleQParserPlugin.java
@@ -21,6 +21,7 @@ import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.queryparser.simple.SimpleQueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.Query;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.SimpleParams;
@@ -205,7 +206,10 @@ public class SimpleQParserPlugin extends QParserPlugin {
prefix = type.getPrefixQuery(qParser, sf, text);
}
- prefix.setBoost(entry.getValue());
+ float boost = entry.getValue();
+ if (boost != 1f) {
+ prefix = new BoostQuery(prefix, boost);
+ }
bq.add(prefix, BooleanClause.Occur.SHOULD);
}
diff --git a/solr/core/src/java/org/apache/solr/search/SolrConstantScoreQuery.java b/solr/core/src/java/org/apache/solr/search/SolrConstantScoreQuery.java
index f409f742ea7..4d9d5f84754 100644
--- a/solr/core/src/java/org/apache/solr/search/SolrConstantScoreQuery.java
+++ b/solr/core/src/java/org/apache/solr/search/SolrConstantScoreQuery.java
@@ -6,7 +6,6 @@ import java.util.Map;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.queries.function.ValueSource;
-import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.ConstantScoreScorer;
import org.apache.lucene.search.ConstantScoreWeight;
import org.apache.lucene.search.DocIdSet;
@@ -16,7 +15,6 @@ import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.Weight;
-import org.apache.lucene.util.Bits;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
@@ -42,13 +40,12 @@ import org.apache.lucene.util.Bits;
*
* Experimental and subject to change.
*/
-public class SolrConstantScoreQuery extends ConstantScoreQuery implements ExtendedQuery {
+public class SolrConstantScoreQuery extends Query implements ExtendedQuery {
private final Filter filter;
boolean cache = true; // cache by default
int cost;
public SolrConstantScoreQuery(Filter filter) {
- super(filter);
this.filter = filter;
}
@@ -86,12 +83,6 @@ public class SolrConstantScoreQuery extends ConstantScoreQuery implements Extend
return cost;
}
-
- @Override
- public Query rewrite(IndexReader reader) throws IOException {
- return this;
- }
-
protected class ConstantWeight extends ConstantScoreWeight {
private Map context;
@@ -125,8 +116,7 @@ public class SolrConstantScoreQuery extends ConstantScoreQuery implements Extend
/** Prints a user-readable version of this query. */
@Override
public String toString(String field) {
- return ExtendedQueryBase.getOptionsString(this) + "ConstantScore(" + filter.toString()
- + (getBoost()==1.0 ? ")" : "^" + getBoost());
+ return ExtendedQueryBase.getOptionsString(this) + "ConstantScore(" + filter.toString() + ")";
}
/** Returns true if <code>o</code> is equal to this. */
diff --git a/solr/core/src/java/org/apache/solr/search/WrappedQuery.java b/solr/core/src/java/org/apache/solr/search/WrappedQuery.java
index 357ae1749d2..c7dc5b55fb5 100644
--- a/solr/core/src/java/org/apache/solr/search/WrappedQuery.java
+++ b/solr/core/src/java/org/apache/solr/search/WrappedQuery.java
@@ -25,7 +25,7 @@ import org.apache.lucene.search.Weight;
import java.io.IOException;
/** A simple query that wraps another query and implements ExtendedQuery. */
-public class WrappedQuery extends ExtendedQueryBase {
+public final class WrappedQuery extends ExtendedQueryBase {
private Query q;
public WrappedQuery(Query q) {
@@ -40,16 +40,6 @@ public class WrappedQuery extends ExtendedQueryBase {
this.q = q;
}
- @Override
- public void setBoost(float b) {
- q.setBoost(b);
- }
-
- @Override
- public float getBoost() {
- return q.getBoost();
- }
-
@Override
public Weight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {
return q.createWeight(searcher, needsScores);
@@ -61,13 +51,6 @@ public class WrappedQuery extends ExtendedQueryBase {
return q.rewrite(reader);
}
- @Override
- public WrappedQuery clone() {
- WrappedQuery newQ = (WrappedQuery)super.clone();
- newQ.q = (Query) q.clone();
- return newQ;
- }
-
@Override
public int hashCode() {
return q.hashCode();
diff --git a/solr/core/src/java/org/apache/solr/search/join/ScoreJoinQParserPlugin.java b/solr/core/src/java/org/apache/solr/search/join/ScoreJoinQParserPlugin.java
index f9cf9b3f03a..ebd6155436b 100644
--- a/solr/core/src/java/org/apache/solr/search/join/ScoreJoinQParserPlugin.java
+++ b/solr/core/src/java/org/apache/solr/search/join/ScoreJoinQParserPlugin.java
@@ -107,7 +107,6 @@ public class ScoreJoinQParserPlugin extends QParserPlugin {
fromCore.close();
fromHolder.decref();
}
- joinQuery.setBoost(getBoost());
return joinQuery.rewrite(reader);
}
@@ -162,7 +161,6 @@ public class ScoreJoinQParserPlugin extends QParserPlugin {
SolrRequestInfo info = SolrRequestInfo.getRequestInfo();
final Query jq = JoinUtil.createJoinQuery(fromField, true,
toField, fromQuery, info.getReq().getSearcher(), scoreMode);
- jq.setBoost(getBoost());
return jq.rewrite(reader);
}
diff --git a/solr/core/src/java/org/apache/solr/update/DeleteByQueryWrapper.java b/solr/core/src/java/org/apache/solr/update/DeleteByQueryWrapper.java
index 15a29051cfb..5abd0a60807 100644
--- a/solr/core/src/java/org/apache/solr/update/DeleteByQueryWrapper.java
+++ b/solr/core/src/java/org/apache/solr/update/DeleteByQueryWrapper.java
@@ -61,7 +61,7 @@ final class DeleteByQueryWrapper extends Query {
if (rewritten != in) {
return new DeleteByQueryWrapper(rewritten, schema);
} else {
- return this;
+ return super.rewrite(reader);
}
}
diff --git a/solr/core/src/java/org/apache/solr/util/SolrPluginUtils.java b/solr/core/src/java/org/apache/solr/util/SolrPluginUtils.java
index 1486ca1ce16..e8acc74f972 100644
--- a/solr/core/src/java/org/apache/solr/util/SolrPluginUtils.java
+++ b/solr/core/src/java/org/apache/solr/util/SolrPluginUtils.java
@@ -32,11 +32,13 @@ import java.util.TreeMap;
import java.util.regex.Pattern;
import com.google.common.collect.ImmutableMap;
+
import org.apache.lucene.index.StorableField;
import org.apache.lucene.index.StoredDocument;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.DisjunctionMaxQuery;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.Query;
@@ -703,18 +705,27 @@ public class SolrPluginUtils {
* </p>
*/
public static void flattenBooleanQuery(BooleanQuery.Builder to, BooleanQuery from) {
+ flattenBooleanQuery(to, from, 1f);
+ }
+
+ private static void flattenBooleanQuery(BooleanQuery.Builder to, BooleanQuery from, float fromBoost) {
for (BooleanClause clause : from.clauses()) {
Query cq = clause.getQuery();
- cq.setBoost(cq.getBoost() * from.getBoost());
+ float boost = fromBoost;
+ while (cq instanceof BoostQuery) {
+ BoostQuery bq = (BoostQuery) cq;
+ cq = bq.getQuery();
+ boost *= bq.getBoost();
+ }
if (cq instanceof BooleanQuery
&& !clause.isRequired()
&& !clause.isProhibited()) {
/* we can recurse */
- flattenBooleanQuery(to, (BooleanQuery)cq);
+ flattenBooleanQuery(to, (BooleanQuery)cq, boost);
} else {
to.add(clause);
@@ -866,7 +877,7 @@ public class SolrPluginUtils {
Query sub = getFieldQuery(f,queryText,quoted);
if (null != sub) {
if (null != a.fields.get(f)) {
- sub.setBoost(a.fields.get(f));
+ sub = new BoostQuery(sub, a.fields.get(f));
}
q.add(sub);
ok = true;
diff --git a/solr/core/src/test/org/apache/solr/search/TestExtendedDismaxParser.java b/solr/core/src/test/org/apache/solr/search/TestExtendedDismaxParser.java
index f9a768ede95..732e19fc11b 100644
--- a/solr/core/src/test/org/apache/solr/search/TestExtendedDismaxParser.java
+++ b/solr/core/src/test/org/apache/solr/search/TestExtendedDismaxParser.java
@@ -23,6 +23,7 @@ import java.util.Set;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.DisjunctionMaxQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.Query;
@@ -1054,27 +1055,35 @@ public class TestExtendedDismaxParser extends SolrTestCaseJ4 {
private boolean containsClause(Query query, String field, String value,
int boost, boolean fuzzy) {
-
+
+ float queryBoost = 1f;
+ if (query instanceof BoostQuery) {
+ BoostQuery bq = (BoostQuery) query;
+ query = bq.getQuery();
+ queryBoost = bq.getBoost();
+ }
+
if(query instanceof BooleanQuery) {
return containsClause((BooleanQuery)query, field, value, boost, fuzzy);
}
if(query instanceof DisjunctionMaxQuery) {
return containsClause((DisjunctionMaxQuery)query, field, value, boost, fuzzy);
}
+ if (boost != queryBoost) {
+ return false;
+ }
if(query instanceof TermQuery && !fuzzy) {
- return containsClause((TermQuery)query, field, value, boost);
+ return containsClause((TermQuery)query, field, value);
}
if(query instanceof FuzzyQuery && fuzzy) {
- return containsClause((FuzzyQuery)query, field, value, boost);
+ return containsClause((FuzzyQuery)query, field, value);
}
return false;
}
- private boolean containsClause(FuzzyQuery query, String field, String value,
- int boost) {
+ private boolean containsClause(FuzzyQuery query, String field, String value) {
if(query.getTerm().field().equals(field) &&
- query.getTerm().bytes().utf8ToString().equals(value) &&
- query.getBoost() == boost) {
+ query.getTerm().bytes().utf8ToString().equals(value)) {
return true;
}
return false;
@@ -1089,10 +1098,9 @@ public class TestExtendedDismaxParser extends SolrTestCaseJ4 {
return false;
}
- private boolean containsClause(TermQuery query, String field, String value, int boost) {
+ private boolean containsClause(TermQuery query, String field, String value) {
if(query.getTerm().field().equals(field) &&
- query.getTerm().bytes().utf8ToString().equals(value) &&
- query.getBoost() == boost) {
+ query.getTerm().bytes().utf8ToString().equals(value)) {
return true;
}
return false;
diff --git a/solr/core/src/test/org/apache/solr/search/TestMaxScoreQueryParser.java b/solr/core/src/test/org/apache/solr/search/TestMaxScoreQueryParser.java
index 864a8cd2ce2..862a86404e8 100644
--- a/solr/core/src/test/org/apache/solr/search/TestMaxScoreQueryParser.java
+++ b/solr/core/src/test/org/apache/solr/search/TestMaxScoreQueryParser.java
@@ -17,6 +17,7 @@ package org.apache.solr.search;
* limitations under the License.
*/
+import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.util.AbstractSolrTestCase;
@@ -40,10 +41,10 @@ public class TestMaxScoreQueryParser extends AbstractSolrTestCase {
@Test
public void testFallbackToLucene() {
q = parse("foo");
- assertTrue(q instanceof TermQuery);
+ assertEquals(new TermQuery(new Term("text", "foo")), q);
q = parse("foo^3.0");
- assertTrue(q instanceof TermQuery);
+ assertEquals(new BoostQuery(new TermQuery(new Term("text", "foo")), 3f), q);
q = parse("price:[0 TO 10]");
assertTrue(q instanceof NumericRangeQuery);
@@ -100,7 +101,8 @@ public class TestMaxScoreQueryParser extends AbstractSolrTestCase {
public void testBoost() {
// Simple term query
q = parse("foo^3.0");
- assertEquals(3.0, q.getBoost(), 1e-15);
+ assertTrue(q instanceof BoostQuery);
+ assertEquals(3.0, ((BoostQuery) q).getBoost(), 1e-15);
// Some DMQ and one plain required
q = parse("foo^5.0 bar^6.0 +baz^7");
@@ -108,12 +110,12 @@ public class TestMaxScoreQueryParser extends AbstractSolrTestCase {
assertEquals(2, clauses.length);
assertTrue(clauses[0].getQuery() instanceof DisjunctionMaxQuery);
DisjunctionMaxQuery dmq = ((DisjunctionMaxQuery) clauses[0].getQuery());
- float fooClause = ((BooleanQuery)dmq.getDisjuncts().get(0)).clauses().iterator().next().getQuery().getBoost();
- assertEquals(5.0, fooClause, 1e-15);
- float barClause = ((BooleanQuery)dmq.getDisjuncts().get(1)).clauses().iterator().next().getQuery().getBoost();
- assertEquals(6.0, barClause, 1e-15);
- assertEquals(7.0, clauses[1].getQuery().getBoost(), 1e-15);
- assertEquals(1.0, q.getBoost(), 1e-15);
+ Query fooClause = ((BooleanQuery)dmq.getDisjuncts().get(0)).clauses().iterator().next().getQuery();
+ assertEquals(5.0, ((BoostQuery) fooClause).getBoost(), 1e-15);
+ Query barClause = ((BooleanQuery)dmq.getDisjuncts().get(1)).clauses().iterator().next().getQuery();
+ assertEquals(6.0, ((BoostQuery) barClause).getBoost(), 1e-15);
+ assertEquals(7.0, ((BoostQuery) clauses[1].getQuery()).getBoost(), 1e-15);
+ assertFalse(q instanceof BoostQuery);
// Grouped with parens on top level
q = parse("(foo^2.0 bar)^3.0");
@@ -121,11 +123,11 @@ public class TestMaxScoreQueryParser extends AbstractSolrTestCase {
assertEquals(1, clauses.length);
assertTrue(clauses[0].getQuery() instanceof DisjunctionMaxQuery);
dmq = ((DisjunctionMaxQuery) clauses[0].getQuery());
- fooClause = ((BooleanQuery)dmq.getDisjuncts().get(0)).clauses().iterator().next().getQuery().getBoost();
- assertEquals(2.0, fooClause, 1e-15);
- barClause = ((BooleanQuery)dmq.getDisjuncts().get(1)).clauses().iterator().next().getQuery().getBoost();
- assertEquals(1.0, barClause, 1e-15);
- assertEquals(3.0, q.getBoost(), 1e-15);
+ fooClause = ((BooleanQuery)dmq.getDisjuncts().get(0)).clauses().iterator().next().getQuery();
+ assertEquals(2.0, ((BoostQuery) fooClause).getBoost(), 1e-15);
+ barClause = ((BooleanQuery)dmq.getDisjuncts().get(1)).clauses().iterator().next().getQuery();
+ assertFalse(barClause instanceof BoostQuery);
+ assertEquals(3.0, ((BoostQuery) q).getBoost(), 1e-15);
}
//
@@ -148,6 +150,9 @@ public class TestMaxScoreQueryParser extends AbstractSolrTestCase {
}
private BooleanClause[] clauses(Query q) {
+ while (q instanceof BoostQuery) {
+ q = ((BoostQuery) q).getQuery();
+ }
return ((BooleanQuery) q).clauses().toArray(new BooleanClause[0]);
}
}
diff --git a/solr/core/src/test/org/apache/solr/search/TestRankQueryPlugin.java b/solr/core/src/test/org/apache/solr/search/TestRankQueryPlugin.java
index ccbd2e690aa..5f4f100b1cf 100644
--- a/solr/core/src/test/org/apache/solr/search/TestRankQueryPlugin.java
+++ b/solr/core/src/test/org/apache/solr/search/TestRankQueryPlugin.java
@@ -117,14 +117,6 @@ public class TestRankQueryPlugin extends QParserPlugin {
return q.createWeight(indexSearcher, needsScores);
}
- public void setBoost(float boost) {
- q.setBoost(boost);
- }
-
- public float getBoost() {
- return q.getBoost();
- }
-
@Override
public String toString(String field) {
return q.toString(field);
diff --git a/solr/core/src/test/org/apache/solr/search/TestSolrQueryParser.java b/solr/core/src/test/org/apache/solr/search/TestSolrQueryParser.java
index 88c8a9d31da..2b2ad247605 100644
--- a/solr/core/src/test/org/apache/solr/search/TestSolrQueryParser.java
+++ b/solr/core/src/test/org/apache/solr/search/TestSolrQueryParser.java
@@ -16,6 +16,7 @@
*/
package org.apache.solr.search;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.Query;
import org.apache.solr.SolrTestCaseJ4;
@@ -154,14 +155,14 @@ public class TestSolrQueryParser extends SolrTestCaseJ4 {
assertJQ(req("fq","id:1", "fl","id,score", "q", subqq+"^3", "qq","text:x^2"
, "debug","query"
)
- ,"/debug/parsedquery=='text:x^6.0'"
+ ,"/debug/parsedquery_toString=='(text:x^2.0)^3.0'"
);
// boost should multiply
assertJQ(req("fq","id:1", "fl","id,score", "q", " {!v=$qq}^3", "qq","text:x^2"
, "debug","query"
)
- ,"/debug/parsedquery=='text:x^6.0'"
+ ,"/debug/parsedquery_toString=='(text:x^2.0)^3.0'"
);
}
@@ -174,13 +175,15 @@ public class TestSolrQueryParser extends SolrTestCaseJ4 {
QParser qParser = QParser.getParser("text:x^=3", "lucene", req);
Query q = qParser.getQuery();
- assertTrue( q instanceof ConstantScoreQuery);
- assertEquals(3.0, q.getBoost(), 0.0f);
+ assertTrue( q instanceof BoostQuery);
+ assertTrue(((BoostQuery) q).getQuery() instanceof ConstantScoreQuery);
+ assertEquals(3.0, ((BoostQuery) q).getBoost(), 0.0f);
qParser = QParser.getParser("(text:x text:y)^=-3", "lucene", req);
q = qParser.getQuery();
- assertTrue( q instanceof ConstantScoreQuery );
- assertEquals(-3.0, q.getBoost(), 0.0f);
+ assertTrue( q instanceof BoostQuery);
+ assertTrue(((BoostQuery) q).getQuery() instanceof ConstantScoreQuery);
+ assertEquals(-3.0, ((BoostQuery) q).getBoost(), 0.0f);
req.close();
}
diff --git a/solr/core/src/test/org/apache/solr/search/join/TestScoreJoinQPScore.java b/solr/core/src/test/org/apache/solr/search/join/TestScoreJoinQPScore.java
index 3938fd2d260..fa790c80131 100644
--- a/solr/core/src/test/org/apache/solr/search/join/TestScoreJoinQPScore.java
+++ b/solr/core/src/test/org/apache/solr/search/join/TestScoreJoinQPScore.java
@@ -24,6 +24,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Random;
+import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.join.ScoreMode;
import org.apache.solr.SolrTestCaseJ4;
@@ -191,7 +192,9 @@ public class TestScoreJoinQPScore extends SolrTestCaseJ4 {
final SolrQueryRequest req = req("q", "{!join from=movieId_s to=id score=" + score + " b=200}title:movie", "fl", "id,score", "omitHeader", "true");
SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, new SolrQueryResponse()));
final Query luceneQ = QParser.getParser(req.getParams().get("q"), null, req).getQuery().rewrite(req.getSearcher().getLeafReader());
- assertEquals("" + luceneQ, Float.floatToIntBits(200), Float.floatToIntBits(luceneQ.getBoost()));
+ assertTrue(luceneQ instanceof BoostQuery);
+ float boost = ((BoostQuery) luceneQ).getBoost();
+ assertEquals("" + luceneQ, Float.floatToIntBits(200), Float.floatToIntBits(boost));
SolrRequestInfo.clearRequestInfo();
req.close();
}