Apache Lucene open-source search software
LUCENE-6583: Remove FilteredQuery.
Adrien Grand35c0ff0ec64d
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex 949b504921c..2c5956505e7 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -38,6 +38,10 @@ API Changes* LUCENE-6570: BooleanQuery is now immutable and can be built using theBooleanQuery.Builder class. (Adrien Grand)+* LUCENE-6583: FilteredQuery has been removed. Instead, you can construct a+ BooleanQuery with one MUST clause for the query, and one FILTER clause for+ the filter. (Adrien Grand)+======================= Lucene 5.3.0 =======================New Featuresdiff --git a/lucene/MIGRATE.txt b/lucene/MIGRATE.txtindex 689ccc85247..ae25a7b557b 100644--- a/lucene/MIGRATE.txt+++ b/lucene/MIGRATE.txt@@ -14,3 +14,7 @@ situations where some documents do not have values for fields wrapped in otherValueSources. Users who want to preserve the previous behavior may need to wraptheir ValueSources in a "DefFunction" along with a ConstValueSource of "0.0".+## Removal of FilteredQuery (LUCENE-6583)++FilteredQuery has been removed. Instead, you can construct a BooleanQuery with+one MUST clause for the query, and one FILTER clause for the filter.diff --git a/lucene/core/src/java/org/apache/lucene/search/Filter.java b/lucene/core/src/java/org/apache/lucene/search/Filter.javaindex 51e98cb8bf8..835e79be25e 100644--- a/lucene/core/src/java/org/apache/lucene/search/Filter.java+++ b/lucene/core/src/java/org/apache/lucene/search/Filter.java@@ -30,6 +30,22 @@ import org.apache.lucene.util.Bits;*/public abstract class Filter extends Query {+ private final boolean applyLazily;++ /** Filter constructor. When {@code applyLazily} is true and the produced+ * {@link DocIdSet}s support {@link DocIdSet#bits() random-access}, Lucene+ * will only apply this filter after other clauses. */+ protected Filter(boolean applyLazily) {+ this.applyLazily = applyLazily;+ }++ /** Default Filter constructor that will use the+ * {@link DocIdSet#iterator() doc id set iterator} when consumed through+ * the {@link Query} API. */+ protected Filter() {+ this(false);+ }+/*** Creates a {@link DocIdSet} enumerating the documents that should be* permitted in search results. <b>NOTE:</b> null can be@@ -96,6 +112,17 @@ public abstract class Filter extends Query {if (set == null) {return null;}+ if (applyLazily && set.bits() != null) {+ final Bits bits = set.bits();+ final DocIdSetIterator approximation = DocIdSetIterator.all(context.reader().maxDoc());+ final TwoPhaseIterator twoPhase = new TwoPhaseIterator(approximation) {+ @Override+ public boolean matches() throws IOException {+ return bits.get(approximation.docID());+ }+ };+ return new ConstantScoreScorer(this, 0f, twoPhase);+ }final DocIdSetIterator iterator = set.iterator();if (iterator == null) {return null;diff --git a/lucene/core/src/java/org/apache/lucene/search/FilteredQuery.java b/lucene/core/src/java/org/apache/lucene/search/FilteredQuery.javadeleted file mode 100644index bbd6cfd66e9..00000000000--- a/lucene/core/src/java/org/apache/lucene/search/FilteredQuery.java+++ /dev/null@@ -1,619 +0,0 @@-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.Collection;-import java.util.Collections;-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;-import org.apache.lucene.search.BooleanClause.Occur;-import org.apache.lucene.util.Bits;-import org.apache.lucene.util.ToStringUtils;---/**- * A query that applies a filter to the results of another query.- *- * <p>Note: the bits are retrieved from the filter each time this- * query is used in a search - use a CachingWrapperFilter to avoid- * regenerating the bits every time.- * @since 1.4- * @see CachingWrapperQuery- */-public class FilteredQuery extends Query {-- private final Query query;- private final Filter filter;- private final FilterStrategy strategy;-- /**- * Constructs a new query which applies a filter to the results of the original query.- * {@link Filter#getDocIdSet} will be called every time this query is used in a search.- * @param query Query to be filtered, cannot be <code>null</code>.- * @param filter Filter to apply to query results, cannot be <code>null</code>.- */- public FilteredQuery(Query query, Filter filter) {- this(query, filter, RANDOM_ACCESS_FILTER_STRATEGY);- }-- /**- * Expert: Constructs a new query which applies a filter to the results of the original query.- * {@link Filter#getDocIdSet} will be called every time this query is used in a search.- * @param query Query to be filtered, cannot be <code>null</code>.- * @param filter Filter to apply to query results, cannot be <code>null</code>.- * @param strategy a filter strategy used to create a filtered scorer.- *- * @see FilterStrategy- */- public FilteredQuery(Query query, Filter filter, FilterStrategy strategy) {- this.strategy = Objects.requireNonNull(strategy, "FilterStrategy must not be null");- this.query = Objects.requireNonNull(query, "Query must not be null");- this.filter = Objects.requireNonNull(filter, "Filter must not be null");- }-- /**- * Returns a Weight that applies the filter to the enclosed query's Weight.- * This is accomplished by overriding the Scorer returned by the Weight.- */- @Override- public Weight createWeight(final IndexSearcher searcher, boolean needsScores) throws IOException {- final Weight weight = query.createWeight (searcher, needsScores);- return new Weight(FilteredQuery.this) {-- @Override- public void extractTerms(Set<Term> terms) {- weight.extractTerms(terms);- }-- @Override- public float getValueForNormalization() throws IOException {- return weight.getValueForNormalization() * getBoost() * getBoost(); // boost sub-weight- }-- @Override- public void normalize(float norm, float topLevelBoost) {- weight.normalize(norm, topLevelBoost * getBoost()); // incorporate boost- }-- @Override- public Explanation explain(LeafReaderContext ir, int i) throws IOException {- Explanation inner = weight.explain (ir, i);- Filter f = FilteredQuery.this.filter;- DocIdSet docIdSet = f.getDocIdSet(ir, ir.reader().getLiveDocs());- DocIdSetIterator docIdSetIterator = docIdSet == null ? DocIdSetIterator.empty() : docIdSet.iterator();- if (docIdSetIterator == null) {- docIdSetIterator = DocIdSetIterator.empty();- }- if (docIdSetIterator.advance(i) == i) {- return inner;- } else {- return Explanation.noMatch("failure to match filter: " + f.toString(), inner);- }- }-- // return a filtering scorer- @Override- public Scorer scorer(LeafReaderContext context, Bits acceptDocs) throws IOException {- assert filter != null;-- DocIdSet filterDocIdSet = filter.getDocIdSet(context, acceptDocs);- if (filterDocIdSet == null) {- // this means the filter does not accept any documents.- return null;- }-- return strategy.filteredScorer(context, weight, filterDocIdSet);- }-- // return a filtering top scorer- @Override- public BulkScorer bulkScorer(LeafReaderContext context, Bits acceptDocs) throws IOException {- assert filter != null;-- DocIdSet filterDocIdSet = filter.getDocIdSet(context, acceptDocs);- if (filterDocIdSet == null) {- // this means the filter does not accept any documents.- return null;- }-- return strategy.filteredBulkScorer(context, weight, filterDocIdSet);-- }- };- }-- /**- * A scorer that consults the filter iff a document was matched by the- * delegate scorer. This is useful if the filter computation is more expensive- * than document scoring or if the filter has a linear running time to compute- * the next matching doc like exact geo distances.- */- private static final class QueryFirstScorer extends Scorer {- private final Scorer scorer;- private final Bits filterBits;-- protected QueryFirstScorer(Weight weight, Bits filterBits, Scorer other) {- super(weight);- this.scorer = other;- this.filterBits = filterBits;- }-- @Override- public int nextDoc() throws IOException {- int doc;- for(;;) {- doc = scorer.nextDoc();- if (doc == DocIdSetIterator.NO_MORE_DOCS || filterBits.get(doc)) {- return doc;- }- }- }-- @Override- public int advance(int target) throws IOException {- int doc = scorer.advance(target);- if (doc != DocIdSetIterator.NO_MORE_DOCS && !filterBits.get(doc)) {- return nextDoc();- } else {- return doc;- }- }-- @Override- public int docID() {- return scorer.docID();- }-- @Override- public float score() throws IOException {- return scorer.score();- }-- @Override- public int freq() throws IOException {- return scorer.freq();- }-- @Override- public long cost() {- return scorer.cost();- }-- @Override- public Collection<ChildScorer> getChildren() {- return Collections.singleton(new ChildScorer(scorer, "FILTERED"));- }-- @Override- public TwoPhaseIterator asTwoPhaseIterator() {- TwoPhaseIterator inner = scorer.asTwoPhaseIterator();- if (inner != null) {- // we are like a simplified conjunction here, handle the nested case:- return new TwoPhaseIterator(inner.approximation()) {- @Override- public boolean matches() throws IOException {- // check the approximation matches first, then check bits last.- return inner.matches() && filterBits.get(scorer.docID());- }- };- } else {- // scorer doesnt have an approximation, just use it, to force bits applied last.- return new TwoPhaseIterator(scorer) {- @Override- public boolean matches() throws IOException {- return filterBits.get(scorer.docID());- }- };- }- }- }-- private static class QueryFirstBulkScorer extends BulkScorer {-- private final Scorer scorer;- private final Bits filterBits;-- public QueryFirstBulkScorer(Scorer scorer, Bits filterBits) {- this.scorer = scorer;- this.filterBits = filterBits;- }-- @Override- public long cost() {- return scorer.cost();- }-- @Override- public int score(LeafCollector collector, int min, int maxDoc) throws IOException {- // the normalization trick already applies the boost of this query,- // so we can use the wrapped scorer directly:- collector.setScorer(scorer);- if (scorer.docID() < min) {- scorer.advance(min);- }- while (true) {- final int scorerDoc = scorer.docID();- if (scorerDoc < maxDoc) {- if (filterBits.get(scorerDoc)) {- collector.collect(scorerDoc);- }- scorer.nextDoc();- } else {- break;- }- }-- return scorer.docID();- }- }-- /**- * A Scorer that uses a "leap-frog" approach (also called "zig-zag join"). The scorer and the filter- * take turns trying to advance to each other's next matching document, often- * jumping past the target document. When both land on the same document, it's- * collected.- */- private static final class LeapFrogScorer extends Scorer {- private final ConjunctionDISI conjunction;- private final Scorer scorer;-- protected LeapFrogScorer(Weight weight, DocIdSetIterator primary, DocIdSetIterator secondary, Scorer scorer) {- super(weight);- conjunction = ConjunctionDISI.intersect(Arrays.asList(primary, secondary));- this.scorer = scorer;- }-- @Override- public int nextDoc() throws IOException {- return conjunction.nextDoc();- }-- @Override- public final int advance(int target) throws IOException {- return conjunction.advance(target);- }-- @Override- public final int docID() {- return conjunction.docID();- }-- @Override- public final Collection<ChildScorer> getChildren() {- return Collections.singleton(new ChildScorer(scorer, "FILTERED"));- }-- @Override- public long cost() {- return conjunction.cost();- }-- @Override- public float score() throws IOException {- return scorer.score();- }-- @Override- public int freq() throws IOException {- return scorer.freq();- }-- @Override- public TwoPhaseIterator asTwoPhaseIterator() {- return conjunction.asTwoPhaseIterator();- }- }-- @Override- public Query rewrite(IndexReader reader) throws IOException {- final Query queryRewritten = query.rewrite(reader);- final Query filterRewritten = filter.rewrite(reader);-- if (queryRewritten != query || filterRewritten != filter) {- // rewrite to a new FilteredQuery wrapping the rewritten query/filter- if (filterRewritten instanceof Filter) {- final Query rewritten = new FilteredQuery(queryRewritten, (Filter) filterRewritten, strategy);- rewritten.setBoost(this.getBoost());- return rewritten;- } else {- // In that case the filter does not implement random-access anyway so- // we want to take advantage of approximations- BooleanQuery.Builder builder = new BooleanQuery.Builder();- builder.add(queryRewritten, Occur.MUST);- builder.add(filterRewritten, Occur.FILTER);- BooleanQuery rewritten = builder.build();- rewritten.setBoost(getBoost());- return rewritten;- }- }- // nothing to rewrite, we are done!- return this;- }-- /** Returns this FilteredQuery's (unfiltered) Query */- public final Query getQuery() {- return query;- }-- /** Returns this FilteredQuery's filter */- public final Filter getFilter() {- return filter;- }-- /** Returns this FilteredQuery's {@link FilterStrategy} */- public FilterStrategy getFilterStrategy() {- return this.strategy;- }-- /** Prints a user-readable version of this query. */- @Override- public String toString (String s) {- StringBuilder buffer = new StringBuilder();- buffer.append("filtered(");- buffer.append(query.toString(s));- buffer.append(")->");- buffer.append(filter);- buffer.append(ToStringUtils.boost(getBoost()));- return buffer.toString();- }-- /** Returns true iff <code>o</code> is equal to this. */- @Override- public boolean equals(Object o) {- if (o == this)- return true;- if (!super.equals(o))- return false;- assert o instanceof FilteredQuery;- final FilteredQuery fq = (FilteredQuery) o;- return fq.query.equals(this.query) && fq.filter.equals(this.filter) && fq.strategy.equals(this.strategy);- }-- /** Returns a hash code value for this object. */- @Override- public int hashCode() {- int hash = super.hashCode();- hash = hash * 31 + strategy.hashCode();- hash = hash * 31 + query.hashCode();- hash = hash * 31 + filter.hashCode();- return hash;- }-- /**- * A {@link FilterStrategy} that conditionally uses a random access filter if- * the given {@link DocIdSet} supports random access (returns a non-null value- * from {@link DocIdSet#bits()}) and- * {@link RandomAccessFilterStrategy#useRandomAccess(Bits, long)} returns- * <code>true</code>. Otherwise this strategy falls back to a "zig-zag join" (- * {@link FilteredQuery#LEAP_FROG_FILTER_FIRST_STRATEGY}) strategy.- *- * <p>- * Note: this strategy is the default strategy in {@link FilteredQuery}- * </p>- */- public static final FilterStrategy RANDOM_ACCESS_FILTER_STRATEGY = new RandomAccessFilterStrategy();-- /**- * A filter strategy that uses a "leap-frog" approach (also called "zig-zag join").- * The scorer and the filter- * take turns trying to advance to each other's next matching document, often- * jumping past the target document. When both land on the same document, it's- * collected.- * <p>- * Note: This strategy uses the filter to lead the iteration.- * </p>- */- public static final FilterStrategy LEAP_FROG_FILTER_FIRST_STRATEGY = new LeapFrogFilterStrategy(false);-- /**- * A filter strategy that uses a "leap-frog" approach (also called "zig-zag join").- * The scorer and the filter- * take turns trying to advance to each other's next matching document, often- * jumping past the target document. When both land on the same document, it's- * collected.- * <p>- * Note: This strategy uses the query to lead the iteration.- * </p>- */- public static final FilterStrategy LEAP_FROG_QUERY_FIRST_STRATEGY = new LeapFrogFilterStrategy(true);-- /**- * A filter strategy that advances the Query or rather its {@link Scorer} first and consults the- * filter {@link DocIdSet} for each matched document.- * <p>- * Note: this strategy requires a {@link DocIdSet#bits()} to return a non-null value. Otherwise- * this strategy falls back to {@link FilteredQuery#LEAP_FROG_QUERY_FIRST_STRATEGY}- * </p>- * <p>- * Use this strategy if the filter computation is more expensive than document- * scoring or if the filter has a linear running time to compute the next- * matching doc like exact geo distances.- * </p>- */- public static final FilterStrategy QUERY_FIRST_FILTER_STRATEGY = new QueryFirstFilterStrategy();-- /** Abstract class that defines how the filter ({@link DocIdSet}) applied during document collection. */- public static abstract class FilterStrategy {-- /**- * Returns a filtered {@link Scorer} based on this strategy.- *- * @param context- * the {@link org.apache.lucene.index.LeafReaderContext} for which to return the {@link Scorer}.- * @param weight the {@link FilteredQuery} {@link Weight} to create the filtered scorer.- * @param docIdSet the filter {@link DocIdSet} to apply- * @return a filtered scorer- *- * @throws IOException if an {@link IOException} occurs- */- public abstract Scorer filteredScorer(LeafReaderContext context,- Weight weight, DocIdSet docIdSet) throws IOException;-- /**- * Returns a filtered {@link BulkScorer} based on this- * strategy. This is an optional method: the default- * implementation just calls {@link #filteredScorer} and- * wraps that into a BulkScorer.- *- * @param context- * the {@link org.apache.lucene.index.LeafReaderContext} for which to return the {@link Scorer}.- * @param weight the {@link FilteredQuery} {@link Weight} to create the filtered scorer.- * @param docIdSet the filter {@link DocIdSet} to apply- * @return a filtered top scorer- */- public BulkScorer filteredBulkScorer(LeafReaderContext context,- Weight weight, DocIdSet docIdSet) throws IOException {- Scorer scorer = filteredScorer(context, weight, docIdSet);- if (scorer == null) {- return null;- }- // This impl always scores docs in order, so we can- // ignore scoreDocsInOrder:- return new Weight.DefaultBulkScorer(scorer);- }-- }-- /**- * A {@link FilterStrategy} that conditionally uses a random access filter if- * the given {@link DocIdSet} supports random access (returns a non-null value- * from {@link DocIdSet#bits()}) and- * {@link RandomAccessFilterStrategy#useRandomAccess(Bits, long)} returns- * <code>true</code>. Otherwise this strategy falls back to a "zig-zag join" (- * {@link FilteredQuery#LEAP_FROG_FILTER_FIRST_STRATEGY}) strategy .- */- public static class RandomAccessFilterStrategy extends FilterStrategy {-- @Override- public Scorer filteredScorer(LeafReaderContext context, Weight weight, DocIdSet docIdSet) throws IOException {- final DocIdSetIterator filterIter = docIdSet.iterator();- if (filterIter == null) {- // this means the filter does not accept any documents.- return null;- }-- final Bits filterAcceptDocs = docIdSet.bits();- // force if RA is requested- final boolean useRandomAccess = filterAcceptDocs != null && useRandomAccess(filterAcceptDocs, filterIter.cost());- if (useRandomAccess) {- // if we are using random access, we return the inner scorer, just with other acceptDocs- return weight.scorer(context, filterAcceptDocs);- } else {- // we are gonna advance() this scorer, so we set inorder=true/toplevel=false- // we pass null as acceptDocs, as our filter has already respected acceptDocs, no need to do twice- final Scorer scorer = weight.scorer(context, null);- return (scorer == null) ? null : new LeapFrogScorer(weight, filterIter, scorer, scorer);- }- }-- /**- * Expert: decides if a filter should be executed as "random-access" or not.- * random-access means the filter "filters" in a similar way as deleted docs are filtered- * in Lucene. This is faster when the filter accepts many documents.- * However, when the filter is very sparse, it can be faster to execute the query+filter- * as a conjunction in some cases.- *- * The default implementation returns <code>true</code> if the filter matches more than 1%- * of documents- *- * @lucene.internal- */- protected boolean useRandomAccess(Bits bits, long filterCost) {- // if the filter matches more than 1% of documents, we use random-access- return filterCost * 100 > bits.length();- }- }-- private static final class LeapFrogFilterStrategy extends FilterStrategy {-- private final boolean scorerFirst;-- private LeapFrogFilterStrategy(boolean scorerFirst) {- this.scorerFirst = scorerFirst;- }-- @Override- public Scorer filteredScorer(LeafReaderContext context,- Weight weight, DocIdSet docIdSet) throws IOException {- final DocIdSetIterator filterIter = docIdSet.iterator();- if (filterIter == null) {- // this means the filter does not accept any documents.- return null;- }- // we pass null as acceptDocs, as our filter has already respected acceptDocs, no need to do twice- final Scorer scorer = weight.scorer(context, null);- if (scorer == null) {- return null;- }-- if (scorerFirst) {- return new LeapFrogScorer(weight, scorer, filterIter, scorer);- } else {- return new LeapFrogScorer(weight, filterIter, scorer, scorer);- }- }- }-- /**- * A filter strategy that advances the {@link Scorer} first and consults the- * {@link DocIdSet} for each matched document.- * <p>- * Note: this strategy requires a {@link DocIdSet#bits()} to return a non-null value. Otherwise- * this strategy falls back to {@link FilteredQuery#LEAP_FROG_QUERY_FIRST_STRATEGY}- * </p>- * <p>- * Use this strategy if the filter computation is more expensive than document- * scoring or if the filter has a linear running time to compute the next- * matching doc like exact geo distances.- * </p>- */- private static final class QueryFirstFilterStrategy extends FilterStrategy {- @Override- public Scorer filteredScorer(final LeafReaderContext context,- Weight weight, DocIdSet docIdSet) throws IOException {- Bits filterAcceptDocs = docIdSet.bits();- if (filterAcceptDocs == null) {- // Filter does not provide random-access Bits; we- // must fallback to leapfrog:- return LEAP_FROG_QUERY_FIRST_STRATEGY.filteredScorer(context, weight, docIdSet);- }- final Scorer scorer = weight.scorer(context, null);- return scorer == null ? null : new QueryFirstScorer(weight, filterAcceptDocs, scorer);- }-- @Override- public BulkScorer filteredBulkScorer(final LeafReaderContext context,- Weight weight, DocIdSet docIdSet) throws IOException {- Bits filterAcceptDocs = docIdSet.bits();- if (filterAcceptDocs == null) {- // Filter does not provide random-access Bits; we- // must fallback to leapfrog:- return LEAP_FROG_QUERY_FIRST_STRATEGY.filteredBulkScorer(context, weight, docIdSet);- }- final Scorer scorer = weight.scorer(context, null);- return scorer == null ? null : new QueryFirstBulkScorer(scorer, filterAcceptDocs);- }- }--}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.javaindex d2b3a930901..567d1ab8e1a 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@@ -24,7 +24,6 @@ import org.apache.lucene.index.Term;import org.apache.lucene.search.BooleanClause;import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.DisjunctionMaxQuery;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.MultiPhraseQuery;import org.apache.lucene.search.PhraseQuery;@@ -109,8 +108,6 @@ public class PayloadSpanUtil {getPayloads(payloads, stq);} else if (query instanceof SpanQuery) {getPayloads(payloads, (SpanQuery) query);- } else if (query instanceof FilteredQuery) {- queryToSpanQuery(((FilteredQuery) query).getQuery(), payloads);} else if (query instanceof DisjunctionMaxQuery) {for (Iterator<Query> iterator = ((DisjunctionMaxQuery) query).iterator(); iteratordiff --git a/lucene/core/src/test/org/apache/lucene/search/TestComplexExplanations.java b/lucene/core/src/test/org/apache/lucene/search/TestComplexExplanations.javaindex 9146e1342db..6a946a80e1a 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestComplexExplanations.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestComplexExplanations.java@@ -69,8 +69,10 @@ public class TestComplexExplanations extends BaseExplanationTestCase {q.add(snear(sf("w3",2), st("w2"), st("w3"), 5, true),Occur.SHOULD);- Query t = new FilteredQuery(new TermQuery(new Term(FIELD, "xx")),- new QueryWrapperFilter(matchTheseItems(new int[] {1,3})));+ Query t = new BooleanQuery.Builder()+ .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);@@ -129,8 +131,10 @@ public class TestComplexExplanations extends BaseExplanationTestCase {q.add(snear(sf("w3",2), st("w2"), st("w3"), 5, true),Occur.SHOULD);- Query t = new FilteredQuery(new TermQuery(new Term(FIELD, "xx")),- new QueryWrapperFilter(matchTheseItems(new int[] {1,3})));+ Query t = new BooleanQuery.Builder()+ .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);@@ -202,7 +206,11 @@ public class TestComplexExplanations extends BaseExplanationTestCase {public void testFQ5() throws Exception {TermQuery query = new TermQuery(new Term(FIELD, "xx"));query.setBoost(0);- bqtest(new FilteredQuery(query, new QueryWrapperFilter(matchTheseItems(new int[] {1,3}))), new int[] {3});+ Query filtered = new BooleanQuery.Builder()+ .add(query, Occur.MUST)+ .add(matchTheseItems(new int[] {1,3}), Occur.FILTER)+ .build();+ bqtest(filtered, new int[] {3});}public void testCSQ4() throws Exception {diff --git a/lucene/core/src/test/org/apache/lucene/search/TestConstantScoreQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestConstantScoreQuery.javaindex 1f73d877848..7ceec72924e 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestConstantScoreQuery.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestConstantScoreQuery.java@@ -30,6 +30,7 @@ import org.apache.lucene.index.LeafReaderContext;import org.apache.lucene.index.MultiReader;import org.apache.lucene.index.RandomIndexWriter;import org.apache.lucene.index.Term;+import org.apache.lucene.search.BooleanClause.Occur;import org.apache.lucene.search.similarities.DefaultSimilarity;import org.apache.lucene.store.Directory;import org.apache.lucene.util.Bits;@@ -181,12 +182,20 @@ public class TestConstantScoreQuery extends LuceneTestCase {Query query = new ConstantScoreQuery(filterB);IndexSearcher s = newSearcher(r);- assertEquals(1, s.search(new FilteredQuery(query, filterB), 1).totalHits); // Query for field:b, Filter field:b+ Query filtered = new BooleanQuery.Builder()+ .add(query, Occur.MUST)+ .add(filterB, Occur.FILTER)+ .build();+ assertEquals(1, s.search(filtered, 1).totalHits); // Query for field:b, Filter field:bFilter filterA = new FilterWrapper(new QueryWrapperFilter(new TermQuery(new Term("field", "a"))));query = new ConstantScoreQuery(filterA);- assertEquals(0, s.search(new FilteredQuery(query, filterB), 1).totalHits); // Query field:b, Filter field:a+ filtered = new BooleanQuery.Builder()+ .add(query, Occur.MUST)+ .add(filterB, Occur.FILTER)+ .build();+ assertEquals(0, s.search(filtered, 1).totalHits); // Query field:b, Filter field:ar.close();d.close();diff --git a/lucene/core/src/test/org/apache/lucene/search/TestDateFilter.java b/lucene/core/src/test/org/apache/lucene/search/TestDateFilter.javaindex c28797067d1..f4b3e532f81 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestDateFilter.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestDateFilter.java@@ -18,6 +18,7 @@ package org.apache.lucene.search;*/import org.apache.lucene.document.Field;+import org.apache.lucene.search.BooleanClause.Occur;import org.apache.lucene.store.Directory;import org.apache.lucene.util.LuceneTestCase;import org.apache.lucene.document.DateTools;@@ -83,16 +84,32 @@ public class TestDateFilter extends LuceneTestCase {assertEquals(1, result.length);// run queries with DateFilter- result = searcher.search(new FilteredQuery(query1, df1), 1000).scoreDocs;+ Query filtered = new BooleanQuery.Builder()+ .add(query1, Occur.MUST)+ .add(df1, Occur.FILTER)+ .build();+ result = searcher.search(filtered, 1000).scoreDocs;assertEquals(0, result.length);- result = searcher.search(new FilteredQuery(query1, df2), 1000).scoreDocs;+ filtered = new BooleanQuery.Builder()+ .add(query1, Occur.MUST)+ .add(df2, Occur.FILTER)+ .build();+ result = searcher.search(filtered, 1000).scoreDocs;assertEquals(0, result.length);- result = searcher.search(new FilteredQuery(query2, df1), 1000).scoreDocs;+ filtered = new BooleanQuery.Builder()+ .add(query2, Occur.MUST)+ .add(df1, Occur.FILTER)+ .build();+ result = searcher.search(filtered, 1000).scoreDocs;assertEquals(1, result.length);- result = searcher.search(new FilteredQuery(query2, df2), 1000).scoreDocs;+ filtered = new BooleanQuery.Builder()+ .add(query2, Occur.MUST)+ .add(df2, Occur.FILTER)+ .build();+ result = searcher.search(filtered, 1000).scoreDocs;assertEquals(0, result.length);reader.close();indexStore.close();@@ -147,16 +164,32 @@ public class TestDateFilter extends LuceneTestCase {assertEquals(1, result.length);// run queries with DateFilter- result = searcher.search(new FilteredQuery(query1, df1), 1000).scoreDocs;+ Query filtered = new BooleanQuery.Builder()+ .add(query1, Occur.MUST)+ .add(df1, Occur.FILTER)+ .build();+ result = searcher.search(filtered, 1000).scoreDocs;assertEquals(0, result.length);- result = searcher.search(new FilteredQuery(query1, df2), 1000).scoreDocs;+ filtered = new BooleanQuery.Builder()+ .add(query1, Occur.MUST)+ .add(df2, Occur.FILTER)+ .build();+ result = searcher.search(filtered, 1000).scoreDocs;assertEquals(0, result.length);- result = searcher.search(new FilteredQuery(query2, df1), 1000).scoreDocs;+ filtered = new BooleanQuery.Builder()+ .add(query2, Occur.MUST)+ .add(df1, Occur.FILTER)+ .build();+ result = searcher.search(filtered, 1000).scoreDocs;assertEquals(1, result.length);- result = searcher.search(new FilteredQuery(query2, df2), 1000).scoreDocs;+ filtered = new BooleanQuery.Builder()+ .add(query2, Occur.MUST)+ .add(df2, Occur.FILTER)+ .build();+ result = searcher.search(filtered, 1000).scoreDocs;assertEquals(0, result.length);reader.close();indexStore.close();diff --git a/lucene/core/src/test/org/apache/lucene/search/TestDocIdSet.java b/lucene/core/src/test/org/apache/lucene/search/TestDocIdSet.javaindex 57835227886..ab2a4c9ddb9 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestDocIdSet.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestDocIdSet.java@@ -29,6 +29,7 @@ import org.apache.lucene.document.Field;import org.apache.lucene.index.LeafReaderContext;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.RandomIndexWriter;+import org.apache.lucene.search.BooleanClause.Occur;import org.apache.lucene.store.Directory;import org.apache.lucene.util.Bits;import org.apache.lucene.util.LuceneTestCase;@@ -132,8 +133,12 @@ public class TestDocIdSet extends LuceneTestCase {return "nullDocIdSetFilter";}};-- Assert.assertEquals(0, searcher.search(new FilteredQuery(new MatchAllDocsQuery(), f), 10).totalHits);++ Query filtered = new BooleanQuery.Builder()+ .add(new MatchAllDocsQuery(), Occur.MUST)+ .add(f, Occur.FILTER)+ .build();+ Assert.assertEquals(0, searcher.search(filtered, 10).totalHits);reader.close();dir.close();}@@ -179,7 +184,11 @@ public class TestDocIdSet extends LuceneTestCase {}};- Assert.assertEquals(0, searcher.search(new FilteredQuery(new MatchAllDocsQuery(), f), 10).totalHits);+ Query filtered = new BooleanQuery.Builder()+ .add(new MatchAllDocsQuery(), Occur.MUST)+ .add(f, Occur.FILTER)+ .build();+ Assert.assertEquals(0, searcher.search(filtered, 10).totalHits);reader.close();dir.close();}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestFilteredQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestFilteredQuery.javadeleted file mode 100644index 8e1c1ac0778..00000000000--- a/lucene/core/src/test/org/apache/lucene/search/TestFilteredQuery.java+++ /dev/null@@ -1,662 +0,0 @@-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.BitSet;-import java.util.Random;--import org.apache.lucene.analysis.MockAnalyzer;-import org.apache.lucene.document.Document;-import org.apache.lucene.document.Field;-import org.apache.lucene.document.Field.Store;-import org.apache.lucene.document.SortedDocValuesField;-import org.apache.lucene.document.StringField;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.LeafReader;-import org.apache.lucene.index.LeafReaderContext;-import org.apache.lucene.index.PostingsEnum;-import org.apache.lucene.index.RandomIndexWriter;-import org.apache.lucene.index.Term;-import org.apache.lucene.search.BooleanClause.Occur;-import org.apache.lucene.search.FilteredQuery.FilterStrategy;-import org.apache.lucene.store.Directory;-import org.apache.lucene.util.BitDocIdSet;-import org.apache.lucene.util.Bits;-import org.apache.lucene.util.BytesRef;-import org.apache.lucene.util.FixedBitSet;-import org.apache.lucene.util.IOUtils;-import org.apache.lucene.util.LuceneTestCase;-import org.apache.lucene.util.TestUtil;--/**- * FilteredQuery JUnit tests.- *- * <p>Created: Apr 21, 2004 1:21:46 PM- *- *- * @since 1.4- */-public class TestFilteredQuery extends LuceneTestCase {-- private IndexSearcher searcher;- private IndexReader reader;- private Directory directory;- private Query query;- private Filter filter;-- @Override- public void setUp() throws Exception {- super.setUp();- directory = newDirectory();- RandomIndexWriter writer = new RandomIndexWriter (random(), directory, newIndexWriterConfig(new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy()));-- Document doc = new Document();- doc.add (newTextField("field", "one two three four five", Field.Store.YES));- doc.add (newTextField("sorter", "b", Field.Store.YES));- doc.add (new SortedDocValuesField("sorter", new BytesRef("b")));- writer.addDocument (doc);-- doc = new Document();- doc.add (newTextField("field", "one two three four", Field.Store.YES));- doc.add (newTextField("sorter", "d", Field.Store.YES));- doc.add (new SortedDocValuesField("sorter", new BytesRef("d")));- writer.addDocument (doc);-- doc = new Document();- doc.add (newTextField("field", "one two three y", Field.Store.YES));- doc.add (newTextField("sorter", "a", Field.Store.YES));- doc.add (new SortedDocValuesField("sorter", new BytesRef("a")));- writer.addDocument (doc);-- doc = new Document();- doc.add (newTextField("field", "one two x", Field.Store.YES));- doc.add (newTextField("sorter", "c", Field.Store.YES));- doc.add (new SortedDocValuesField("sorter", new BytesRef("c")));- writer.addDocument (doc);-- // tests here require single segment (eg try seed- // 8239472272678419952L), because SingleDocTestFilter(x)- // blindly accepts that docID in any sub-segment- writer.forceMerge(1);-- reader = writer.getReader();- writer.close();-- searcher = newSearcher(reader);-- query = new TermQuery (new Term ("field", "three"));- filter = newStaticFilterB();- }-- // must be static for serialization tests- private static Filter newStaticFilterB() {- return new Filter() {- @Override- public DocIdSet getDocIdSet (LeafReaderContext context, Bits acceptDocs) {- if (acceptDocs == null) acceptDocs = new Bits.MatchAllBits(5);- FixedBitSet bitset = new FixedBitSet(context.reader().maxDoc());- if (acceptDocs.get(1)) bitset.set(1);- if (acceptDocs.get(3)) bitset.set(3);- return new BitDocIdSet(bitset);- }- @Override- public String toString(String field) {- return "staticFilterB";- }- };- }-- @Override- public void tearDown() throws Exception {- reader.close();- directory.close();- super.tearDown();- }-- public void testFilteredQuery() throws Exception {- // force the filter to be executed as bits- tFilteredQuery(true);- // force the filter to be executed as iterator- tFilteredQuery(false);- }-- private void tFilteredQuery(final boolean useRandomAccess) throws Exception {- Query filteredquery = new FilteredQuery(query, filter, randomFilterStrategy(random(), useRandomAccess));- ScoreDoc[] hits = searcher.search (filteredquery, 1000).scoreDocs;- assertEquals (1, hits.length);- assertEquals (1, hits[0].doc);- QueryUtils.check(random(), filteredquery,searcher);-- hits = searcher.search (filteredquery, 1000, new Sort(new SortField("sorter", SortField.Type.STRING))).scoreDocs;- assertEquals (1, hits.length);- assertEquals (1, hits[0].doc);-- filteredquery = new FilteredQuery(new TermQuery (new Term ("field", "one")), filter, randomFilterStrategy(random(), useRandomAccess));- hits = searcher.search (filteredquery, 1000).scoreDocs;- assertEquals (2, hits.length);- QueryUtils.check(random(), filteredquery,searcher);-- filteredquery = new FilteredQuery(new MatchAllDocsQuery(), filter, randomFilterStrategy(random(), useRandomAccess));- hits = searcher.search (filteredquery, 1000).scoreDocs;- assertEquals (2, hits.length);- QueryUtils.check(random(), filteredquery,searcher);-- filteredquery = new FilteredQuery(new TermQuery (new Term ("field", "x")), filter, randomFilterStrategy(random(), useRandomAccess));- hits = searcher.search (filteredquery, 1000).scoreDocs;- assertEquals (1, hits.length);- assertEquals (3, hits[0].doc);- QueryUtils.check(random(), filteredquery,searcher);-- filteredquery = new FilteredQuery(new TermQuery (new Term ("field", "y")), filter, randomFilterStrategy(random(), useRandomAccess));- hits = searcher.search (filteredquery, 1000).scoreDocs;- assertEquals (0, hits.length);- QueryUtils.check(random(), filteredquery,searcher);-- // test boost- Filter f = newStaticFilterA();-- float boost = 2.5f;- BooleanQuery.Builder bq1 = new BooleanQuery.Builder();- TermQuery tq = new TermQuery (new Term ("field", "one"));- tq.setBoost(boost);- bq1.add(tq, Occur.MUST);- bq1.add(new TermQuery (new Term ("field", "five")), Occur.MUST);-- BooleanQuery.Builder bq2 = new BooleanQuery.Builder();- tq = new TermQuery (new Term ("field", "one"));- filteredquery = new FilteredQuery(tq, f, randomFilterStrategy(random(), useRandomAccess));- filteredquery.setBoost(boost);- bq2.add(filteredquery, Occur.MUST);- bq2.add(new TermQuery (new Term ("field", "five")), Occur.MUST);- assertScoreEquals(bq1.build(), bq2.build());-- assertEquals(boost, filteredquery.getBoost(), 0);- assertEquals(1.0f, tq.getBoost(), 0); // the boost value of the underlying query shouldn't have changed- }-- // must be static for serialization tests- private static Filter newStaticFilterA() {- return new Filter() {- @Override- public DocIdSet getDocIdSet (LeafReaderContext context, Bits acceptDocs) {- assertNull("acceptDocs should be null, as we have an index without deletions", acceptDocs);- FixedBitSet bitset = new FixedBitSet(context.reader().maxDoc());- bitset.set(0, Math.min(5, bitset.length()));- return new BitDocIdSet(bitset);- }- @Override- public String toString(String field) {- return "staticFilterA";- }- };- }-- /**- * Tests whether the scores of the two queries are the same.- */- public void assertScoreEquals(Query q1, Query q2) throws Exception {- ScoreDoc[] hits1 = searcher.search (q1, 1000).scoreDocs;- ScoreDoc[] hits2 = searcher.search (q2, 1000).scoreDocs;-- assertEquals(hits1.length, hits2.length);-- for (int i = 0; i < hits1.length; i++) {- assertEquals(hits1[i].score, hits2[i].score, 0.000001f);- }- }-- /**- * This tests FilteredQuery's rewrite correctness- */- public void testRangeQuery() throws Exception {- // force the filter to be executed as bits- tRangeQuery(true);- tRangeQuery(false);- }-- private void tRangeQuery(final boolean useRandomAccess) throws Exception {- TermRangeQuery rq = TermRangeQuery.newStringRange(- "sorter", "b", "d", true, true);-- Query filteredquery = new FilteredQuery(rq, filter, randomFilterStrategy(random(), useRandomAccess));- ScoreDoc[] hits = searcher.search(filteredquery, 1000).scoreDocs;- assertEquals(2, hits.length);- QueryUtils.check(random(), filteredquery,searcher);- }-- public void testBooleanMUST() throws Exception {- // force the filter to be executed as bits- tBooleanMUST(true);- // force the filter to be executed as iterator- tBooleanMUST(false);- }-- private void tBooleanMUST(final boolean useRandomAccess) throws Exception {- BooleanQuery.Builder bq = new BooleanQuery.Builder();- Query query = new FilteredQuery(new TermQuery(new Term("field", "one")), new SingleDocTestFilter(0), randomFilterStrategy(random(), useRandomAccess));- bq.add(query, BooleanClause.Occur.MUST);- query = new FilteredQuery(new TermQuery(new Term("field", "one")), new SingleDocTestFilter(1), randomFilterStrategy(random(), useRandomAccess));- bq.add(query, BooleanClause.Occur.MUST);- ScoreDoc[] hits = searcher.search(bq.build(), 1000).scoreDocs;- assertEquals(0, hits.length);- QueryUtils.check(random(), query,searcher);- }-- public void testBooleanSHOULD() throws Exception {- // force the filter to be executed as bits- tBooleanSHOULD(true);- // force the filter to be executed as iterator- tBooleanSHOULD(false);- }-- private void tBooleanSHOULD(final boolean useRandomAccess) throws Exception {- BooleanQuery.Builder bq = new BooleanQuery.Builder();- Query query = new FilteredQuery(new TermQuery(new Term("field", "one")), new SingleDocTestFilter(0), randomFilterStrategy(random(), useRandomAccess));- bq.add(query, BooleanClause.Occur.SHOULD);- query = new FilteredQuery(new TermQuery(new Term("field", "one")), new SingleDocTestFilter(1), randomFilterStrategy(random(), useRandomAccess));- bq.add(query, BooleanClause.Occur.SHOULD);- ScoreDoc[] hits = searcher.search(bq.build(), 1000).scoreDocs;- assertEquals(2, hits.length);- QueryUtils.check(random(), query,searcher);- }-- // Make sure BooleanQuery, which does out-of-order- // scoring, inside FilteredQuery, works- public void testBoolean2() throws Exception {- // force the filter to be executed as bits- tBoolean2(true);- // force the filter to be executed as iterator- tBoolean2(false);- }-- private void tBoolean2(final boolean useRandomAccess) throws Exception {- BooleanQuery.Builder bq = new BooleanQuery.Builder();- bq.add(new TermQuery(new Term("field", "one")), BooleanClause.Occur.SHOULD);- bq.add(new TermQuery(new Term("field", "two")), BooleanClause.Occur.SHOULD);- Query query = new FilteredQuery(bq.build(), new SingleDocTestFilter(0), randomFilterStrategy(random(), useRandomAccess));- ScoreDoc[] hits = searcher.search(query, 1000).scoreDocs;- assertEquals(1, hits.length);- QueryUtils.check(random(), query, searcher);- }-- public void testChainedFilters() throws Exception {- // force the filter to be executed as bits- tChainedFilters(true);- // force the filter to be executed as iterator- tChainedFilters(false);- }-- // a filter for which other queries don't have special rewrite rules- private static class FilterWrapper extends Filter {-- private final Filter in;-- FilterWrapper(Filter in) {- this.in = in;- }-- @Override- public DocIdSet getDocIdSet(LeafReaderContext context, Bits acceptDocs) throws IOException {- return in.getDocIdSet(context, acceptDocs);- }-- @Override- public String toString(String field) {- return in.toString(field);- }-- }-- private void tChainedFilters(final boolean useRandomAccess) throws Exception {- Query query = new FilteredQuery(new FilteredQuery(- new MatchAllDocsQuery(), new FilterWrapper(new QueryWrapperFilter(new TermQuery(new Term("field", "three")))), randomFilterStrategy(random(), useRandomAccess)),- new FilterWrapper(new QueryWrapperFilter(new TermQuery(new Term("field", "four")))), randomFilterStrategy(random(), useRandomAccess));- ScoreDoc[] hits = searcher.search(query, 10).scoreDocs;- assertEquals(2, hits.length);- QueryUtils.check(random(), query, searcher);-- // one more:- query = new FilteredQuery(query,- new FilterWrapper(new QueryWrapperFilter(new TermQuery(new Term("field", "five")))), randomFilterStrategy(random(), useRandomAccess));- hits = searcher.search(query, 10).scoreDocs;- assertEquals(1, hits.length);- QueryUtils.check(random(), query, searcher);- }-- public void testEqualsHashcode() throws Exception {- // some tests before, if the used queries and filters work:- assertEquals(new PrefixQuery(new Term("field", "o")), new PrefixQuery(new Term("field", "o")));- assertFalse(new PrefixQuery(new Term("field", "a")).equals(new PrefixQuery(new Term("field", "o"))));- QueryUtils.checkHashEquals(new TermQuery(new Term("field", "one")));- QueryUtils.checkUnequal(- new TermQuery(new Term("field", "one")), new TermQuery(new Term("field", "two"))- );- // now test FilteredQuery equals/hashcode:- QueryUtils.checkHashEquals(new FilteredQuery(new TermQuery(new Term("field", "one")), new QueryWrapperFilter(new PrefixQuery(new Term("field", "o")))));- QueryUtils.checkUnequal(- new FilteredQuery(new TermQuery(new Term("field", "one")), new QueryWrapperFilter(new PrefixQuery(new Term("field", "o")))),- new FilteredQuery(new TermQuery(new Term("field", "two")), new QueryWrapperFilter(new PrefixQuery(new Term("field", "o"))))- );- QueryUtils.checkUnequal(- new FilteredQuery(new TermQuery(new Term("field", "one")), new QueryWrapperFilter(new PrefixQuery(new Term("field", "a")))),- new FilteredQuery(new TermQuery(new Term("field", "one")), new QueryWrapperFilter(new PrefixQuery(new Term("field", "o"))))- );- }-- public void testInvalidArguments() throws Exception {- try {- new FilteredQuery(null, null);- fail("Should throw NullPointerException");- } catch (NullPointerException npe) {- // pass- }- try {- new FilteredQuery(new TermQuery(new Term("field", "one")), null);- fail("Should throw NullPointerException");- } catch (NullPointerException npe) {- // pass- }- try {- new FilteredQuery(null, new QueryWrapperFilter(new PrefixQuery(new Term("field", "o"))));- fail("Should throw NullPointerException");- } catch (NullPointerException npe) {- // pass- }- }-- private FilterStrategy randomFilterStrategy() {- return randomFilterStrategy(random(), true);- }-- private void assertRewrite(FilteredQuery fq, Class<? extends Query> clazz) throws Exception {- // assign crazy boost to FQ- final float boost = random().nextFloat() * 100.f;- fq.setBoost(boost);--- // assign crazy boost to inner- final float innerBoost = random().nextFloat() * 100.f;- fq.getQuery().setBoost(innerBoost);-- // check the class and boosts of rewritten query- final Query rewritten = searcher.rewrite(fq);- assertTrue("is not instance of " + clazz.getName(), clazz.isInstance(rewritten));- if (rewritten instanceof FilteredQuery) {- assertEquals(boost, rewritten.getBoost(), 1.E-5f);- assertEquals(innerBoost, ((FilteredQuery) rewritten).getQuery().getBoost(), 1.E-5f);- assertEquals(fq.getFilterStrategy(), ((FilteredQuery) rewritten).getFilterStrategy());- } else {- assertEquals(boost * innerBoost, rewritten.getBoost(), 1.E-5f);- }-- // check that the original query was not modified- assertEquals(boost, fq.getBoost(), 1.E-5f);- assertEquals(innerBoost, fq.getQuery().getBoost(), 1.E-5f);- }-- public void testRewrite() throws Exception {- assertRewrite(new FilteredQuery(new TermQuery(new Term("field", "one")), new FilterWrapper(new QueryWrapperFilter(new PrefixQuery(new Term("field", "o")))), randomFilterStrategy()), FilteredQuery.class);- assertRewrite(new FilteredQuery(new PrefixQuery(new Term("field", "one")), new FilterWrapper(new QueryWrapperFilter(new PrefixQuery(new Term("field", "o")))), randomFilterStrategy()), FilteredQuery.class);- }-- public void testGetFilterStrategy() {- FilterStrategy randomFilterStrategy = randomFilterStrategy();- FilteredQuery filteredQuery = new FilteredQuery(new TermQuery(new Term("field", "one")), new QueryWrapperFilter(new PrefixQuery(new Term("field", "o"))), randomFilterStrategy);- assertSame(randomFilterStrategy, filteredQuery.getFilterStrategy());- }-- private static FilteredQuery.FilterStrategy randomFilterStrategy(Random random, final boolean useRandomAccess) {- if (useRandomAccess) {- return new FilteredQuery.RandomAccessFilterStrategy() {- @Override- protected boolean useRandomAccess(Bits bits, long filterCost) {- return true;- }- };- }- return TestUtil.randomFilterStrategy(random);- }-- /*- * Test if the QueryFirst strategy calls the bits only if the document has- * been matched by the query and not otherwise- */- public void testQueryFirstFilterStrategy() throws IOException {- Directory directory = newDirectory();- RandomIndexWriter writer = new RandomIndexWriter(random(), directory,- newIndexWriterConfig(new MockAnalyzer(random())));- int numDocs = atLeast(50);- int totalDocsWithZero = 0;- for (int i = 0; i < numDocs; i++) {- Document doc = new Document();- int num = random().nextInt(5);- if (num == 0) {- totalDocsWithZero++;- }- doc.add(newTextField("field", "" + num, Field.Store.YES));- writer.addDocument(doc);- }- IndexReader reader = writer.getReader();- writer.close();-- IndexSearcher searcher = newSearcher(reader);- Query query = new FilteredQuery(new TermQuery(new Term("field", "0")),- new Filter() {- @Override- public DocIdSet getDocIdSet(LeafReaderContext context,- Bits acceptDocs) throws IOException {- final boolean nullBitset = random().nextInt(10) == 5;- final LeafReader reader = context.reader();- PostingsEnum termPostingsEnum = reader.postings(new Term("field", "0"));- if (termPostingsEnum == null) {- return null; // no docs -- return null- }- final BitSet bitSet = new BitSet(reader.maxDoc());- int d;- while ((d = termPostingsEnum.nextDoc()) != PostingsEnum.NO_MORE_DOCS) {- bitSet.set(d, true);- }- return new DocIdSet() {-- @Override- public long ramBytesUsed() {- return 0L;- }-- @Override- public Bits bits() throws IOException {- if (nullBitset) {- return null;- }- return new Bits() {-- @Override- public boolean get(int index) {- assertTrue("filter was called for a non-matching doc",- bitSet.get(index));- return bitSet.get(index);- }-- @Override- public int length() {- return bitSet.length();- }-- };- }-- @Override- public DocIdSetIterator iterator() throws IOException {- assertTrue(- "iterator should not be called if bitset is present",- nullBitset);- return reader.postings(new Term("field", "0"));- }-- };- }- @Override- public String toString(String field) {- return "filterField0";- }- }, FilteredQuery.QUERY_FIRST_FILTER_STRATEGY);-- TopDocs search = searcher.search(query, 10);- assertEquals(totalDocsWithZero, search.totalHits);- IOUtils.close(reader, directory);- }-- /*- * Test if the leapfrog strategy works correctly in terms- * of advancing / next the right thing first- */- public void testLeapFrogStrategy() throws IOException {- Directory directory = newDirectory();- RandomIndexWriter writer = new RandomIndexWriter (random(), directory, newIndexWriterConfig(new MockAnalyzer(random())));- int numDocs = atLeast(50);- int totalDocsWithZero = 0;- for (int i = 0; i < numDocs; i++) {- Document doc = new Document();- int num = random().nextInt(10);- if (num == 0) {- totalDocsWithZero++;- }- doc.add (newTextField("field", ""+num, Field.Store.YES));- writer.addDocument (doc);- }- IndexReader reader = writer.getReader();- writer.close();- final boolean queryFirst = random().nextBoolean();- IndexSearcher searcher = newSearcher(reader);- Query query = new FilteredQuery(new TermQuery(new Term("field", "0")), new Filter() {- @Override- public DocIdSet getDocIdSet(final LeafReaderContext context, Bits acceptDocs)- throws IOException {- return new DocIdSet() {-- @Override- public long ramBytesUsed() {- return 0L;- }-- @Override- public Bits bits() throws IOException {- return null;- }- @Override- public DocIdSetIterator iterator() throws IOException {- final PostingsEnum termPostingsEnum = context.reader().postings(new Term("field", "0"));- if (termPostingsEnum == null) {- return null;- }- return new DocIdSetIterator() {- boolean nextCalled;- boolean advanceCalled;- @Override- public int nextDoc() throws IOException {- assertTrue("queryFirst: "+ queryFirst + " advanced: " + advanceCalled + " next: "+ nextCalled, nextCalled || advanceCalled ^ !queryFirst);- nextCalled = true;- return termPostingsEnum.nextDoc();- }-- @Override- public int docID() {- return termPostingsEnum.docID();- }-- @Override- public int advance(int target) throws IOException {- assertTrue("queryFirst: "+ queryFirst + " advanced: " + advanceCalled + " next: "+ nextCalled, advanceCalled || nextCalled ^ queryFirst);- advanceCalled = true;- return termPostingsEnum.advance(target);- }-- @Override- public long cost() {- return termPostingsEnum.cost();- }- };- }--- };-- }- @Override- public String toString(String field) {- return "filterField0";- }- }, queryFirst ? FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY : random()- .nextBoolean() ? FilteredQuery.RANDOM_ACCESS_FILTER_STRATEGY- : FilteredQuery.LEAP_FROG_FILTER_FIRST_STRATEGY); // if filterFirst, we can use random here since bits are null-- TopDocs search = searcher.search(query, 10);- assertEquals(totalDocsWithZero, search.totalHits);- IOUtils.close(reader, directory);- }-- public void testPreservesScores() throws IOException {- Directory dir = newDirectory();- RandomIndexWriter writer = new RandomIndexWriter(random(), dir);- Document doc = new Document();- doc.add(new StringField("foo", "bar", Store.NO));- writer.addDocument(doc);- writer.commit();- final IndexReader reader = writer.getReader();- writer.close();- final IndexSearcher searcher = new IndexSearcher(reader);- final Query query = new TermQuery(new Term("foo", "bar"));- query.setBoost(random().nextFloat());- FilteredQuery fq = new FilteredQuery(query, new Filter() {- @Override- public DocIdSet getDocIdSet(LeafReaderContext context, Bits acceptDocs)- throws IOException {- return new DocIdSet() {-- @Override- public long ramBytesUsed() {- return 0;- }-- @Override- public DocIdSetIterator iterator() throws IOException {- return DocIdSetIterator.all(context.reader().maxDoc());- }- };- }- @Override- public String toString(String field) {- return "dummy";- }- });- assertEquals(searcher.search(query, 1).scoreDocs[0].score, searcher.search(fq, 1).scoreDocs[0].score, 0f);- fq.setBoost(random().nextFloat());- // QueryWrapperFilter has special rewrite rules- FilteredQuery fq2 = new FilteredQuery(query, new QueryWrapperFilter(new MatchAllDocsQuery()));- fq2.setBoost(fq.getBoost());- fq2.setBoost(42);- assertEquals(searcher.search(fq, 1).scoreDocs[0].score, searcher.search(fq2, 1).scoreDocs[0].score, 10e-5);- reader.close();- dir.close();- }-}----diff --git a/lucene/core/src/test/org/apache/lucene/search/TestFilteredSearch.java b/lucene/core/src/test/org/apache/lucene/search/TestFilteredSearch.javadeleted file mode 100644index 54481dcb92a..00000000000--- a/lucene/core/src/test/org/apache/lucene/search/TestFilteredSearch.java+++ /dev/null@@ -1,125 +0,0 @@-/*- * 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.- */--package org.apache.lucene.search;--import java.io.IOException;-import java.util.Arrays;--import org.apache.lucene.document.Field;-import org.apache.lucene.index.LeafReaderContext;-import org.apache.lucene.util.LuceneTestCase;-import org.apache.lucene.analysis.MockAnalyzer;-import org.apache.lucene.document.Document;-import org.apache.lucene.index.DirectoryReader;-import org.apache.lucene.index.IndexReader;-import org.apache.lucene.index.IndexWriter;-import org.apache.lucene.index.Term;-import org.apache.lucene.index.IndexWriterConfig.OpenMode;-import org.apache.lucene.store.Directory;-import org.apache.lucene.util.Bits;-import org.apache.lucene.util.BitDocIdSet;-import org.apache.lucene.util.FixedBitSet;----/**- *- */-public class TestFilteredSearch extends LuceneTestCase {-- private static final String FIELD = "category";-- public void testFilteredSearch() throws IOException {- boolean enforceSingleSegment = true;- Directory directory = newDirectory();- int[] filterBits = {1, 36};- SimpleDocIdSetFilter filter = new SimpleDocIdSetFilter(filterBits);- IndexWriter writer = new IndexWriter(directory, newIndexWriterConfig(new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy()));- searchFiltered(writer, directory, filter, enforceSingleSegment);- // run the test on more than one segment- enforceSingleSegment = false;- writer = new IndexWriter(directory, newIndexWriterConfig(new MockAnalyzer(random())).setOpenMode(OpenMode.CREATE).setMaxBufferedDocs(10).setMergePolicy(newLogMergePolicy()));- // we index 60 docs - this will create 6 segments- searchFiltered(writer, directory, filter, enforceSingleSegment);- directory.close();- }-- public void searchFiltered(IndexWriter writer, Directory directory, Filter filter, boolean fullMerge) throws IOException {- for (int i = 0; i < 60; i++) {//Simple docs- Document doc = new Document();- doc.add(newStringField(FIELD, Integer.toString(i), Field.Store.YES));- writer.addDocument(doc);- }- if (fullMerge) {- writer.forceMerge(1);- }- writer.close();-- BooleanQuery.Builder booleanQuery = new BooleanQuery.Builder();- booleanQuery.add(new TermQuery(new Term(FIELD, "36")), BooleanClause.Occur.SHOULD);--- IndexReader reader = DirectoryReader.open(directory);- IndexSearcher indexSearcher = newSearcher(reader);- ScoreDoc[] hits = indexSearcher.search(new FilteredQuery(booleanQuery.build(), filter), 1000).scoreDocs;- assertEquals("Number of matched documents", 1, hits.length);- reader.close();- }-- public static final class SimpleDocIdSetFilter extends Filter {- private final int[] docs;-- public SimpleDocIdSetFilter(int[] docs) {- this.docs = docs;- }-- @Override- public DocIdSet getDocIdSet(LeafReaderContext context, Bits acceptDocs) {- assertNull("acceptDocs should be null, as we have an index without deletions", acceptDocs);- final FixedBitSet set = new FixedBitSet(context.reader().maxDoc());- int docBase = context.docBase;- final int limit = docBase+context.reader().maxDoc();- for (int index=0;index < docs.length; index++) {- final int docId = docs[index];- if (docId >= docBase && docId < limit) {- set.set(docId-docBase);- }- }- return set.cardinality() == 0 ? null : new BitDocIdSet(set);- }-- @Override- public String toString(String field) {- return "SimpleDocIdSetFilter";- }-- @Override- public boolean equals(Object obj) {- if (super.equals(obj) == false) {- return false;- }- return Arrays.equals(docs, ((SimpleDocIdSetFilter) obj).docs);- }-- @Override- public int hashCode() {- return 31 * super.hashCode() + Arrays.hashCode(docs);- }- }--}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestNeedsScores.java b/lucene/core/src/test/org/apache/lucene/search/TestNeedsScores.javaindex 5a0463bbe8b..d5670f7edc0 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestNeedsScores.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestNeedsScores.java@@ -77,10 +77,9 @@ public class TestNeedsScores extends LuceneTestCase {/** when converted to a filter */public void testQueryWrapperFilter() throws Exception {- Query query = new MatchAllDocsQuery();Query term = new TermQuery(new Term("field", "this"));Filter filter = new QueryWrapperFilter(new AssertNeedsScores(term, false));- assertEquals(5, searcher.search(new FilteredQuery(query, filter), 5).totalHits);+ assertEquals(5, searcher.search(filter, 5).totalHits);}/** when not sorting by score */diff --git a/lucene/core/src/test/org/apache/lucene/search/TestQueryWrapperFilter.java b/lucene/core/src/test/org/apache/lucene/search/TestQueryWrapperFilter.javaindex ce03607db11..cf9f9978ec2 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestQueryWrapperFilter.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestQueryWrapperFilter.java@@ -84,9 +84,9 @@ public class TestQueryWrapperFilter extends LuceneTestCase {QueryWrapperFilter qwf = new QueryWrapperFilter(termQuery);IndexSearcher searcher = newSearcher(reader);- TopDocs hits = searcher.search(new FilteredQuery(new MatchAllDocsQuery(), qwf), 10);+ TopDocs hits = searcher.search(qwf, 10);assertEquals(1, hits.totalHits);- hits = searcher.search(new FilteredQuery(new MatchAllDocsQuery(), new FilterWrapper(qwf)), 10);+ hits = searcher.search(new FilterWrapper(qwf), 10);assertEquals(1, hits.totalHits);// should not throw exception with complex primitive query@@ -96,26 +96,26 @@ public class TestQueryWrapperFilter extends LuceneTestCase {Occur.MUST_NOT);qwf = new QueryWrapperFilter(termQuery);- hits = searcher.search(new FilteredQuery(new MatchAllDocsQuery(), qwf), 10);+ hits = searcher.search(qwf, 10);assertEquals(1, hits.totalHits);- hits = searcher.search(new FilteredQuery(new MatchAllDocsQuery(), new FilterWrapper(qwf)), 10);+ hits = searcher.search(new FilterWrapper(qwf), 10);assertEquals(1, hits.totalHits);// should not throw exception with non primitive Query (doesn't implement// Query#createWeight)qwf = new QueryWrapperFilter(new FuzzyQuery(new Term("field", "valu")));- hits = searcher.search(new FilteredQuery(new MatchAllDocsQuery(), qwf), 10);+ hits = searcher.search(qwf, 10);assertEquals(1, hits.totalHits);- hits = searcher.search(new FilteredQuery(new MatchAllDocsQuery(), new FilterWrapper(qwf)), 10);+ hits = searcher.search(new FilterWrapper(qwf), 10);assertEquals(1, hits.totalHits);// test a query with no hitstermQuery = new TermQuery(new Term("field", "not_exist"));qwf = new QueryWrapperFilter(termQuery);- hits = searcher.search(new FilteredQuery(new MatchAllDocsQuery(), qwf), 10);+ hits = searcher.search(qwf, 10);assertEquals(0, hits.totalHits);- hits = searcher.search(new FilteredQuery(new MatchAllDocsQuery(), new FilterWrapper(qwf)), 10);+ hits = searcher.search(new FilterWrapper(qwf), 10);assertEquals(0, hits.totalHits);reader.close();dir.close();@@ -151,8 +151,7 @@ public class TestQueryWrapperFilter extends LuceneTestCase {final IndexReader r = w.getReader();w.close();- final TopDocs hits = newSearcher(r).search(new FilteredQuery(new MatchAllDocsQuery(),- new QueryWrapperFilter(new TermQuery(new Term("field", "a")))),+ final TopDocs hits = newSearcher(r).search(new QueryWrapperFilter(new TermQuery(new Term("field", "a"))),numDocs);assertEquals(aDocs.size(), hits.totalHits);for(ScoreDoc sd: hits.scoreDocs) {@@ -179,7 +178,7 @@ public class TestQueryWrapperFilter extends LuceneTestCase {for (int i = 0; i < 1000; i++) {TermQuery termQuery = new TermQuery(new Term("field", English.intToEnglish(i)));QueryWrapperFilter qwf = new QueryWrapperFilter(termQuery);- TopDocs td = searcher.search(new FilteredQuery(new MatchAllDocsQuery(), qwf), 10);+ TopDocs td = searcher.search(qwf, 10);assertEquals(1, td.totalHits);}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestSimpleExplanations.java b/lucene/core/src/test/org/apache/lucene/search/TestSimpleExplanations.javaindex 31c8cb6a0c9..21ee8968770 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestSimpleExplanations.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestSimpleExplanations.java@@ -82,36 +82,6 @@ public class TestSimpleExplanations extends BaseExplanationTestCase {qtest(phraseQuery, new int[] { 0,1,2,3 });}- /* some simple filtered query tests */-- public void testFQ1() throws Exception {- qtest(new FilteredQuery(new TermQuery(new Term(FIELD, "w1")),- new QueryWrapperFilter(matchTheseItems(new int[] {0,1,2,3}))),- new int[] {0,1,2,3});- }- public void testFQ2() throws Exception {- qtest(new FilteredQuery(new TermQuery(new Term(FIELD, "w1")),- new QueryWrapperFilter(matchTheseItems(new int[] {0,2,3}))),- new int[] {0,2,3});- }- public void testFQ3() throws Exception {- qtest(new FilteredQuery(new TermQuery(new Term(FIELD, "xx")),- new QueryWrapperFilter(matchTheseItems(new int[] {1,3}))),- new int[] {3});- }- public void testFQ4() throws Exception {- TermQuery termQuery = new TermQuery(new Term(FIELD, "xx"));- termQuery.setBoost(1000);- qtest(new FilteredQuery(termQuery, new QueryWrapperFilter(matchTheseItems(new int[] {1,3}))),- new int[] {3});- }- public void testFQ6() throws Exception {- Query q = new FilteredQuery(new TermQuery(new Term(FIELD, "xx")),- new QueryWrapperFilter(matchTheseItems(new int[] {1,3})));- q.setBoost(1000);- qtest(q, new int[] {3});- }-/* ConstantScoreQueries */public void testCSQ1() throws Exception {diff --git a/lucene/core/src/test/org/apache/lucene/search/TestSortRandom.java b/lucene/core/src/test/org/apache/lucene/search/TestSortRandom.javaindex 19db26a4fc3..9ec83ebe655 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestSortRandom.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestSortRandom.java@@ -148,21 +148,8 @@ public class TestSortRandom extends LuceneTestCase {}final int hitCount = TestUtil.nextInt(random, 1, r.maxDoc() + 20);final RandomFilter f = new RandomFilter(random.nextLong(), random.nextFloat(), docValues);- int queryType = random.nextInt(2);- if (queryType == 0) {- // force out of order- BooleanQuery.Builder bq = new BooleanQuery.Builder();- // Add a Query with SHOULD, since bw.scorer() returns BooleanScorer2- // which delegates to BS if there are no mandatory clauses.- bq.add(new MatchAllDocsQuery(), Occur.SHOULD);- // Set minNrShouldMatch to 1 so that BQ will not optimize rewrite to return- // the clause instead of BQ.- bq.setMinimumNumberShouldMatch(1);- hits = s.search(new FilteredQuery(bq.build(), f), hitCount, sort, random.nextBoolean(), random.nextBoolean());- } else {- hits = s.search(new ConstantScoreQuery(f),- hitCount, sort, random.nextBoolean(), random.nextBoolean());- }+ hits = s.search(new ConstantScoreQuery(f),+ hitCount, sort, random.nextBoolean(), random.nextBoolean());if (VERBOSE) {System.out.println("\nTEST: iter=" + iter + " " + hits.totalHits + " hits; topN=" + hitCount + "; reverse=" + reverse + "; sortMissingLast=" + sortMissingLast + " sort=" + sort);diff --git a/lucene/facet/src/java/org/apache/lucene/facet/DrillDownQuery.java b/lucene/facet/src/java/org/apache/lucene/facet/DrillDownQuery.javaindex fc3ad1b9e96..187ff6aee4c 100644--- a/lucene/facet/src/java/org/apache/lucene/facet/DrillDownQuery.java+++ b/lucene/facet/src/java/org/apache/lucene/facet/DrillDownQuery.java@@ -30,7 +30,6 @@ import org.apache.lucene.search.BooleanClause.Occur;import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.ConstantScoreQuery;import org.apache.lucene.search.Filter;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.MatchAllDocsQuery;import org.apache.lucene.search.Query;import org.apache.lucene.search.TermQuery;@@ -69,7 +68,10 @@ public final class DrillDownQuery extends Query {/** Used by DrillSideways */DrillDownQuery(FacetsConfig config, Filter filter, DrillDownQuery other) {- this.baseQuery = new FilteredQuery(other.baseQuery == null ? new MatchAllDocsQuery() : other.baseQuery, filter);+ this.baseQuery = new BooleanQuery.Builder()+ .add(other.baseQuery == null ? new MatchAllDocsQuery() : other.baseQuery, Occur.MUST)+ .add(filter, Occur.FILTER)+ .build();this.dimQueries.addAll(other.dimQueries);this.drillDownDims.putAll(other.drillDownDims);this.config = config;diff --git a/lucene/facet/src/java/org/apache/lucene/facet/FacetsCollector.java b/lucene/facet/src/java/org/apache/lucene/facet/FacetsCollector.javaindex 57d7764f60b..f883a4f4d62 100644--- a/lucene/facet/src/java/org/apache/lucene/facet/FacetsCollector.java+++ b/lucene/facet/src/java/org/apache/lucene/facet/FacetsCollector.java@@ -22,11 +22,12 @@ import java.util.ArrayList;import java.util.List;import org.apache.lucene.index.LeafReaderContext;+import org.apache.lucene.search.BooleanClause.Occur;+import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.Collector;import org.apache.lucene.search.DocIdSet;import org.apache.lucene.search.FieldDoc;import org.apache.lucene.search.Filter;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.MultiCollector;import org.apache.lucene.search.Query;@@ -256,7 +257,10 @@ public class FacetsCollector extends SimpleCollector implements Collector {boolean doDocScores, boolean doMaxScore, Collector fc) throws IOException {if (filter != null) {- q = new FilteredQuery(q, filter);+ q = new BooleanQuery.Builder()+ .add(q, Occur.MUST)+ .add(filter, Occur.FILTER)+ .build();}int limit = searcher.getIndexReader().maxDoc();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.javaindex c96bbc28a6b..4724d5b714d 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@@ -108,6 +108,7 @@ public final class DoubleRange extends Range {private final ValueSource valueSource;ValueSourceFilter(DoubleRange range, Filter fastMatchFilter, ValueSource valueSource) {+ super(true);this.range = range;this.fastMatchFilter = fastMatchFilter;this.valueSource = valueSource;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.javaindex 4d741b82016..257b016d944 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@@ -100,6 +100,7 @@ public final class LongRange extends Range {private final ValueSource valueSource;ValueSourceFilter(LongRange range, Filter fastMatchFilter, ValueSource valueSource) {+ super(true);this.range = range;this.fastMatchFilter = fastMatchFilter;this.valueSource = valueSource;diff --git a/lucene/facet/src/java/org/apache/lucene/facet/range/Range.java b/lucene/facet/src/java/org/apache/lucene/facet/range/Range.javaindex b2735a9a5bf..0f407658bef 100644--- a/lucene/facet/src/java/org/apache/lucene/facet/range/Range.java+++ b/lucene/facet/src/java/org/apache/lucene/facet/range/Range.java@@ -21,7 +21,6 @@ import org.apache.lucene.facet.DrillDownQuery; // javadocsimport org.apache.lucene.facet.DrillSideways; // javadocsimport org.apache.lucene.queries.function.ValueSource;import org.apache.lucene.search.Filter;-import org.apache.lucene.search.FilteredQuery; // javadocsimport org.apache.lucene.search.NumericRangeQuery;/** Base class for a single labeled range.@@ -43,9 +42,7 @@ public abstract class Range {/** Returns a new {@link Filter} accepting only documents* in this range. This filter is not general-purpose;* you should either use it with {@link DrillSideways} by- * adding it to {@link DrillDownQuery#add}, or pass it to- * {@link FilteredQuery} using its {@link- * FilteredQuery#QUERY_FIRST_FILTER_STRATEGY}. If the+ * adding it to {@link DrillDownQuery#add}. If the* {@link ValueSource} is static, e.g. an indexed numeric* field, then it may be more efficient to use {@link* NumericRangeQuery}. The provided fastMatchFilter,@@ -57,9 +54,7 @@ public abstract class Range {/** Returns a new {@link Filter} accepting only documents* in this range. This filter is not general-purpose;* you should either use it with {@link DrillSideways} by- * adding it to {@link DrillDownQuery#add}, or pass it to- * {@link FilteredQuery} using its {@link- * FilteredQuery#QUERY_FIRST_FILTER_STRATEGY}. If the+ * adding it to {@link DrillDownQuery#add}. If the* {@link ValueSource} is static, e.g. an indexed numeric* field, then it may be more efficient to use {@link NumericRangeQuery}. */public Filter getFilter(ValueSource valueSource) {diff --git a/lucene/facet/src/test/org/apache/lucene/facet/TestDrillSideways.java b/lucene/facet/src/test/org/apache/lucene/facet/TestDrillSideways.javaindex f496d8c4296..0ab3d1ee47c 100644--- a/lucene/facet/src/test/org/apache/lucene/facet/TestDrillSideways.java+++ b/lucene/facet/src/test/org/apache/lucene/facet/TestDrillSideways.java@@ -45,11 +45,11 @@ import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.RandomIndexWriter;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.Collector;import org.apache.lucene.search.DocIdSet;import org.apache.lucene.search.Filter;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.MatchAllDocsQuery;import org.apache.lucene.search.Query;@@ -758,7 +758,10 @@ public class TestDrillSideways extends FacetTestCase {// Make sure drill down doesn't change score:Query q = ddq;if (filter != null) {- q = new FilteredQuery(q, filter);+ q = new BooleanQuery.Builder()+ .add(q, Occur.MUST)+ .add(filter, Occur.FILTER)+ .build();}TopDocs ddqHits = s.search(q, numDocs);assertEquals(expected.hits.size(), ddqHits.totalHits);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.javaindex 76e53270334..ff7fc7b1b11 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,7 +25,6 @@ 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.FilteredQuery;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.Query;@@ -123,8 +122,6 @@ public final class QueryTermExtractortry {if (query instanceof BooleanQuery)getTermsFromBooleanQuery((BooleanQuery) query, terms, prohibited, fieldName);- else if (query instanceof FilteredQuery)- getTermsFromFilteredQuery((FilteredQuery) query, terms, prohibited, fieldName);else {HashSet<Term> nonWeightedTerms = new HashSet<>();try {@@ -163,9 +160,5 @@ public final class QueryTermExtractorgetTerms(clause.getQuery(), terms, prohibited, fieldName);}}- private static void getTermsFromFilteredQuery(FilteredQuery query, HashSet<WeightedTerm> terms, boolean prohibited, String fieldName)- {- getTerms(query.getQuery(),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.javaindex 2d35c04a5b6..e51f992a15a 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@@ -37,7 +37,6 @@ import org.apache.lucene.search.BooleanClause;import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.ConstantScoreQuery;import org.apache.lucene.search.DisjunctionMaxQuery;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.MatchAllDocsQuery;import org.apache.lucene.search.MultiPhraseQuery;@@ -151,8 +150,6 @@ public class WeightedSpanTermExtractor {extractWeightedTerms(terms, query);} else if (query instanceof SpanQuery) {extractWeightedSpanTerms(terms, (SpanQuery) query);- } else if (query instanceof FilteredQuery) {- extract(((FilteredQuery) query).getQuery(), terms);} else if (query instanceof ConstantScoreQuery) {final Query q = ((ConstantScoreQuery) query).getQuery();if (q != null) {diff --git a/lucene/highlighter/src/java/org/apache/lucene/search/postingshighlight/MultiTermHighlighting.java b/lucene/highlighter/src/java/org/apache/lucene/search/postingshighlight/MultiTermHighlighting.javaindex 3e73f1f7e57..21e9250d6fe 100644--- a/lucene/highlighter/src/java/org/apache/lucene/search/postingshighlight/MultiTermHighlighting.java+++ b/lucene/highlighter/src/java/org/apache/lucene/search/postingshighlight/MultiTermHighlighting.java@@ -33,7 +33,6 @@ import org.apache.lucene.search.BooleanClause;import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.ConstantScoreQuery;import org.apache.lucene.search.DisjunctionMaxQuery;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.FuzzyQuery;import org.apache.lucene.search.PrefixQuery;import org.apache.lucene.search.Query;@@ -69,8 +68,6 @@ class MultiTermHighlighting {list.addAll(Arrays.asList(extractAutomata(clause.getQuery(), field)));}}- } else if (query instanceof FilteredQuery) {- list.addAll(Arrays.asList(extractAutomata(((FilteredQuery) query).getQuery(), field)));} else if (query instanceof ConstantScoreQuery) {list.addAll(Arrays.asList(extractAutomata(((ConstantScoreQuery) query).getQuery(), field)));} else if (query instanceof DisjunctionMaxQuery) {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.javaindex 6c2b355397b..59f91da49e9 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@@ -34,7 +34,6 @@ import org.apache.lucene.search.BooleanClause;import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.ConstantScoreQuery;import org.apache.lucene.search.DisjunctionMaxQuery;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.MultiTermQuery;import org.apache.lucene.search.PhraseQuery;import org.apache.lucene.search.Query;@@ -123,11 +122,6 @@ public class FieldQuery {if (q != null) {flatten( applyParentBoost( q, sourceQuery ), reader, flatQueries);}- } else if (sourceQuery instanceof FilteredQuery) {- final Query q = ((FilteredQuery) sourceQuery).getQuery();- if (q != null) {- flatten( applyParentBoost( q, sourceQuery ), reader, flatQueries);- }} else if (sourceQuery instanceof CustomScoreQuery) {final Query q = ((CustomScoreQuery) sourceQuery).getSubQuery();if (q != null) {diff --git a/lucene/highlighter/src/test/org/apache/lucene/search/postingshighlight/TestMultiTermHighlighting.java b/lucene/highlighter/src/test/org/apache/lucene/search/postingshighlight/TestMultiTermHighlighting.javaindex 583ce9f9f64..9369b7bac7f 100644--- a/lucene/highlighter/src/test/org/apache/lucene/search/postingshighlight/TestMultiTermHighlighting.java+++ b/lucene/highlighter/src/test/org/apache/lucene/search/postingshighlight/TestMultiTermHighlighting.java@@ -30,16 +30,15 @@ import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.RandomIndexWriter;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.ConstantScoreQuery;import org.apache.lucene.search.DisjunctionMaxQuery;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.FuzzyQuery;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.MatchAllDocsQuery;import org.apache.lucene.search.PrefixQuery;import org.apache.lucene.search.Query;-import org.apache.lucene.search.QueryWrapperFilter;import org.apache.lucene.search.RegexpQuery;import org.apache.lucene.search.Sort;import org.apache.lucene.search.TermQuery;@@ -471,9 +470,10 @@ public class TestMultiTermHighlighting extends LuceneTestCase {return analyzer;}};- FilteredQuery query = new FilteredQuery(- new WildcardQuery(new Term("body", "te*")),- new QueryWrapperFilter(new TermQuery(new Term("body", "test"))));+ Query query = new BooleanQuery.Builder()+ .add(new WildcardQuery(new Term("body", "te*")), Occur.MUST)+ .add(new TermQuery(new Term("body", "test")), Occur.FILTER)+ .build();TopDocs topDocs = searcher.search(query, 10, Sort.INDEXORDER);assertEquals(2, topDocs.totalHits);String snippets[] = highlighter.highlight("body", query, searcher, topDocs);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.javaindex c1ad94137c7..fba2858cb20 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@@ -30,7 +30,6 @@ import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.ConstantScoreQuery;import org.apache.lucene.search.DocIdSet;import org.apache.lucene.search.Filter;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.PrefixQuery;import org.apache.lucene.search.Query;import org.apache.lucene.search.RegexpQuery;@@ -940,7 +939,7 @@ public class FieldQueryTest extends AbstractTestCase {public void testFlattenFilteredQuery() throws Exception {initBoost();- Query query = new FilteredQuery(pqF( "A" ), new Filter() {+ Filter filter = new Filter() {@Overridepublic DocIdSet getDocIdSet(LeafReaderContext context, Bits acceptDocs)throws IOException {@@ -950,7 +949,11 @@ public class FieldQueryTest extends AbstractTestCase {public String toString(String field) {return "filterToBeFlattened";}- });+ };+ Query query = new BooleanQuery.Builder()+ .add(pqF( "A" ), Occur.MUST)+ .add(filter, Occur.FILTER)+ .build();query.setBoost(boost);FieldQuery fq = new FieldQuery( query, true, true );Set<Query> flatQueries = new HashSet<>();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.javaindex b23e057815b..b37554a0734 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@@ -228,9 +228,8 @@ public class TestBlockJoin extends LuceneTestCase {assertEquals("Lisa", getParentDoc(r, parentsFilter, hits.scoreDocs[0].doc).get("name"));// Test with filter on child docs:- assertEquals(0, s.search(new FilteredQuery(fullChildQuery.build(),- new QueryWrapperFilter(new TermQuery(new Term("skill", "foosball")))),- 1).totalHits);+ fullChildQuery.add(new TermQuery(new Term("skill", "foosball")), Occur.FILTER);+ assertEquals(0, s.search(fullChildQuery.build(), 1).totalHits);r.close();dir.close();@@ -336,20 +335,44 @@ public class TestBlockJoin extends LuceneTestCase {assertEquals("no filter - both passed", 2, s.search(childJoinQuery, 10).totalHits);- assertEquals("dummy filter passes everyone ", 2, s.search(new FilteredQuery(childJoinQuery, parentsFilter), 10).totalHits);- assertEquals("dummy filter passes everyone ", 2, s.search(new FilteredQuery(childJoinQuery, new QueryWrapperFilter(new TermQuery(new Term("docType", "resume")))), 10).totalHits);+ Query query = new BooleanQuery.Builder()+ .add(childJoinQuery, Occur.MUST)+ .add(parentsFilter, Occur.FILTER)+ .build();+ assertEquals("dummy filter passes everyone ", 2, s.search(query, 10).totalHits);+ query = new BooleanQuery.Builder()+ .add(childJoinQuery, Occur.MUST)+ .add(new TermQuery(new Term("docType", "resume")), Occur.FILTER)+ .build();+ assertEquals("dummy filter passes everyone ", 2, s.search(query, 10).totalHits);// not found test- assertEquals("noone live there", 0, s.search(new FilteredQuery(childJoinQuery, new BitDocIdSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("country", "Oz"))))), 1).totalHits);- assertEquals("noone live there", 0, s.search(new FilteredQuery(childJoinQuery, new QueryWrapperFilter(new TermQuery(new Term("country", "Oz")))), 1).totalHits);+ query = new BooleanQuery.Builder()+ .add(childJoinQuery, Occur.MUST)+ .add(new BitDocIdSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("country", "Oz")))), Occur.FILTER)+ .build();+ assertEquals("noone live there", 0, s.search(query, 1).totalHits);+ query = new BooleanQuery.Builder()+ .add(childJoinQuery, Occur.MUST)+ .add(new QueryWrapperFilter(new TermQuery(new Term("country", "Oz"))), Occur.FILTER)+ .build();+ assertEquals("noone live there", 0, s.search(query, 1).totalHits);// apply the UK filter by the searcher- TopDocs ukOnly = s.search(new FilteredQuery(childJoinQuery, new QueryWrapperFilter(parentQuery)), 1);+ query = new BooleanQuery.Builder()+ .add(childJoinQuery, Occur.MUST)+ .add(new QueryWrapperFilter(parentQuery), Occur.FILTER)+ .build();+ TopDocs ukOnly = s.search(query, 1);assertEquals("has filter - single passed", 1, ukOnly.totalHits);assertEquals( "Lisa", r.document(ukOnly.scoreDocs[0].doc).get("name"));+ query = new BooleanQuery.Builder()+ .add(childJoinQuery, Occur.MUST)+ .add(new QueryWrapperFilter(new TermQuery(new Term("country", "United States"))), Occur.FILTER)+ .build();// looking for US candidates- TopDocs usThen = s.search(new FilteredQuery(childJoinQuery , new QueryWrapperFilter(new TermQuery(new Term("country", "United States")))), 1);+ TopDocs usThen = s.search(query, 1);assertEquals("has filter - single passed", 1, usThen.totalHits);assertEquals("Frank", r.document(usThen.scoreDocs[0].doc).get("name"));@@ -359,14 +382,20 @@ public class TestBlockJoin extends LuceneTestCase {s.search(new ToChildBlockJoinQuery(us,parentsFilter), 10).totalHits );- assertEquals("java skills in US", 1, s.search(new FilteredQuery(new ToChildBlockJoinQuery(us, parentsFilter),- skill("java")), 10).totalHits );+ query = new BooleanQuery.Builder()+ .add(new ToChildBlockJoinQuery(us, parentsFilter), Occur.MUST)+ .add(skill("java"), Occur.FILTER)+ .build();+ assertEquals("java skills in US", 1, s.search(query, 10).totalHits );BooleanQuery.Builder rubyPython = new BooleanQuery.Builder();rubyPython.add(new TermQuery(new Term("skill", "ruby")), Occur.SHOULD);rubyPython.add(new TermQuery(new Term("skill", "python")), Occur.SHOULD);- assertEquals("ruby skills in US", 1, s.search(new FilteredQuery(new ToChildBlockJoinQuery(us, parentsFilter),- new QueryWrapperFilter(rubyPython.build())), 10).totalHits );+ query = new BooleanQuery.Builder()+ .add(new ToChildBlockJoinQuery(us, parentsFilter), Occur.MUST)+ .add(rubyPython.build(), Occur.FILTER)+ .build();+ assertEquals("ruby skills in US", 1, s.search(query, 10).totalHits );r.close();dir.close();@@ -910,8 +939,10 @@ public class TestBlockJoin extends LuceneTestCase {if (random().nextBoolean()) { // filtered casechildJoinQuery2 = parentJoinQuery2;final Filter f = new QueryWrapperFilter(new TermQuery(childTerm));- childJoinQuery2 = new FilteredQuery(childJoinQuery2, random().nextBoolean()- ? new BitDocIdSetCachingWrapperFilter(f): f);+ childJoinQuery2 = new BooleanQuery.Builder()+ .add(childJoinQuery2, Occur.MUST)+ .add(random().nextBoolean() ? new BitDocIdSetCachingWrapperFilter(f): f, Occur.FILTER)+ .build();} else {// AND child field w/ parent query:final BooleanQuery.Builder bq = new BooleanQuery.Builder();@@ -930,8 +961,10 @@ public class TestBlockJoin extends LuceneTestCase {if (random().nextBoolean()) { // filtered casechildQuery2 = parentQuery2;final Filter f = new QueryWrapperFilter(new TermQuery(childTerm));- childQuery2 = new FilteredQuery(childQuery2, random().nextBoolean()- ? new BitDocIdSetCachingWrapperFilter(f): f);+ childQuery2 = new BooleanQuery.Builder()+ .add(childQuery2, Occur.MUST)+ .add(random().nextBoolean() ? new BitDocIdSetCachingWrapperFilter(f): f, Occur.FILTER)+ .build();} else {final BooleanQuery.Builder bq2 = new BooleanQuery.Builder();if (random().nextBoolean()) {diff --git a/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoinSorting.java b/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoinSorting.javaindex 5620766a4d5..de853ee43db 100644--- a/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoinSorting.java+++ b/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoinSorting.java@@ -27,10 +27,7 @@ import org.apache.lucene.index.NoMergePolicy;import org.apache.lucene.index.RandomIndexWriter;import org.apache.lucene.index.Term;import org.apache.lucene.search.FieldDoc;-import org.apache.lucene.search.Filter;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.IndexSearcher;-import org.apache.lucene.search.MatchAllDocsQuery;import org.apache.lucene.search.PrefixQuery;import org.apache.lucene.search.QueryWrapperFilter;import org.apache.lucene.search.Sort;@@ -234,7 +231,7 @@ public class TestBlockJoinSorting extends LuceneTestCase {BitDocIdSetFilter parentFilter = new BitDocIdSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("__type", "parent"))));BitDocIdSetFilter childFilter = new BitDocIdSetCachingWrapperFilter(new QueryWrapperFilter(new PrefixQuery(new Term("field2"))));ToParentBlockJoinQuery query = new ToParentBlockJoinQuery(- new FilteredQuery(new MatchAllDocsQuery(), childFilter),+ childFilter,new BitDocIdSetCachingWrapperFilter(parentFilter),ScoreMode.None);@@ -299,7 +296,7 @@ public class TestBlockJoinSorting extends LuceneTestCase {// Sort by field descending, order last, sort filter (filter_1:T)childFilter = new BitDocIdSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery((new Term("filter_1", "T")))));query = new ToParentBlockJoinQuery(- new FilteredQuery(new MatchAllDocsQuery(), childFilter),+ childFilter,new BitDocIdSetCachingWrapperFilter(parentFilter),ScoreMode.None);diff --git a/lucene/misc/src/test/org/apache/lucene/uninverting/TestFieldCacheSortRandom.java b/lucene/misc/src/test/org/apache/lucene/uninverting/TestFieldCacheSortRandom.javaindex 7d10002cd08..085b44057ce 100644--- a/lucene/misc/src/test/org/apache/lucene/uninverting/TestFieldCacheSortRandom.java+++ b/lucene/misc/src/test/org/apache/lucene/uninverting/TestFieldCacheSortRandom.java@@ -38,15 +38,11 @@ import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.LeafReaderContext;import org.apache.lucene.index.NumericDocValues;import org.apache.lucene.index.RandomIndexWriter;-import org.apache.lucene.search.BooleanClause.Occur;-import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.ConstantScoreQuery;import org.apache.lucene.search.DocIdSet;import org.apache.lucene.search.FieldDoc;import org.apache.lucene.search.Filter;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.IndexSearcher;-import org.apache.lucene.search.MatchAllDocsQuery;import org.apache.lucene.search.Sort;import org.apache.lucene.search.SortField;import org.apache.lucene.search.TopFieldDocs;@@ -165,23 +161,12 @@ public class TestFieldCacheSortRandom extends LuceneTestCase {}final int hitCount = TestUtil.nextInt(random, 1, r.maxDoc() + 20);final RandomFilter f = new RandomFilter(random.nextLong(), random.nextFloat(), docValues);- int queryType = random.nextInt(3);+ int queryType = random.nextInt(2);if (queryType == 0) {- // force out of order- BooleanQuery.Builder bq = new BooleanQuery.Builder();- // Add a Query with SHOULD, since bw.scorer() returns BooleanScorer2- // which delegates to BS if there are no mandatory clauses.- bq.add(new MatchAllDocsQuery(), Occur.SHOULD);- // Set minNrShouldMatch to 1 so that BQ will not optimize rewrite to return- // the clause instead of BQ.- bq.setMinimumNumberShouldMatch(1);- hits = s.search(new FilteredQuery(bq.build(), f), hitCount, sort, random.nextBoolean(), random.nextBoolean());- } else if (queryType == 1) {hits = s.search(new ConstantScoreQuery(f),hitCount, sort, random.nextBoolean(), random.nextBoolean());} else {- hits = s.search(new FilteredQuery(new MatchAllDocsQuery(),- f), hitCount, sort, random.nextBoolean(), random.nextBoolean());+ hits = s.search(f, hitCount, sort, random.nextBoolean(), random.nextBoolean());}if (VERBOSE) {diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/CoreParser.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/CoreParser.javaindex 8a8360ee1ff..d6f6848352b 100644--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/CoreParser.java+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/CoreParser.java@@ -9,6 +9,7 @@ import org.w3c.dom.Element;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;+import java.io.InputStream;/*@@ -36,9 +37,8 @@ public class CoreParser implements QueryBuilder {protected Analyzer analyzer;protected QueryParser parser;protected QueryBuilderFactory queryFactory;- protected FilterBuilderFactory filterFactory;//Controls the max size of the LRU cache used for QueryFilter objects parsed.- public static int maxNumCachedFilters = 20;+ public static int maxNumCachedQueries = 20;/**@@ -63,7 +63,6 @@ public class CoreParser implements QueryBuilder {protected CoreParser(String defaultField, Analyzer analyzer, QueryParser parser) {this.analyzer = analyzer;this.parser = parser;- filterFactory = new FilterBuilderFactory();queryFactory = new QueryBuilderFactory();queryFactory.addBuilder("TermQuery", new TermQueryBuilder());@@ -78,12 +77,8 @@ public class CoreParser implements QueryBuilder {} else {queryFactory.addBuilder("UserQuery", new UserInputQueryBuilder(defaultField, analyzer));}- queryFactory.addBuilder("FilteredQuery", new FilteredQueryBuilder(filterFactory, queryFactory));queryFactory.addBuilder("ConstantScoreQuery", new ConstantScoreQueryBuilder(queryFactory));-- filterFactory.addBuilder("CachedFilter", new CachedFilterBuilder(queryFactory,- filterFactory, maxNumCachedFilters));-+ queryFactory.addBuilder("CachedQuery", new CachedQueryBuilder(queryFactory, maxNumCachedQueries));SpanQueryBuilderFactory sqof = new SpanQueryBuilderFactory();@@ -124,10 +119,6 @@ public class CoreParser implements QueryBuilder {queryFactory.addBuilder(nodeName, builder);}- public void addFilterBuilder(String nodeName, FilterBuilder builder) {- filterFactory.addBuilder(nodeName, builder);- }-private static Document parseXML(InputStream pXmlFile) throws ParserException {DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilder db = null;diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/CorePlusExtensionsParser.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/CorePlusExtensionsParser.javaindex b257f3f5499..456f6d1e168 100644--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/CorePlusExtensionsParser.java+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/CorePlusExtensionsParser.java@@ -49,7 +49,7 @@ public class CorePlusExtensionsParser extends CoreParser {private CorePlusExtensionsParser(String defaultField, Analyzer analyzer, QueryParser parser) {super(defaultField, analyzer, parser);- filterFactory.addBuilder("DuplicateFilter", new DuplicateFilterBuilder());+ queryFactory.addBuilder("DuplicateFilter", new DuplicateFilterBuilder());String fields[] = {"contents"};queryFactory.addBuilder("LikeThisQuery", new LikeThisQueryBuilder(analyzer, fields));queryFactory.addBuilder("BoostingQuery", new BoostingQueryBuilder(queryFactory));diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/FilterBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/FilterBuilder.javadeleted file mode 100644index 0e732f6ba75..00000000000--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/FilterBuilder.java+++ /dev/null@@ -1,31 +0,0 @@-/*- * Created on 25-Jan-2006- */-package org.apache.lucene.queryparser.xml;--import org.apache.lucene.search.Filter;-import org.w3c.dom.Element;-/*- * 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.- */--/**- * Interface for building {@link Filter}s- */-public interface FilterBuilder {-- public Filter getFilter(Element e) throws ParserException;-}diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/FilterBuilderFactory.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/FilterBuilderFactory.javadeleted file mode 100644index 1ab1bb8ae15..00000000000--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/FilterBuilderFactory.java+++ /dev/null@@ -1,50 +0,0 @@-/*- * Created on 25-Jan-2006- */-package org.apache.lucene.queryparser.xml;--import org.apache.lucene.search.Filter;-import org.w3c.dom.Element;--import java.util.HashMap;-/*- * 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.- */--/**- * Factory for {@link FilterBuilder}- */-public class FilterBuilderFactory implements FilterBuilder {-- HashMap<String, FilterBuilder> builders = new HashMap<>();-- @Override- public Filter getFilter(Element n) throws ParserException {- FilterBuilder builder = builders.get(n.getNodeName());- if (builder == null) {- throw new ParserException("No FilterBuilder defined for node " + n.getNodeName());- }- return builder.getFilter(n);- }-- public void addBuilder(String nodeName, FilterBuilder builder) {- builders.put(nodeName, builder);- }-- public FilterBuilder getFilterBuilder(String nodeName) {- return builders.get(nodeName);- }-}diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/CachedFilterBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/CachedQueryBuilder.javasimilarity index 70%rename from lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/CachedFilterBuilder.javarename to lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/CachedQueryBuilder.javaindex a40c8ee5596..817c5755f7f 100644--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/CachedFilterBuilder.java+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/CachedQueryBuilder.java@@ -3,14 +3,15 @@*/package org.apache.lucene.queryparser.xml.builders;-import org.apache.lucene.queryparser.xml.*;+import java.util.Map;++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.CachingWrapperQuery;-import org.apache.lucene.search.Filter;import org.apache.lucene.search.Query;-import org.apache.lucene.search.QueryWrapperFilter;import org.w3c.dom.Element;--import java.util.Map;/** Licensed to the Apache Software Foundation (ASF) under one or more* contributor license agreements. See the NOTICE file distributed with@@ -43,58 +44,44 @@ import java.util.Map;* The CoreParser.maxNumCachedFilters property can be used to control the size of the LRU* Cache established during the construction of CoreParser instances.*/-public class CachedFilterBuilder implements FilterBuilder {+public class CachedQueryBuilder implements QueryBuilder {private final QueryBuilderFactory queryFactory;- private final FilterBuilderFactory filterFactory;- private LRUCache<Object, Query> filterCache;+ private LRUCache<Object, Query> queryCache;private final int cacheSize;- public CachedFilterBuilder(QueryBuilderFactory queryFactory,- FilterBuilderFactory filterFactory,+ public CachedQueryBuilder(QueryBuilderFactory queryFactory,int cacheSize) {this.queryFactory = queryFactory;- this.filterFactory = filterFactory;this.cacheSize = cacheSize;}@Override- public synchronized Filter getFilter(Element e) throws ParserException {+ public synchronized Query getQuery(Element e) throws ParserException {Element childElement = DOMUtils.getFirstChildOrFail(e);- if (filterCache == null) {- filterCache = new LRUCache<>(cacheSize);+ if (queryCache == null) {+ queryCache = new LRUCache<>(cacheSize);}// Test to see if child Element is a query or filter that needs to be// cachedQueryBuilder qb = queryFactory.getQueryBuilder(childElement.getNodeName());Object cacheKey = null;- Query q = null;- Filter f = null;- if (qb != null) {- q = qb.getQuery(childElement);- cacheKey = q;- } else {- f = filterFactory.getFilter(childElement);- cacheKey = f;- }- Query cachedFilter = filterCache.get(cacheKey);- if (cachedFilter != null) {- return new QueryWrapperFilter(cachedFilter); // cache hit+ Query q = qb.getQuery(childElement);+ cacheKey = q;+ Query cachedQuery = queryCache.get(cacheKey);+ if (cachedQuery != null) {+ return cachedQuery; // cache hit}//cache miss- if (qb != null) {- cachedFilter = new QueryWrapperFilter(q);- } else {- cachedFilter = new CachingWrapperQuery(f);- }+ cachedQuery = new CachingWrapperQuery(q);- filterCache.put(cacheKey, cachedFilter);- return new QueryWrapperFilter(cachedFilter);+ queryCache.put(cacheKey, cachedQuery);+ return cachedQuery;}static class LRUCache<K, V> extends java.util.LinkedHashMap<K, V> {diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/DuplicateFilterBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/DuplicateFilterBuilder.javaindex b85703ac190..02b908746c9 100644--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/DuplicateFilterBuilder.java+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/DuplicateFilterBuilder.java@@ -4,8 +4,8 @@package org.apache.lucene.queryparser.xml.builders;import org.apache.lucene.queryparser.xml.DOMUtils;-import org.apache.lucene.queryparser.xml.FilterBuilder;import org.apache.lucene.queryparser.xml.ParserException;+import org.apache.lucene.queryparser.xml.QueryBuilder;import org.apache.lucene.sandbox.queries.DuplicateFilter;import org.apache.lucene.search.Filter;import org.w3c.dom.Element;@@ -30,10 +30,10 @@ import org.w3c.dom.Element;/*** Builder for {@link DuplicateFilter}*/-public class DuplicateFilterBuilder implements FilterBuilder {+public class DuplicateFilterBuilder implements QueryBuilder {@Override- public Filter getFilter(Element e) throws ParserException {+ public Filter getQuery(Element e) throws ParserException {String fieldName = DOMUtils.getAttributeWithInheritanceOrFail(e, "fieldName");DuplicateFilter df = new DuplicateFilter(fieldName);diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/FilteredQueryBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/FilteredQueryBuilder.javadeleted file mode 100644index 1c2a6ecea46..00000000000--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/FilteredQueryBuilder.java+++ /dev/null@@ -1,64 +0,0 @@-/*- * Created on 25-Jan-2006- */-package org.apache.lucene.queryparser.xml.builders;--import org.apache.lucene.search.Filter;-import org.apache.lucene.search.FilteredQuery;-import org.apache.lucene.search.Query;-import org.apache.lucene.queryparser.xml.DOMUtils;-import org.apache.lucene.queryparser.xml.FilterBuilder;-import org.apache.lucene.queryparser.xml.ParserException;-import org.apache.lucene.queryparser.xml.QueryBuilder;-import org.w3c.dom.Element;--/*- * 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.- */--/**- * Builder for {@link FilteredQuery}- */-public class FilteredQueryBuilder implements QueryBuilder {-- private final FilterBuilder filterFactory;- private final QueryBuilder queryFactory;-- public FilteredQueryBuilder(FilterBuilder filterFactory, QueryBuilder queryFactory) {- this.filterFactory = filterFactory;- this.queryFactory = queryFactory;-- }-- /* (non-Javadoc)- * @see org.apache.lucene.xmlparser.QueryObjectBuilder#process(org.w3c.dom.Element)- */- @Override- public Query getQuery(Element e) throws ParserException {- Element filterElement = DOMUtils.getChildByTagOrFail(e, "Filter");- filterElement = DOMUtils.getFirstChildOrFail(filterElement);- Filter f = filterFactory.getFilter(filterElement);-- Element queryElement = DOMUtils.getChildByTagOrFail(e, "Query");- queryElement = DOMUtils.getFirstChildOrFail(queryElement);- Query q = queryFactory.getQuery(queryElement);-- FilteredQuery fq = new FilteredQuery(q, f);- fq.setBoost(DOMUtils.getAttribute(e, "boost", 1.0f));- return fq;- }--}diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/xml/CachedFilter.xml b/lucene/queryparser/src/test/org/apache/lucene/queryparser/xml/CachedQuery.xmlsimilarity index 86%rename from lucene/queryparser/src/test/org/apache/lucene/queryparser/xml/CachedFilter.xmlrename to lucene/queryparser/src/test/org/apache/lucene/queryparser/xml/CachedQuery.xmlindex 7d10711107e..40dc0f7f58d 100644--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/xml/CachedFilter.xml+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/xml/CachedQuery.xml@@ -15,19 +15,14 @@See the License for the specific language governing permissions andlimitations under the License.-->-<FilteredQuery>- <Query>- <BooleanQuery fieldName="contents">- <Clause occurs="should">- <TermQuery>merger</TermQuery>- </Clause>- <Clause occurs="mustnot">- <TermQuery >sumitomo</TermQuery>- </Clause>- </BooleanQuery>- </Query>-- <Filter>+<BooleanQuery fieldName="contents">+ <Clause occurs="should">+ <TermQuery>merger</TermQuery>+ </Clause>+ <Clause occurs="mustnot">+ <TermQuery >sumitomo</TermQuery>+ </Clause>+ <Clause occurs="filter"><!--CachedFilter elements can contain any Query or Filter.CachedFilters are cached in an LRU Cache keyed on the contained query/filter object.@@ -45,13 +40,12 @@The CoreParser.maxNumCachedFilters property can be used to control the sizeof the LRU Cache established during the construction of CoreParser instances.-->- <CachedFilter>+ <CachedQuery><!-- Example query to be cached for fast, repeated use --><TermQuery fieldName="contents">bank</TermQuery><!-- Alternatively, a filter object can be cached ....<RangeFilter fieldName="date" lowerTerm="19870409" upperTerm="19870412"/>-->- </CachedFilter>- </Filter>--</FilteredQuery>+ </CachedQuery>+ </Clause>+</BooleanQuery>diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/xml/DuplicateFilterQuery.xml b/lucene/queryparser/src/test/org/apache/lucene/queryparser/xml/DuplicateFilterQuery.xmlindex c5002c7c98b..979c1983d08 100644--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/xml/DuplicateFilterQuery.xml+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/xml/DuplicateFilterQuery.xml@@ -15,20 +15,15 @@See the License for the specific language governing permissions andlimitations under the License.-->-<FilteredQuery>- <Query>- <BooleanQuery fieldName="contents">- <Clause occurs="should">- <TermQuery>money</TermQuery>- </Clause>- <Clause occurs="must">- <TermQuery fieldName="date">19870408</TermQuery>- </Clause>- </BooleanQuery>- </Query>- <Filter>+<BooleanQuery fieldName="contents">+ <Clause occurs="should">+ <TermQuery>money</TermQuery>+ </Clause>+ <Clause occurs="must">+ <TermQuery fieldName="date">19870408</TermQuery>+ </Clause>+ <Clause occurs="filter"><!-- Filters to last document with this date --><DuplicateFilter fieldName="date" keepMode="last"/>- </Filter>--</FilteredQuery>+ </Clause>+</BooleanQuery>diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/xml/TestParser.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/xml/TestParser.javaindex 4f9b3c33d8e..94e5902e9cb 100644--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/xml/TestParser.java+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/xml/TestParser.java@@ -182,7 +182,7 @@ public class TestParser extends LuceneTestCase {}public void testCachedFilterXML() throws ParserException, IOException {- Query q = parse("CachedFilter.xml");+ Query q = parse("CachedQuery.xml");dumpResults("Cached filter", q, 5);}diff --git a/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/DuplicateFilterTest.java b/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/DuplicateFilterTest.javaindex 2c232c6c9d7..42f151d5e31 100644--- a/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/DuplicateFilterTest.java+++ b/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/DuplicateFilterTest.java@@ -25,9 +25,11 @@ import org.apache.lucene.analysis.MockAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.index.*;+import org.apache.lucene.search.BooleanClause.Occur;+import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.DocIdSetIterator;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.Query;import org.apache.lucene.search.ScoreDoc;import org.apache.lucene.search.TermQuery;import org.apache.lucene.store.Directory;@@ -88,7 +90,11 @@ public class DuplicateFilterTest extends LuceneTestCase {public void testDefaultFilter() throws Throwable {DuplicateFilter df = new DuplicateFilter(KEY_FIELD);HashSet<String> results = new HashSet<>();- ScoreDoc[] hits = searcher.search(new FilteredQuery(tq, df), 1000).scoreDocs;+ Query query = new BooleanQuery.Builder()+ .add(tq, Occur.MUST)+ .add(df, Occur.FILTER)+ .build();+ ScoreDoc[] hits = searcher.search(query, 1000).scoreDocs;for (ScoreDoc hit : hits) {StoredDocument d = searcher.doc(hit.doc);@@ -118,7 +124,11 @@ public class DuplicateFilterTest extends LuceneTestCase {DuplicateFilter df = new DuplicateFilter(KEY_FIELD);df.setProcessingMode(DuplicateFilter.ProcessingMode.PM_FAST_INVALIDATION);HashSet<String> results = new HashSet<>();- ScoreDoc[] hits = searcher.search(new FilteredQuery(tq, df), 1000).scoreDocs;+ Query query = new BooleanQuery.Builder()+ .add(tq, Occur.MUST)+ .add(df, Occur.FILTER)+ .build();+ ScoreDoc[] hits = searcher.search(query, 1000).scoreDocs;assertTrue("Filtered searching should have found some matches", hits.length > 0);for (ScoreDoc hit : hits) {@@ -133,7 +143,11 @@ public class DuplicateFilterTest extends LuceneTestCase {public void testKeepsLastFilter() throws Throwable {DuplicateFilter df = new DuplicateFilter(KEY_FIELD);df.setKeepMode(DuplicateFilter.KeepMode.KM_USE_LAST_OCCURRENCE);- ScoreDoc[] hits = searcher.search(new FilteredQuery(tq, df), 1000).scoreDocs;+ Query query = new BooleanQuery.Builder()+ .add(tq, Occur.MUST)+ .add(df, Occur.FILTER)+ .build();+ ScoreDoc[] hits = searcher.search(query, 1000).scoreDocs;assertTrue("Filtered searching should have found some matches", hits.length > 0);for (ScoreDoc hit : hits) {StoredDocument d = searcher.doc(hit.doc);@@ -157,7 +171,11 @@ public class DuplicateFilterTest extends LuceneTestCase {public void testKeepsFirstFilter() throws Throwable {DuplicateFilter df = new DuplicateFilter(KEY_FIELD);df.setKeepMode(DuplicateFilter.KeepMode.KM_USE_FIRST_OCCURRENCE);- ScoreDoc[] hits = searcher.search(new FilteredQuery(tq, df), 1000).scoreDocs;+ Query query = new BooleanQuery.Builder()+ .add(tq, Occur.MUST)+ .add(df, Occur.FILTER)+ .build();+ ScoreDoc[] hits = searcher.search(query, 1000).scoreDocs;assertTrue("Filtered searching should have found some matches", hits.length > 0);for (ScoreDoc hit : hits) {StoredDocument d = searcher.doc(hit.doc);diff --git a/lucene/sandbox/src/test/org/apache/lucene/search/TestTermAutomatonQuery.java b/lucene/sandbox/src/test/org/apache/lucene/search/TestTermAutomatonQuery.javaindex f5f49a21dcb..564a5393a53 100644--- a/lucene/sandbox/src/test/org/apache/lucene/search/TestTermAutomatonQuery.java+++ b/lucene/sandbox/src/test/org/apache/lucene/search/TestTermAutomatonQuery.java@@ -44,6 +44,7 @@ import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.LeafReaderContext;import org.apache.lucene.index.RandomIndexWriter;import org.apache.lucene.index.Term;+import org.apache.lucene.search.BooleanClause.Occur;import org.apache.lucene.store.Directory;import org.apache.lucene.util.BitDocIdSet;import org.apache.lucene.util.Bits;@@ -584,8 +585,14 @@ public class TestTermAutomatonQuery extends LuceneTestCase {System.out.println(" use random filter");}RandomFilter filter = new RandomFilter(random().nextLong(), random().nextFloat());- q1 = new FilteredQuery(q1, filter);- q2 = new FilteredQuery(q2, filter);+ q1 = new BooleanQuery.Builder()+ .add(q1, Occur.MUST)+ .add(filter, Occur.FILTER)+ .build();+ q2 = new BooleanQuery.Builder()+ .add(q2, Occur.MUST)+ .add(filter, Occur.FILTER)+ .build();}TopDocs hits1 = s.search(q1, numDocs);diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/serialized/SerializedDVStrategy.java b/lucene/spatial/src/java/org/apache/lucene/spatial/serialized/SerializedDVStrategy.javaindex d292e97680f..c05c0684a33 100644--- a/lucene/spatial/src/java/org/apache/lucene/spatial/serialized/SerializedDVStrategy.java+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/serialized/SerializedDVStrategy.java@@ -111,7 +111,7 @@ public class SerializedDVStrategy extends SpatialStrategy {}/**- * Returns a Filter that should be used with {@link org.apache.lucene.search.FilteredQuery#QUERY_FIRST_FILTER_STRATEGY}.+ * Returns a Filter that should be used in a random-access fashion.* Use in another manner is likely to result in an {@link java.lang.UnsupportedOperationException}* to prevent misuse because the filter can't efficiently work via iteration.*/@@ -139,6 +139,7 @@ public class SerializedDVStrategy extends SpatialStrategy {private final ValueSource predicateValueSource;//we call boolVal(doc)public PredicateValueSourceFilter(ValueSource predicateValueSource) {+ super(true);this.predicateValueSource = predicateValueSource;}@@ -148,7 +149,7 @@ public class SerializedDVStrategy extends SpatialStrategy {@Overridepublic DocIdSetIterator iterator() throws IOException {throw new UnsupportedOperationException(- "Iteration is too slow; instead try FilteredQuery.QUERY_FIRST_FILTER_STRATEGY");+ "Iteration is too slow; consume using DocIdSet.bits() instead");//Note that if you're truly bent on doing this, then see FunctionValues.getRangeScorer}diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/vector/PointVectorStrategy.java b/lucene/spatial/src/java/org/apache/lucene/spatial/vector/PointVectorStrategy.javaindex 74c488c65d5..b798105e997 100644--- a/lucene/spatial/src/java/org/apache/lucene/spatial/vector/PointVectorStrategy.java+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/vector/PointVectorStrategy.java@@ -31,8 +31,6 @@ import org.apache.lucene.search.BooleanClause;import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.ConstantScoreQuery;import org.apache.lucene.search.Filter;-import org.apache.lucene.search.FilteredQuery;-import org.apache.lucene.search.MatchAllDocsQuery;import org.apache.lucene.search.NumericRangeQuery;import org.apache.lucene.search.Query;import org.apache.lucene.search.QueryWrapperFilter;@@ -202,7 +200,7 @@ public class PointVectorStrategy extends SpatialStrategy {ValueSourceFilter vsf = new ValueSourceFilter(new QueryWrapperFilter( spatial ), valueSource, 0, circle.getRadius() );- spatial = new FilteredQuery( new MatchAllDocsQuery(), vsf );+ spatial = vsf;}}else if( op == SpatialOperation.IsDisjointTo ) {diff --git a/lucene/spatial/src/test/org/apache/lucene/spatial/PortedSolr3Test.java b/lucene/spatial/src/test/org/apache/lucene/spatial/PortedSolr3Test.javaindex cc3fb022cf0..f8ae42d3202 100644--- a/lucene/spatial/src/test/org/apache/lucene/spatial/PortedSolr3Test.java+++ b/lucene/spatial/src/test/org/apache/lucene/spatial/PortedSolr3Test.java@@ -23,8 +23,6 @@ import com.spatial4j.core.context.SpatialContext;import com.spatial4j.core.distance.DistanceUtils;import com.spatial4j.core.shape.Point;import com.spatial4j.core.shape.Shape;-import org.apache.lucene.search.FilteredQuery;-import org.apache.lucene.search.MatchAllDocsQuery;import org.apache.lucene.search.Query;import org.apache.lucene.spatial.prefix.RecursivePrefixTreeStrategy;import org.apache.lucene.spatial.prefix.TermQueryPrefixTreeStrategy;@@ -171,7 +169,7 @@ public class PortedSolr3Test extends StrategyTestCase {if (random().nextBoolean()) {query = strategy.makeQuery(args);} else {- query = new FilteredQuery(new MatchAllDocsQuery(),strategy.makeFilter(args));+ query = strategy.makeFilter(args);}SearchResults results = executeQuery(query, 100);assertEquals(""+shape,assertNumFound,results.numFound);diff --git a/lucene/spatial/src/test/org/apache/lucene/spatial/SpatialExample.java b/lucene/spatial/src/test/org/apache/lucene/spatial/SpatialExample.javaindex cda0e87d66a..e939fceda40 100644--- a/lucene/spatial/src/test/org/apache/lucene/spatial/SpatialExample.java+++ b/lucene/spatial/src/test/org/apache/lucene/spatial/SpatialExample.java@@ -24,7 +24,6 @@ import com.spatial4j.core.shape.Shape;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;-import org.apache.lucene.document.IntField;import org.apache.lucene.document.NumericDocValuesField;import org.apache.lucene.document.StoredField;import org.apache.lucene.index.DirectoryReader;@@ -34,7 +33,6 @@ import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.StoredDocument;import org.apache.lucene.queries.function.ValueSource;import org.apache.lucene.search.Filter;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.MatchAllDocsQuery;import org.apache.lucene.search.Sort;@@ -154,7 +152,7 @@ public class SpatialExample extends LuceneTestCase {SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects,ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(200, DistanceUtils.EARTH_MEAN_RADIUS_KM)));Filter filter = strategy.makeFilter(args);- TopDocs docs = indexSearcher.search(new FilteredQuery(new MatchAllDocsQuery(), filter), 10, idSort);+ TopDocs docs = indexSearcher.search(filter, 10, idSort);assertDocMatchedIds(indexSearcher, docs, 2);//Now, lets get the distance for the 1st doc via computing from stored point value:// (this computation is usually not redundant)diff --git a/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/HeatmapFacetCounterTest.java b/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/HeatmapFacetCounterTest.javaindex e7c29e7b5ee..b63fcb7b2f8 100644--- a/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/HeatmapFacetCounterTest.java+++ b/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/HeatmapFacetCounterTest.java@@ -32,7 +32,6 @@ import com.spatial4j.core.shape.Shape;import com.spatial4j.core.shape.SpatialRelation;import com.spatial4j.core.shape.impl.RectangleImpl;import org.apache.lucene.search.Filter;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.MatchAllDocsQuery;import org.apache.lucene.search.TotalHitCountCollector;import org.apache.lucene.spatial.StrategyTestCase;@@ -236,7 +235,7 @@ public class HeatmapFacetCounterTest extends StrategyTestCase {Filter filter = new IntersectsPrefixTreeFilter(pt, strategy.getFieldName(), grid, facetLevel, grid.getMaxLevels());final TotalHitCountCollector collector = new TotalHitCountCollector();- indexSearcher.search(new FilteredQuery(new MatchAllDocsQuery(), filter), collector);+ indexSearcher.search(filter, collector);cellsValidated++;if (collector.getTotalHits() > 0) {cellValidatedNonZero++;diff --git a/lucene/spatial/src/test/org/apache/lucene/spatial/serialized/SerializedStrategyTest.java b/lucene/spatial/src/test/org/apache/lucene/spatial/serialized/SerializedStrategyTest.javaindex 7ad5f2f68ef..7d60446dbb1 100644--- a/lucene/spatial/src/test/org/apache/lucene/spatial/serialized/SerializedStrategyTest.java+++ b/lucene/spatial/src/test/org/apache/lucene/spatial/serialized/SerializedStrategyTest.java@@ -18,8 +18,6 @@ package org.apache.lucene.spatial.serialized;*/import com.spatial4j.core.context.SpatialContext;-import org.apache.lucene.search.FilteredQuery;-import org.apache.lucene.search.MatchAllDocsQuery;import org.apache.lucene.search.Query;import org.apache.lucene.spatial.SpatialMatchConcern;import org.apache.lucene.spatial.SpatialTestQuery;@@ -47,8 +45,7 @@ public class SerializedStrategyTest extends StrategyTestCase {//called by StrategyTestCase; we can't let it call our makeQuery which will UOE ex.@Overrideprotected Query makeQuery(SpatialTestQuery q) {- return new FilteredQuery(new MatchAllDocsQuery(), strategy.makeFilter(q.args),- FilteredQuery.QUERY_FIRST_FILTER_STRATEGY);+ return strategy.makeFilter(q.args);}@Testdiff --git a/lucene/test-framework/src/java/org/apache/lucene/analysis/CollationTestBase.java b/lucene/test-framework/src/java/org/apache/lucene/analysis/CollationTestBase.javaindex 7ecee9639f1..ea524d98e81 100644--- a/lucene/test-framework/src/java/org/apache/lucene/analysis/CollationTestBase.java+++ b/lucene/test-framework/src/java/org/apache/lucene/analysis/CollationTestBase.java@@ -36,7 +36,6 @@ import org.apache.lucene.index.StoredDocument;import org.apache.lucene.index.Term;import org.apache.lucene.search.BooleanClause.Occur;import org.apache.lucene.search.BooleanQuery;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.Query;import org.apache.lucene.search.ScoreDoc;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.javaindex 26b79ec577e..707dd4f7dd2 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@@ -54,15 +54,6 @@ public class QueryUtils {/** Check the types of things query objects should be able to do. */public static void check(Query q) {checkHashEquals(q);-- if (q instanceof FilteredQuery) {- // This is our best option to have coverage on filters since they are- // rarely searched on directly- // This hack can go away when FilteredQuery goes away too- FilteredQuery filtered = (FilteredQuery) q;- check(filtered.getQuery());- check(filtered.getFilter());- }}/** check very basic hashCode and equals */diff --git a/lucene/test-framework/src/java/org/apache/lucene/search/SearchEquivalenceTestBase.java b/lucene/test-framework/src/java/org/apache/lucene/search/SearchEquivalenceTestBase.javaindex 85b26f220d1..0e4a33120cb 100644--- a/lucene/test-framework/src/java/org/apache/lucene/search/SearchEquivalenceTestBase.java+++ b/lucene/test-framework/src/java/org/apache/lucene/search/SearchEquivalenceTestBase.java@@ -275,13 +275,19 @@ public abstract class SearchEquivalenceTestBase extends LuceneTestCase {** Both queries will be filtered by <code>filter</code>*/- protected void assertSubsetOf(Query q1, Query q2, Filter filter) throws Exception {+ protected void assertSubsetOf(Query q1, Query q2, Query filter) throws Exception {QueryUtils.check(q1);QueryUtils.check(q2);if (filter != null) {- q1 = new FilteredQuery(q1, filter);- q2 = new FilteredQuery(q2, filter);+ q1 = new BooleanQuery.Builder()+ .add(q1, Occur.MUST)+ .add(filter, Occur.FILTER)+ .build();+ q2 = new BooleanQuery.Builder()+ .add(q2, Occur.MUST)+ .add(filter, Occur.FILTER)+ .build();}// we test both INDEXORDER and RELEVANCE because we want to test needsScores=true/falsefor (Sort sort : new Sort[] { Sort.INDEXORDER, Sort.RELEVANCE }) {@@ -323,11 +329,17 @@ public abstract class SearchEquivalenceTestBase extends LuceneTestCase {}}- protected void assertSameScores(Query q1, Query q2, Filter filter) throws Exception {+ protected void assertSameScores(Query q1, Query q2, Query filter) throws Exception {// not efficient, but simple!if (filter != null) {- q1 = new FilteredQuery(q1, filter);- q2 = new FilteredQuery(q2, filter);+ q1 = new BooleanQuery.Builder()+ .add(q1, Occur.MUST)+ .add(filter, Occur.FILTER)+ .build();+ q2 = new BooleanQuery.Builder()+ .add(q2, Occur.MUST)+ .add(filter, Occur.FILTER)+ .build();}TopDocs td1 = s1.search(q1, reader.maxDoc());TopDocs td2 = s2.search(q2, reader.maxDoc());@@ -338,8 +350,11 @@ public abstract class SearchEquivalenceTestBase extends LuceneTestCase {}}- protected Query filteredQuery(Query query, Filter filter) {- return new FilteredQuery(query, filter, TestUtil.randomFilterStrategy(random()));+ protected Query filteredQuery(Query query, Query filter) {+ return new BooleanQuery.Builder()+ .add(query, Occur.MUST)+ .add(filter, Occur.FILTER)+ .build();}protected Query filteredBooleanQuery(Query query, Filter filter) {diff --git a/lucene/test-framework/src/java/org/apache/lucene/util/TestUtil.java b/lucene/test-framework/src/java/org/apache/lucene/util/TestUtil.javaindex 7c948b5d490..e6914c967be 100644--- a/lucene/test-framework/src/java/org/apache/lucene/util/TestUtil.java+++ b/lucene/test-framework/src/java/org/apache/lucene/util/TestUtil.java@@ -93,8 +93,6 @@ import org.apache.lucene.index.Terms;import org.apache.lucene.index.TermsEnum;import org.apache.lucene.index.TieredMergePolicy;import org.apache.lucene.search.FieldDoc;-import org.apache.lucene.search.FilteredQuery;-import org.apache.lucene.search.FilteredQuery.FilterStrategy;import org.apache.lucene.search.ScoreDoc;import org.apache.lucene.search.TopDocs;import org.apache.lucene.store.Directory;@@ -1177,30 +1175,6 @@ public final class TestUtil {}}}--- public static final FilterStrategy randomFilterStrategy(final Random random) {- switch(random.nextInt(6)) {- case 5:- case 4:- return new FilteredQuery.RandomAccessFilterStrategy() {- @Override- protected boolean useRandomAccess(Bits bits, long filterCost) {- return LuceneTestCase.random().nextBoolean();- }- };- case 3:- return FilteredQuery.RANDOM_ACCESS_FILTER_STRATEGY;- case 2:- return FilteredQuery.LEAP_FROG_FILTER_FIRST_STRATEGY;- case 1:- return FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY;- case 0:- return FilteredQuery.QUERY_FIRST_FILTER_STRATEGY;- default:- return FilteredQuery.RANDOM_ACCESS_FILTER_STRATEGY;- }- }/*** Returns a random string in the specified length range consistingdiff --git a/solr/contrib/analytics/src/java/org/apache/solr/analytics/accumulator/FacetingAccumulator.java b/solr/contrib/analytics/src/java/org/apache/solr/analytics/accumulator/FacetingAccumulator.javaindex 3e470901bb2..62a4a5701df 100644--- a/solr/contrib/analytics/src/java/org/apache/solr/analytics/accumulator/FacetingAccumulator.java+++ b/solr/contrib/analytics/src/java/org/apache/solr/analytics/accumulator/FacetingAccumulator.java@@ -32,8 +32,9 @@ import java.util.Set;import java.util.TreeMap;import org.apache.lucene.index.LeafReaderContext;+import org.apache.lucene.search.BooleanClause.Occur;+import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.Filter;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.Query;import org.apache.solr.analytics.accumulator.facet.FacetValueAccumulator;import org.apache.solr.analytics.accumulator.facet.FieldFacetAccumulator;@@ -612,7 +613,11 @@ public class FacetingAccumulator extends BasicAccumulator implements FacetValueA}// The searcher sends docIds to the QueryFacetAccumulator which forwards// them to <code>collectQuery()</code> in this class for collection.- searcher.search(new FilteredQuery(q, filter), qAcc);+ Query filtered = new BooleanQuery.Builder()+ .add(q, Occur.MUST)+ .add(filter, Occur.FILTER)+ .build();+ searcher.search(filtered, qAcc);computeQueryFacet(qfr.getName());queryCount++;}@@ -716,7 +721,11 @@ public class FacetingAccumulator extends BasicAccumulator implements FacetValueARangeFacetAccumulator rAcc = new RangeFacetAccumulator(this,rfr.getName(),facetValue);// The searcher sends docIds to the RangeFacetAccumulator which forwards// them to <code>collectRange()</code> in this class for collection.- searcher.search(new FilteredQuery(q, filter), rAcc);+ Query filtered = new BooleanQuery.Builder()+ .add(q, Occur.MUST)+ .add(filter, Occur.FILTER)+ .build();+ searcher.search(filtered, rAcc);computeRangeFacet(sf.getName());}}diff --git a/solr/core/src/java/org/apache/solr/handler/component/ExpandComponent.java b/solr/core/src/java/org/apache/solr/handler/component/ExpandComponent.javaindex c775bb70135..34ac972352b 100644--- a/solr/core/src/java/org/apache/solr/handler/component/ExpandComponent.java+++ b/solr/core/src/java/org/apache/solr/handler/component/ExpandComponent.java@@ -36,6 +36,7 @@ import com.carrotsearch.hppc.cursors.IntObjectCursor;import com.carrotsearch.hppc.cursors.LongCursor;import com.carrotsearch.hppc.cursors.LongObjectCursor;import com.carrotsearch.hppc.cursors.ObjectCursor;+import org.apache.lucene.index.DocValues;import org.apache.lucene.index.DocValuesType;import org.apache.lucene.index.FieldInfo;@@ -47,9 +48,10 @@ import org.apache.lucene.index.MultiDocValues;import org.apache.lucene.index.NumericDocValues;import org.apache.lucene.index.SortedDocValues;import org.apache.lucene.queries.TermsQuery;+import org.apache.lucene.search.BooleanClause.Occur;+import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.Collector;import org.apache.lucene.search.DocIdSetIterator;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.LeafCollector;import org.apache.lucene.search.Query;import org.apache.lucene.search.QueryWrapperFilter;@@ -381,7 +383,11 @@ public class ExpandComponent extends SearchComponent implements PluginInfoInitiaif (pfilter.filter == null) {searcher.search(query, collector);} else {- searcher.search(new FilteredQuery(query, pfilter.filter), collector);+ Query q = new BooleanQuery.Builder()+ .add(query, Occur.MUST)+ .add(pfilter.filter, Occur.FILTER)+ .build();+ searcher.search(q, collector);}LongObjectMap groups = ((GroupCollector)groupExpandCollector).getGroups();NamedList outMap = new SimpleOrderedMap();diff --git a/solr/core/src/java/org/apache/solr/request/SimpleFacets.java b/solr/core/src/java/org/apache/solr/request/SimpleFacets.javaindex 4958f3a77bd..61372f6c830 100644--- a/solr/core/src/java/org/apache/solr/request/SimpleFacets.java+++ b/solr/core/src/java/org/apache/solr/request/SimpleFacets.java@@ -26,10 +26,11 @@ import org.apache.lucene.index.PostingsEnum;import org.apache.lucene.index.Term;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.DocIdSetIterator;import org.apache.lucene.search.Filter;import org.apache.lucene.search.FilterCollector;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.LeafCollector;import org.apache.lucene.search.MatchAllDocsQuery;import org.apache.lucene.search.Query;@@ -251,7 +252,7 @@ public class SimpleFacets {return;}AbstractAllGroupHeadsCollector allGroupHeadsCollector = grouping.getCommands().get(0).createAllGroupCollector();- searcher.search(new FilteredQuery(new MatchAllDocsQuery(), base.getTopFilter()), allGroupHeadsCollector);+ searcher.search(base.getTopFilter(), allGroupHeadsCollector);this.docs = new BitDocSet(allGroupHeadsCollector.retrieveGroupHeads(searcher.maxDoc()));} else {this.docs = base;@@ -350,7 +351,11 @@ public class SimpleFacets {TermAllGroupsCollector collector = new TermAllGroupsCollector(groupField);Filter mainQueryFilter = docs.getTopFilter(); // This returns a filter that only matches documents matching with q param and fq params- searcher.search(new FilteredQuery(facetQuery, mainQueryFilter), collector);+ Query filteredFacetQuery = new BooleanQuery.Builder()+ .add(facetQuery, Occur.MUST)+ .add(mainQueryFilter, Occur.FILTER)+ .build();+ searcher.search(filteredFacetQuery, collector);return collector.getGroupCount();}@@ -526,7 +531,7 @@ public class SimpleFacets {if (sf != null && sf.hasDocValues() == false && sf.multiValued() == false && sf.getType().getNumericType() != null) {// it's a single-valued numeric field: we must currently create insanity :(// there isn't a GroupedFacetCollector that works on numerics right now...- searcher.search(new FilteredQuery(new MatchAllDocsQuery(), base.getTopFilter()), new FilterCollector(collector) {+ searcher.search(base.getTopFilter(), new FilterCollector(collector) {@Overridepublic LeafCollector getLeafCollector(LeafReaderContext context) throws IOException {LeafReader insane = Insanity.wrapInsanity(context.reader(), groupField);@@ -534,7 +539,7 @@ public class SimpleFacets {}});} else {- searcher.search(new FilteredQuery(new MatchAllDocsQuery(), base.getTopFilter()), collector);+ searcher.search(base.getTopFilter(), collector);}boolean orderByCount = sort.equals(FacetParams.FACET_SORT_COUNT) || sort.equals(FacetParams.FACET_SORT_COUNT_LEGACY);diff --git a/solr/core/src/java/org/apache/solr/schema/AbstractSpatialFieldType.java b/solr/core/src/java/org/apache/solr/schema/AbstractSpatialFieldType.javaindex be641f7bc3a..60d79740932 100644--- a/solr/core/src/java/org/apache/solr/schema/AbstractSpatialFieldType.java+++ b/solr/core/src/java/org/apache/solr/schema/AbstractSpatialFieldType.java@@ -38,13 +38,15 @@ import com.spatial4j.core.distance.DistanceUtils;import com.spatial4j.core.shape.Point;import com.spatial4j.core.shape.Rectangle;import com.spatial4j.core.shape.Shape;+import org.apache.lucene.document.Field;import org.apache.lucene.document.StoredField;import org.apache.lucene.index.StorableField;import org.apache.lucene.queries.function.FunctionQuery;import org.apache.lucene.queries.function.ValueSource;+import org.apache.lucene.search.BooleanClause.Occur;+import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.Filter;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.Query;import org.apache.lucene.search.SortField;import org.apache.lucene.spatial.SpatialStrategy;@@ -350,7 +352,10 @@ public abstract class AbstractSpatialFieldType<T extends SpatialStrategy> extendreturn functionQuery;Filter filter = strategy.makeFilter(spatialArgs);- return new FilteredQuery(functionQuery, filter);+ return new BooleanQuery.Builder()+ .add(functionQuery, Occur.MUST)+ .add(filter, Occur.FILTER)+ .build();}@Overridediff --git a/solr/core/src/java/org/apache/solr/search/Grouping.java b/solr/core/src/java/org/apache/solr/search/Grouping.javaindex 60dfc22675e..3cce5981107 100644--- a/solr/core/src/java/org/apache/solr/search/Grouping.java+++ b/solr/core/src/java/org/apache/solr/search/Grouping.java@@ -32,10 +32,11 @@ import org.apache.lucene.index.StorableField;import org.apache.lucene.queries.function.FunctionQuery;import org.apache.lucene.queries.function.ValueSource;import org.apache.lucene.queries.function.valuesource.QueryValueSource;+import org.apache.lucene.search.BooleanClause.Occur;+import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.CachingCollector;import org.apache.lucene.search.Collector;import org.apache.lucene.search.Filter;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.MultiCollector;import org.apache.lucene.search.Query;import org.apache.lucene.search.ScoreDoc;@@ -451,7 +452,10 @@ public class Grouping {try {Query q = query;if (luceneFilter != null) {- q = new FilteredQuery(q, luceneFilter);+ q = new BooleanQuery.Builder()+ .add(q, Occur.MUST)+ .add(luceneFilter, Occur.FILTER)+ .build();}searcher.search(q, collector);} catch (TimeLimitingCollector.TimeExceededException | ExitableDirectoryReader.ExitingReaderException x) {diff --git a/solr/core/src/java/org/apache/solr/search/LuceneQueryOptimizer.java b/solr/core/src/java/org/apache/solr/search/LuceneQueryOptimizer.javaindex 858633a675b..92cc97d87c4 100644--- a/solr/core/src/java/org/apache/solr/search/LuceneQueryOptimizer.java+++ b/solr/core/src/java/org/apache/solr/search/LuceneQueryOptimizer.java@@ -22,6 +22,7 @@ package org.apache.solr.search;import org.apache.lucene.search.*;+import org.apache.lucene.search.BooleanClause.Occur;import java.util.LinkedHashMap;import java.util.Map;@@ -110,7 +111,8 @@ if (c.query instanceof TermQuery) {queryOut[0] = query.build(); filterOut[0] = filter;return null;} else {- return searcher.search(new FilteredQuery(query.build(), filter), numHits);+ query.add(filter, Occur.FILTER);+ return searcher.search(query.build(), numHits);}}diff --git a/solr/core/src/java/org/apache/solr/search/SolrIndexSearcher.java b/solr/core/src/java/org/apache/solr/search/SolrIndexSearcher.javaindex 7dbb544ae7b..9e91797fd26 100644--- a/solr/core/src/java/org/apache/solr/search/SolrIndexSearcher.java+++ b/solr/core/src/java/org/apache/solr/search/SolrIndexSearcher.java@@ -63,6 +63,7 @@ import org.apache.lucene.index.TermContext;import org.apache.lucene.index.Terms;import org.apache.lucene.index.TermsEnum;import org.apache.lucene.search.*;+import org.apache.lucene.search.BooleanClause.Occur;import org.apache.lucene.store.Directory;import org.apache.lucene.uninverting.UninvertingReader;import org.apache.lucene.util.Bits;@@ -977,7 +978,11 @@ public class SolrIndexSearcher extends IndexSearcher implements Closeable,SolrIn}if (pf.filter != null) {- search(new FilteredQuery(main, pf.filter), collector);+ Query query = new BooleanQuery.Builder()+ .add(main, Occur.MUST)+ .add(pf.filter, Occur.FILTER)+ .build();+ search(query, collector);} else {search(main, collector);}@@ -1259,12 +1264,14 @@ public class SolrIndexSearcher extends IndexSearcher implements Closeable,SolrInDocSetCollector collector = new DocSetCollector(maxDoc()>>6, maxDoc());try {- if (filter == null) {- super.search(query, collector);- } else {+ if (filter != null) {Filter luceneFilter = filter.getTopFilter();- super.search(new FilteredQuery(query, luceneFilter), collector);+ query = new BooleanQuery.Builder()+ .add(query, Occur.MUST)+ .add(luceneFilter, Occur.FILTER)+ .build();}+ super.search(query, collector);} catch ( ExitableDirectoryReader.ExitingReaderException e) {log.warn("Query: " + query + "; " + e.getMessage());}@@ -1628,7 +1635,10 @@ public class SolrIndexSearcher extends IndexSearcher implements Closeable,SolrInProcessedFilter pf = getProcessedFilter(cmd.getFilter(), cmd.getFilterList());if (pf.filter != null) {- query = new FilteredQuery(query, pf.filter);+ query = new BooleanQuery.Builder()+ .add(query, Occur.MUST)+ .add(pf.filter, Occur.FILTER)+ .build();}// handle zero case...@@ -1726,7 +1736,10 @@ public class SolrIndexSearcher extends IndexSearcher implements Closeable,SolrInProcessedFilter pf = getProcessedFilter(cmd.getFilter(), cmd.getFilterList());Query query = QueryUtils.makeQueryable(cmd.getQuery());if (pf.filter != null) {- query = new FilteredQuery(query, pf.filter);+ query = new BooleanQuery.Builder()+ .add(query, Occur.MUST)+ .add(pf.filter, Occur.FILTER)+ .build();}// handle zero case...diff --git a/solr/core/src/java/org/apache/solr/search/grouping/CommandHandler.java b/solr/core/src/java/org/apache/solr/search/grouping/CommandHandler.javaindex 465f0148554..aaa3a29d2bc 100644--- a/solr/core/src/java/org/apache/solr/search/grouping/CommandHandler.java+++ b/solr/core/src/java/org/apache/solr/search/grouping/CommandHandler.java@@ -24,9 +24,10 @@ import java.util.List;import org.apache.lucene.index.ExitableDirectoryReader;import org.apache.lucene.queries.function.ValueSource;+import org.apache.lucene.search.BooleanClause.Occur;+import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.Collector;import org.apache.lucene.search.Filter;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.MultiCollector;import org.apache.lucene.search.Query;import org.apache.lucene.search.TimeLimitingCollector;@@ -222,7 +223,10 @@ public class CommandHandler {}if (filter.filter != null) {- query = new FilteredQuery(query, filter.filter);+ query = new BooleanQuery.Builder()+ .add(query, Occur.MUST)+ .add(filter.filter, Occur.FILTER)+ .build();}if (filter.postFilter != null) {filter.postFilter.setLastDelegate(collector);diff --git a/solr/core/src/test/org/apache/solr/search/TestSort.java b/solr/core/src/test/org/apache/solr/search/TestSort.javaindex 2763073f29c..41bd79c7906 100644--- a/solr/core/src/test/org/apache/solr/search/TestSort.java+++ b/solr/core/src/test/org/apache/solr/search/TestSort.java@@ -40,7 +40,6 @@ import org.apache.lucene.search.DocIdSet;import org.apache.lucene.search.Filter;import org.apache.lucene.search.FilterCollector;import org.apache.lucene.search.FilterLeafCollector;-import org.apache.lucene.search.FilteredQuery;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.LeafCollector;import org.apache.lucene.search.MatchAllDocsQuery;@@ -296,7 +295,7 @@ public class TestSort extends SolrTestCaseJ4 {};- searcher.search(new FilteredQuery(new MatchAllDocsQuery(), filt), myCollector);+ searcher.search(filt, myCollector);Collections.sort(collectedDocs, new Comparator<MyDoc>() {@Override