Apache Solr open-source search software
SOLR-16496: QueryElevationComponent can now bypass filters (#1154)
Rudi Seitz5606d9b7f7a3
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txtindex 865394e5d0f..04ff3236176 100644--- a/solr/CHANGES.txt+++ b/solr/CHANGES.txt@@ -37,6 +37,8 @@ New Features* SOLR-16500: Added --enable-preview for JDK 19 to enable MemorySegment support in MMapDirectory (Kevin Risden)+* SOLR-16496: QueryElevationComponent now supports fq exclusions (Rudi Seitz via David Smiley)+Improvements---------------------diff --git a/solr/core/src/java/org/apache/solr/handler/component/QueryElevationComponent.java b/solr/core/src/java/org/apache/solr/handler/component/QueryElevationComponent.javaindex 6c74cd49740..6c3ff178efc 100644--- a/solr/core/src/java/org/apache/solr/handler/component/QueryElevationComponent.java+++ b/solr/core/src/java/org/apache/solr/handler/component/QueryElevationComponent.java@@ -49,6 +49,7 @@ import java.util.Queue;import java.util.Set;import java.util.SortedSet;import java.util.function.Consumer;+import org.apache.commons.lang3.StringUtils;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.TokenStream;import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;@@ -61,6 +62,7 @@ import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.BoostQuery;import org.apache.lucene.search.FieldComparator;import org.apache.lucene.search.FieldComparatorSource;+import org.apache.lucene.search.Query;import org.apache.lucene.search.SimpleFieldComparator;import org.apache.lucene.search.Sort;import org.apache.lucene.search.SortField;@@ -76,14 +78,19 @@ import org.apache.solr.common.util.SimpleOrderedMap;import org.apache.solr.common.util.StrUtils;import org.apache.solr.core.SolrCore;import org.apache.solr.core.SolrResourceNotFoundException;+import org.apache.solr.query.FilterQuery;import org.apache.solr.request.SolrQueryRequest;import org.apache.solr.response.transform.ElevatedMarkerFactory;import org.apache.solr.response.transform.ExcludedMarkerFactory;import org.apache.solr.schema.FieldType;import org.apache.solr.schema.SchemaField;+import org.apache.solr.search.CollapsingQParserPlugin;+import org.apache.solr.search.ExtendedQuery;import org.apache.solr.search.QueryParsing;+import org.apache.solr.search.QueryUtils;import org.apache.solr.search.SolrIndexSearcher;import org.apache.solr.search.SortSpec;+import org.apache.solr.search.WrappedQuery;import org.apache.solr.search.grouping.GroupingSpecification;import org.apache.solr.util.RefCounted;import org.apache.solr.util.SafeXMLParsing;@@ -482,6 +489,7 @@ public class QueryElevationComponent extends SearchComponent implements SolrCoreElevation elevation = getElevation(rb);if (elevation != null) {setQuery(rb, elevation);+ setFilters(rb, elevation);setSort(rb, elevation);}@@ -553,6 +561,108 @@ public class QueryElevationComponent extends SearchComponent implements SolrCore}}+ /**+ * Updates any filters that have been tagged for exclusion. Filters can be tagged for exclusion+ * via the syntax fq={!tag=t1}field1:value1&elevate.excludeTags=t1 This method modifies each+ * "excluded" filter so that it becomes a boolean OR of the original filter with an "include+ * query" that matches the elevated documents by their IDs. To be clear, the "excluded" filters+ * are not ignored entirely, but rather broadened so that the elevated documents are allowed+ * through.+ */+ private void setFilters(ResponseBuilder rb, Elevation elevation) {+ SolrParams params = rb.req.getParams();++ String tagStr = params.get(QueryElevationParams.ELEVATE_EXCLUDE_TAGS);+ if (StringUtils.isEmpty(tagStr)) {+ // the parameter that specifies tags for exclusion was not provided or had no value+ return;+ }++ List<String> excludeTags = StrUtils.splitSmart(tagStr, ',');+ excludeTags.removeIf(s -> StringUtils.isBlank(s));+ if (excludeTags.isEmpty()) {+ // the parameter that specifies tags for exclusion was provided but the tag names were blank+ return;+ }++ List<Query> filters = rb.getFilters();+ if (filters == null || filters.isEmpty()) {+ // no filters were provided+ return;+ }++ Set<Query> excludeSet = QueryUtils.getTaggedQueries(rb.req, excludeTags);+ if (excludeSet.isEmpty()) {+ // no filters were tagged+ return;+ }++ List<Query> updatedFilters = new ArrayList<Query>();++ for (Query filter : filters) {++ // filters that weren't tagged for exclusion are left unchanged+ if (!excludeSet.contains(filter)) {+ updatedFilters.add(filter);+ continue;+ }++ // if a collapse filter was tagged for exclusion, throw an Exception; the desired semantics of+ // tagging a collapse filter this way is unclear; furthermore, CollapsingPostFilter is a+ // special case that cannot be included as a clause in a BooleanQuery; its createWeight()+ // method would throw an UnsupportedOperationException when called by the BooleanQuery's own+ // createWeight()+ if (filter instanceof CollapsingQParserPlugin.CollapsingPostFilter) {+ throw new SolrException(+ SolrException.ErrorCode.BAD_REQUEST, "collapse filter cannot be tagged for exclusion");+ }++ // we're looking at a filter that has been tagged for exclusion; first, figure out whether it+ // avoids the cache; if the original filter had the Local Param "cache" and/or "cost", it will+ // be an ExtendedQuery; unless it specifically had cache=false, it's cacheable+ boolean avoidCache =+ (filter instanceof ExtendedQuery) && !((ExtendedQuery) filter).getCache();++ // transform the filter into a boolean OR of the original filter with the "include query"+ // matching the elevated docs+ BooleanQuery.Builder queryBuilder = new BooleanQuery.Builder();+ if (avoidCache || filter instanceof FilterQuery) {+ // if the original filter avoids the cache, we add it to the BooleanQuery as-is; we do the+ // same if the filter is _already_ a FilterQuery -- there's no need to wrap it in another;+ // note that FilterQuery.getCache() returns false, so in this scenario, avoidCache will be+ // true and the instanceof check is not necessary; however, it is left in place for clarity+ // and as a failsafe in case the behavior of FilterQuery.getCache() should ever change+ queryBuilder.add(filter, BooleanClause.Occur.SHOULD);+ } else {+ // the original filter is cacheable and not already a FilterQuery; wrap it in a FilterQuery+ // so that it always consults the filter cache even though it will be represented as a+ // clause within a larger non-caching BooleanQuery+ queryBuilder.add(new FilterQuery(filter), BooleanClause.Occur.SHOULD);+ }+ queryBuilder.add(elevation.includeQuery, BooleanClause.Occur.SHOULD);+ BooleanQuery updatedFilter = queryBuilder.build();++ // we don't want to cache the BooleanQuery that we've built from the original filter and the+ // elevated doc ids; the first clause of the BooleanQuery will be a FilterQuery if the+ // original filter was cacheable, and FilterQueries always consult the cache; the second+ // clause is a set of doc ids that should be fast on its own+ WrappedQuery wrappedUpdatedFilter = new WrappedQuery(updatedFilter);+ wrappedUpdatedFilter.setCache(false);++ // if the original filter is an ExtendedQuery, it may have a user-provided cost; this cost+ // would be ignored for nested queries so we copy it to the outer WrappedQuery; this allows it+ // serve as a tiebreaker for filters that produce the same internal cost in the case where the+ // user-provided cost is >= 100+ if (filter instanceof ExtendedQuery) {+ wrappedUpdatedFilter.setCost(((ExtendedQuery) filter).getCost());+ }++ updatedFilters.add(wrappedUpdatedFilter);+ }++ rb.setFilters(updatedFilters);+ }+private void setSort(ResponseBuilder rb, Elevation elevation) throws IOException {if (elevation.elevatedIds.isEmpty()) {return;diff --git a/solr/core/src/java/org/apache/solr/search/QueryUtils.java b/solr/core/src/java/org/apache/solr/search/QueryUtils.javaindex 0e43d3baac8..d7a16b8446f 100644--- a/solr/core/src/java/org/apache/solr/search/QueryUtils.java+++ b/solr/core/src/java/org/apache/solr/search/QueryUtils.java@@ -19,7 +19,10 @@ package org.apache.solr.search;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;+import java.util.IdentityHashMap;import java.util.List;+import java.util.Map;+import java.util.Set;import org.apache.lucene.search.BooleanClause;import org.apache.lucene.search.BooleanClause.Occur;import org.apache.lucene.search.BooleanQuery;@@ -255,4 +258,49 @@ public class QueryUtils {return Collections.emptyList();}++ /**+ * Returns a Set containing all of the Queries in the designated SolrQueryRequest possessing a tag+ * in the provided list of desired tags. The Set uses reference equality so, for example, it will+ * have 2 elements if the caller requests the tag "t1" for a request where+ * "fq={!tag=t1}a:b&fq={!tag=t1}a:b". The Set will be empty (not null) if there are no+ * matches.+ *+ * <p>This method assumes that the provided SolrQueryRequest's context has been populated with a+ * "tags" entry, which should be a Map from a tag name to a Collection of QParsers. In general,+ * the "tags" entry will not be present until the QParsers have been instantiated, for example via+ * QueryComponent.prepare()+ *+ * @param req Solr request+ * @param desiredTags the tags to look for+ * @return Set of Queries in the given SolrQueryRequest possessing any of the desiredTags+ */+ public static Set<Query> getTaggedQueries(SolrQueryRequest req, Collection<String> desiredTags) {+ Map<?, ?> tagMap = (Map<?, ?>) req.getContext().get("tags");++ if (tagMap == null || tagMap.isEmpty() || desiredTags == null || desiredTags.isEmpty()) {+ return Collections.emptySet();+ }++ Set<Query> taggedQueries = Collections.newSetFromMap(new IdentityHashMap<>());++ for (String tagName : desiredTags) {+ Object tagVal = tagMap.get(tagName);+ if (!(tagVal instanceof Collection)) continue;+ for (Object obj : (Collection<?>) tagVal) {+ if (!(obj instanceof QParser)) continue;+ QParser qParser = (QParser) obj;+ Query query;+ try {+ query = qParser.getQuery();+ } catch (SyntaxError syntaxError) {+ // should not happen since we should only be retrieving a previously parsed query+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, syntaxError);+ }+ taggedQueries.add(query);+ }+ }++ return taggedQueries;+ }}diff --git a/solr/core/src/java/org/apache/solr/search/facet/FacetProcessor.java b/solr/core/src/java/org/apache/solr/search/facet/FacetProcessor.javaindex 1280071eeb8..357e1be356b 100644--- a/solr/core/src/java/org/apache/solr/search/facet/FacetProcessor.java+++ b/solr/core/src/java/org/apache/solr/search/facet/FacetProcessor.java@@ -18,12 +18,11 @@ package org.apache.solr.search.facet;import java.io.IOException;import java.util.ArrayList;-import java.util.Collection;-import java.util.IdentityHashMap;import java.util.Iterator;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;+import java.util.Set;import java.util.function.IntFunction;import org.apache.lucene.index.LeafReaderContext;import org.apache.lucene.search.BooleanClause;@@ -39,6 +38,7 @@ import org.apache.solr.search.BitDocSet;import org.apache.solr.search.DocIterator;import org.apache.solr.search.DocSet;import org.apache.solr.search.QParser;+import org.apache.solr.search.QueryUtils;import org.apache.solr.search.SolrIndexSearcher;import org.apache.solr.search.SyntaxError;import org.apache.solr.search.facet.SlotAcc.SlotContext;@@ -196,29 +196,11 @@ public abstract class FacetProcessor<T extends FacetRequest> {return;}- Map<?, ?> tagMap = (Map<?, ?>) fcontext.req.getContext().get("tags");- if (tagMap == null) {- // no filters were tagged- return;- }+ Set<Query> excludeSet = QueryUtils.getTaggedQueries(fcontext.req, excludeTags);- IdentityHashMap<Query, Boolean> excludeSet = new IdentityHashMap<>();- for (String excludeTag : excludeTags) {- Object olst = tagMap.get(excludeTag);- // tagMap has entries of List<String,List<QParser>>, but subject to change in the future- if (!(olst instanceof Collection)) continue;- for (Object o : (Collection<?>) olst) {- if (!(o instanceof QParser)) continue;- QParser qp = (QParser) o;- try {- excludeSet.put(qp.getQuery(), Boolean.TRUE);- } catch (SyntaxError syntaxError) {- // This should not happen since we should only be retrieving a previously parsed query- throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, syntaxError);- }- }+ if (excludeSet.isEmpty()) {+ return;}- if (excludeSet.size() == 0) return;List<Query> qlist = new ArrayList<>();@@ -226,14 +208,14 @@ public abstract class FacetProcessor<T extends FacetRequest> {ResponseBuilder rb = SolrRequestInfo.getRequestInfo().getResponseBuilder();// add the base query- if (!excludeSet.containsKey(rb.getQuery())) {+ if (!excludeSet.contains(rb.getQuery())) {qlist.add(rb.getQuery());}// add the filtersif (rb.getFilters() != null) {for (Query q : rb.getFilters()) {- if (!excludeSet.containsKey(q)) {+ if (!excludeSet.contains(q)) {qlist.add(q);}}diff --git a/solr/core/src/test/org/apache/solr/handler/component/QueryElevationComponentTest.java b/solr/core/src/test/org/apache/solr/handler/component/QueryElevationComponentTest.javaindex 43d3955519b..f996529c5c4 100644--- a/solr/core/src/test/org/apache/solr/handler/component/QueryElevationComponentTest.java+++ b/solr/core/src/test/org/apache/solr/handler/component/QueryElevationComponentTest.java@@ -28,13 +28,18 @@ import java.io.PrintWriter;import java.lang.invoke.MethodHandles;import java.nio.charset.StandardCharsets;import java.nio.file.Path;+import java.util.ArrayList;import java.util.Arrays;import java.util.Map;import java.util.Set;import java.util.stream.Collectors;import org.apache.lucene.index.IndexReader;+import org.apache.lucene.search.BooleanQuery;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.TermQuery;import org.apache.lucene.util.BytesRef;import org.apache.solr.SolrTestCaseJ4;+import org.apache.solr.common.SolrException;import org.apache.solr.common.params.CommonParams;import org.apache.solr.common.params.CursorMarkParams;import org.apache.solr.common.params.GroupParams;@@ -42,9 +47,12 @@ import org.apache.solr.common.params.QueryElevationParams;import org.apache.solr.common.params.SolrParams;import org.apache.solr.common.util.NamedList;import org.apache.solr.core.SolrCore;+import org.apache.solr.query.FilterQuery;import org.apache.solr.request.SolrQueryRequest;+import org.apache.solr.response.SolrQueryResponse;import org.apache.solr.search.CollapsingQParserPlugin;import org.apache.solr.search.SolrIndexSearcher;+import org.apache.solr.search.WrappedQuery;import org.junit.Before;import org.junit.BeforeClass;import org.junit.Test;@@ -131,6 +139,520 @@ public class QueryElevationComponentTest extends SolrTestCaseJ4 {}}+ /**+ * Tests the behavior of elevation when the fq parameter is present: elevated documents are+ * subject to filters unless specific filters have been tagged for exclusion.+ */+ @Test+ public void testFq() throws Exception {+ try {+ init("schema11.xml");+ clearIndex();+ assertU(commit());+ assertU(adoc("id", "1", "text", "XXXX", "str_s", "a"));+ assertU(adoc("id", "2", "text", "YYYY", "str_s", "b"));+ assertU(adoc("id", "3", "text", "QQQQ", "str_s", "c"));+ assertU(adoc("id", "4", "text", "MMMM", "str_s", "d"));+ assertU(commit());++ // elevated docs 1, 2, and 3 are returned even though our query "ZZZZ" doesn't match them+ assertQ(+ "",+ req(+ CommonParams.Q, "ZZZZ",+ CommonParams.QT, "/elevate",+ CommonParams.FL, "id, score, [elevated]"),+ "//*[@numFound='3']",+ "//result/doc[1]/str[@name='id'][.='1']",+ "//result/doc[2]/str[@name='id'][.='2']",+ "//result/doc[3]/str[@name='id'][.='3']",+ "//result/doc[1]/bool[@name='[elevated]'][.='true']",+ "//result/doc[2]/bool[@name='[elevated]'][.='true']",+ "//result/doc[3]/bool[@name='[elevated]'][.='true']");++ // the elevation component respects the fq parameter; if we add fq=str_s:b the results will+ // exclude docs 1 and 3 even though those docs are elevated+ assertQ(+ "",+ req(+ CommonParams.Q, "ZZZZ",+ CommonParams.QT, "/elevate",+ CommonParams.FL, "id, score, [elevated]",+ CommonParams.FQ, "str_s:b"),+ "//*[@numFound='1']",+ "//result/doc[1]/str[@name='id'][.='2']",+ "//result/doc[1]/bool[@name='[elevated]'][.='true']");++ // if we tag the filter without also specifying the tag for exclusion,+ // we should see the same behavior as above; the filter still takes effect on the elevated+ // docs+ assertQ(+ "",+ req(+ CommonParams.Q, "ZZZZ",+ CommonParams.QT, "/elevate",+ CommonParams.FL, "id, score, [elevated]",+ CommonParams.FQ, "{!tag=test1,test2}str_s:b",+ QueryElevationParams.ELEVATE_EXCLUDE_TAGS, "test3"),+ "//*[@numFound='1']",+ "//result/doc[1]/str[@name='id'][.='2']",+ "//result/doc[1]/bool[@name='[elevated]'][.='true']");++ // if we tag the filter without also specifying the tag for exclusion, we should see the same+ // behavior as above; the filter still takes effect on the elevated docs+ assertQ(+ "",+ req(+ CommonParams.Q, "ZZZZ",+ CommonParams.QT, "/elevate",+ CommonParams.FL, "id, score, [elevated]",+ CommonParams.FQ, "{!tag=test1,test2}str_s:b",+ QueryElevationParams.ELEVATE_EXCLUDE_TAGS, ","),+ "//*[@numFound='1']",+ "//result/doc[1]/str[@name='id'][.='2']",+ "//result/doc[1]/bool[@name='[elevated]'][.='true']");++ // if we specify at least one of the filter's tags for exclusion, the filter is broadened to+ // include the elvated docs; we should see docs 1 and 3 returned even though they don't match+ // the original filter+ assertQ(+ "",+ req(+ CommonParams.Q, "ZZZZ",+ CommonParams.QT, "/elevate",+ CommonParams.FL, "id, score, [elevated]",+ CommonParams.FQ, "{!tag=test1,test2}str_s:b",+ QueryElevationParams.ELEVATE_EXCLUDE_TAGS, "test0,test2,test4"),+ "//*[@numFound='3']",+ "//result/doc[1]/str[@name='id'][.='1']",+ "//result/doc[2]/str[@name='id'][.='2']",+ "//result/doc[3]/str[@name='id'][.='3']",+ "//result/doc[1]/bool[@name='[elevated]'][.='true']",+ "//result/doc[2]/bool[@name='[elevated]'][.='true']",+ "//result/doc[3]/bool[@name='[elevated]'][.='true']");++ // redundant tags don't cause problems; nor does tagging something that's not a filter (in+ // this case, the main query); nor does including empty values in the list of tags to exclude+ assertQ(+ "",+ req(+ CommonParams.Q, "{!tag=test0}ZZZZ",+ CommonParams.QT, "/elevate",+ CommonParams.FL, "id, score, [elevated]",+ CommonParams.FQ, "{!tag=test1,test1,test2,test2}str_s:b",+ QueryElevationParams.ELEVATE_EXCLUDE_TAGS, "test0,test0,test2,test2,test4,test4,,,"),+ "//*[@numFound='3']",+ "//result/doc[1]/str[@name='id'][.='1']",+ "//result/doc[2]/str[@name='id'][.='2']",+ "//result/doc[3]/str[@name='id'][.='3']",+ "//result/doc[1]/bool[@name='[elevated]'][.='true']",+ "//result/doc[2]/bool[@name='[elevated]'][.='true']",+ "//result/doc[3]/bool[@name='[elevated]'][.='true']");++ // we can exclude some filters while leaving others in place+ assertQ(+ "",+ req(+ CommonParams.Q, "ZZZZ",+ CommonParams.QT, "/elevate",+ CommonParams.FL, "id, score, [elevated]",+ CommonParams.FQ, "{!tag=test1}id:10",+ CommonParams.FQ, "{!tag=test2}str_s:b",+ CommonParams.FQ, "{!tag=test3}id:11",+ QueryElevationParams.ELEVATE_EXCLUDE_TAGS, "test1,test3"),+ "//*[@numFound='1']",+ "//result/doc[1]/str[@name='id'][.='2']",+ "//result/doc[1]/bool[@name='[elevated]'][.='true']");++ // when filters are marked as cache=false, tag exclusion works the same as before+ assertQ(+ "",+ req(+ CommonParams.Q, "ZZZZ",+ CommonParams.QT, "/elevate",+ CommonParams.FL, "id, score, [elevated]",+ CommonParams.FQ, "{!tag=test1 cache=false}id:10",+ CommonParams.FQ, "{!tag=test2 cache=false}str_s:b",+ CommonParams.FQ, "{!tag=test3 cache=false}id:11",+ QueryElevationParams.ELEVATE_EXCLUDE_TAGS, "test1,test3"),+ "//*[@numFound='1']",+ "//result/doc[1]/str[@name='id'][.='2']",+ "//result/doc[1]/bool[@name='[elevated]'][.='true']");++ // we can apply the same tag to two different filters+ assertQ(+ "",+ req(+ CommonParams.Q, "ZZZZ",+ CommonParams.QT, "/elevate",+ CommonParams.FL, "id, score, [elevated]",+ CommonParams.FQ, "{!tag=test1}id:10",+ CommonParams.FQ, "{!tag=test2}str_s:b",+ CommonParams.FQ, "{!tag=test1}id:11",+ QueryElevationParams.ELEVATE_EXCLUDE_TAGS, "test1,test3"),+ "//*[@numFound='1']",+ "//result/doc[1]/str[@name='id'][.='2']",+ "//result/doc[1]/bool[@name='[elevated]'][.='true']");++ // we can use filter() syntax inside fq's that are tagged for exclusion+ assertQ(+ "",+ req(+ CommonParams.Q, "ZZZZ",+ CommonParams.QT, "/elevate",+ CommonParams.FL, "id, score, [elevated]",+ CommonParams.FQ, "{!tag=test1}+filter(id:10) +filter(id:11)",+ CommonParams.FQ, "{!tag=test2}filter(str_s:b)",+ QueryElevationParams.ELEVATE_EXCLUDE_TAGS, "test1"),+ "//*[@numFound='1']",+ "//result/doc[1]/str[@name='id'][.='2']",+ "//result/doc[1]/bool[@name='[elevated]'][.='true']");++ // the next few assertions confirm that filter exclusion only applies to elevated documents;+ // if we search for MMMM we should get one match; no documents are elevated for this query+ assertQ(+ "",+ req(+ CommonParams.Q, "MMMM",+ CommonParams.QT, "/elevate",+ CommonParams.FL, "id, score, [elevated]"),+ "//*[@numFound='1']",+ "//result/doc[1]/str[@name='id'][.='4']",+ "//result/doc[1]/bool[@name='[elevated]'][.='false']");++ // if we add fq=str_s:b, our one document that matches MMMM will be filtered out+ assertQ(+ "",+ req(+ CommonParams.Q, "MMMM",+ CommonParams.QT, "/elevate",+ CommonParams.FL, "id, score, [elevated]",+ CommonParams.FQ, "str_s:b"),+ "//*[@numFound='0']");++ // if we tag the filter and exclude it, we should see the same behavior as before; filters are+ // only bypassed for elevated documents; our MMMM document is not elevated so it is still+ // subject to the filter+ assertQ(+ "",+ req(+ CommonParams.Q, "MMMM",+ CommonParams.QT, "/elevate",+ CommonParams.FL, "id, score, [elevated]",+ CommonParams.FQ, "{!tag=test1}str_s:b",+ QueryElevationParams.ELEVATE_EXCLUDE_TAGS, "test1"),+ "//*[@numFound='0']");++ // the next few assertions confirm that collapsing works as expected when filters are+ // excluded; first, confirm that when collapsing, all elevated docs are visible by default+ assertQ(+ "",+ req(+ CommonParams.Q, "ZZZZ",+ CommonParams.QT, "/elevate",+ CommonParams.FL, "id, score, [elevated]",+ CommonParams.FQ, "{!collapse field=str_s sort='score desc'}"),+ "//*[@numFound='3']",+ "//result/doc[1]/str[@name='id'][.='1']",+ "//result/doc[2]/str[@name='id'][.='2']",+ "//result/doc[3]/str[@name='id'][.='3']",+ "//result/doc[1]/bool[@name='[elevated]'][.='true']",+ "//result/doc[2]/bool[@name='[elevated]'][.='true']",+ "//result/doc[3]/bool[@name='[elevated]'][.='true']");++ // when collapsing, an added filter has the expected effect+ assertQ(+ "",+ req(+ CommonParams.Q, "ZZZZ",+ CommonParams.QT, "/elevate",+ CommonParams.FL, "id, score, [elevated]",+ CommonParams.FQ, "{!collapse field=str_s sort='score desc'}",+ CommonParams.FQ, "str_s:b"),+ "//*[@numFound='1']",+ "//result/doc[1]/str[@name='id'][.='2']",+ "//result/doc[1]/bool[@name='[elevated]'][.='true']");++ // when collapsing, filters can still be tagged and excluded so that they don't affect+ // elevated documents+ assertQ(+ "",+ req(+ CommonParams.Q, "ZZZZ",+ CommonParams.QT, "/elevate",+ CommonParams.FL, "id, score, [elevated]",+ CommonParams.FQ, "{!collapse field=str_s sort='score desc'}",+ CommonParams.FQ, "{!tag=test1}str_s:b",+ QueryElevationParams.ELEVATE_EXCLUDE_TAGS, "test1"),+ "//*[@numFound='3']",+ "//result/doc[1]/str[@name='id'][.='1']",+ "//result/doc[2]/str[@name='id'][.='2']",+ "//result/doc[3]/str[@name='id'][.='3']",+ "//result/doc[1]/bool[@name='[elevated]'][.='true']",+ "//result/doc[2]/bool[@name='[elevated]'][.='true']",+ "//result/doc[3]/bool[@name='[elevated]'][.='true']");++ // if a collapse filter itself is tagged for exclusion, this is considered an error and the+ // user should be informed+ assertQEx(+ "tagging a collapse filter for exclusion should lead to a BAD_REQUEST",+ req(+ CommonParams.Q, "ZZZZ",+ CommonParams.QT, "/elevate",+ CommonParams.FL, "id, score, [elevated]",+ CommonParams.FQ, "{!collapse tag=test1 field=str_s sort='score desc'}",+ CommonParams.FQ, "{!tag=test2}str_s:b",+ QueryElevationParams.ELEVATE_EXCLUDE_TAGS, "test1,test2"),+ SolrException.ErrorCode.BAD_REQUEST);++ // if a function range query is provided as a filter, it can be tagged for exclusion;+ // FunctionRangeQuery is special because it implements the PostFilter interface and+ // we want to be sure that while CollapsingPostFilter leads to an error, other PostFilters+ // can still be used; here we set cache=false and cost=200 to trigger the post-filtering+ // behavior+ assertQ(+ "",+ req(+ CommonParams.Q, "ZZZZ",+ CommonParams.QT, "/elevate",+ CommonParams.FL, "id, score, [elevated]",+ CommonParams.FQ, "{!frange tag=test1 l=100 cache=false cost=200}5.0",+ CommonParams.FQ, "{!tag=test2}str_s:b",+ QueryElevationParams.ELEVATE_EXCLUDE_TAGS, "test1,test2"),+ "//*[@numFound='3']",+ "//result/doc[1]/str[@name='id'][.='1']",+ "//result/doc[2]/str[@name='id'][.='2']",+ "//result/doc[3]/str[@name='id'][.='3']",+ "//result/doc[1]/bool[@name='[elevated]'][.='true']",+ "//result/doc[2]/bool[@name='[elevated]'][.='true']",+ "//result/doc[3]/bool[@name='[elevated]'][.='true']");++ } finally {+ delete();+ }+ }++ /**+ * Tests that QueryElevationComponent's prepare() method transforms filters as expected. By+ * default, filters are left unchanged. However, if a filter is tagged for exclusion it is+ * transformed into a BooleanQuery containing the original filter and an "include query" that+ * matches the elevated documents. The original filter will be wrapped in a FilterQuery if the+ * original filter was cacheable and not already a FilterQuery.+ */+ @Test+ public void testFqWithCacheAndCostLocalParams() throws Exception {+ try {+ init("schema11.xml");+ SearchComponent queryComponent =+ h.getCore().getSearchComponent(QueryComponent.COMPONENT_NAME);+ QueryElevationComponent elevationComponent =+ (QueryElevationComponent) h.getCore().getSearchComponent("elevate");++ // first, we establish the baseline behavior that occurs when executing a query that is NOT+ // elevated; when a filter like "str_s:A" has no local params, it will generate a TermQuery;+ // when a filter uses the "cache" and/or "cost" local params, it will generate a WrappedQuery+ // which contains a TermQuery and which has its cache and cost set according to the param+ // values+ try (SolrQueryRequest request =+ req(+ CommonParams.Q, "ZZZZ1",+ CommonParams.QT, "/elevate",+ CommonParams.DF, "text",+ CommonParams.FL, "id, score, [elevated]",+ CommonParams.FQ, "str_s:A",+ CommonParams.FQ, "{!cache=false cost=100}str_s:B",+ CommonParams.FQ, "{!cache=true}str_s:C",+ CommonParams.FQ, "{!tag=test1 cache=false cost=200}str_s:D",+ CommonParams.FQ, "{!tag=test1 cache=true}str_s:E",+ CommonParams.FQ, "{!tag=test1}str_s:F",+ CommonParams.FQ, "{!tag=test1}filter(str_s:G)",+ CommonParams.FQ, "{!tag=test1 cache=true cost=10}filter(str_s:H)",+ QueryElevationParams.ELEVATE_EXCLUDE_TAGS, "test1")) {++ // create a ResponseBuilder with our query and pass it through the prepare() methods of the+ // QueryComponent and the QueryElevationComponent+ ResponseBuilder rb =+ new ResponseBuilder(request, new SolrQueryResponse(), new ArrayList<>());+ queryComponent.prepare(rb);+ elevationComponent.prepare(rb);++ assertNull(elevationComponent.getElevation(rb));++ Query[] filters = rb.getFilters().toArray(new Query[0]);+ assertEquals(8, filters.length);++ // str_s:A+ assertTrue(filters[0] instanceof TermQuery);++ // {!cache=false cost=100}str_s:B+ assertTrue(filters[1] instanceof WrappedQuery);+ assertFalse(((WrappedQuery) filters[1]).getCache());+ assertEquals(100, ((WrappedQuery) filters[1]).getCost());+ assertTrue(((WrappedQuery) filters[1]).getWrappedQuery() instanceof TermQuery);++ // {!cache=true}str_s:C+ assertTrue(filters[2] instanceof WrappedQuery);+ assertTrue(((WrappedQuery) filters[2]).getCache());+ assertTrue(((WrappedQuery) filters[2]).getWrappedQuery() instanceof TermQuery);++ // {!tag=test1 cache=false cost=200}str_s:D+ assertTrue(filters[3] instanceof WrappedQuery);+ assertFalse(((WrappedQuery) filters[3]).getCache());+ assertEquals(200, ((WrappedQuery) filters[3]).getCost());+ assertTrue(((WrappedQuery) filters[3]).getWrappedQuery() instanceof TermQuery);++ // {!tag=test1 cache=true}str_s:E+ assertTrue(filters[4] instanceof WrappedQuery);+ assertTrue(((WrappedQuery) filters[4]).getCache());+ assertTrue(((WrappedQuery) filters[4]).getWrappedQuery() instanceof TermQuery);++ // {!tag=test1}str_s:F+ assertTrue(filters[5] instanceof TermQuery);++ // {!tag=test1}filter(str_s:G)+ assertTrue(filters[6] instanceof FilterQuery);++ // {!tag=test1 cache=false}filter(str_s:H)+ assertTrue(filters[7] instanceof FilterQuery);+ }++ // now establish that when a query IS elevated, non-excluded filters behave the same as shown+ // above; however, excluded filters always generate a non-caching WrappedQuery that contains a+ // BooleanQuery; the first clause of the BooleanQuery will be the original filter, if the+ // original filter had cache=false or was a FilterQuery e.g. defined using filter() syntax; if+ // the original filter was cacheable, the first clause will be FilterQuery containing the+ // original filter; if the original filter _was_ a FilterQuery it is not wrapped in another+ // one+ try (SolrQueryRequest request =+ req(+ CommonParams.Q, "ZZZZ",+ CommonParams.QT, "/elevate",+ CommonParams.DF, "text",+ CommonParams.FL, "id, score, [elevated]",+ CommonParams.FQ, "str_s:A",+ CommonParams.FQ, "{!cache=false cost=100}str_s:B",+ CommonParams.FQ, "{!cache=true}str_s:C",+ CommonParams.FQ, "{!tag=test1 cache=false cost=200}str_s:D",+ CommonParams.FQ, "{!tag=test1 cache=true}str_s:E",+ CommonParams.FQ, "{!tag=test1}str_s:F",+ CommonParams.FQ, "{!tag=test1}filter(str_s:G)",+ CommonParams.FQ, "{!tag=test1 cache=false}filter(str_s:H)",+ QueryElevationParams.ELEVATE_EXCLUDE_TAGS, "test1")) {++ ResponseBuilder rb =+ new ResponseBuilder(request, new SolrQueryResponse(), new ArrayList<>());+ queryComponent.prepare(rb);+ elevationComponent.prepare(rb);++ assertEquals(3, elevationComponent.getElevation(rb).elevatedIds.size());++ Query[] filters = rb.getFilters().toArray(new Query[0]);+ assertEquals(8, filters.length);++ // str_s:A+ assertTrue(filters[0] instanceof TermQuery);++ // {!cache=false cost=100}str_s:B+ assertTrue(filters[1] instanceof WrappedQuery);+ assertFalse(((WrappedQuery) filters[1]).getCache());+ assertEquals(100, ((WrappedQuery) filters[1]).getCost());+ assertTrue(((WrappedQuery) filters[1]).getWrappedQuery() instanceof TermQuery);++ // {!cache=true}str_s:C+ assertTrue(filters[2] instanceof WrappedQuery);+ assertTrue(((WrappedQuery) filters[2]).getCache());+ assertTrue(((WrappedQuery) filters[2]).getWrappedQuery() instanceof TermQuery);++ // {!tag=test1 cache=false cost=200}str_s:D+ {+ // at the outermost level, we have a WrappedQuery that doesn't cache+ assertTrue(filters[3] instanceof WrappedQuery);+ assertFalse(((WrappedQuery) filters[3]).getCache());+ assertEquals(200, ((WrappedQuery) filters[3]).getCost());+ // inside the WrappedQuery, there's a BooleanQuery with two clauses+ BooleanQuery booleanQuery = (BooleanQuery) ((WrappedQuery) filters[3]).getWrappedQuery();+ assertEquals(2, booleanQuery.clauses().size());+ // the first clause is the original query, which is a WrappedQuery because the cache=false+ // local param was provided; the WrappedQuery doesn't cache; it contains a TermQuery+ Query firstClause = booleanQuery.clauses().get(0).getQuery();+ assertTrue(firstClause instanceof WrappedQuery);+ assertFalse(((WrappedQuery) firstClause).getCache());+ assertTrue(((WrappedQuery) firstClause).getWrappedQuery() instanceof TermQuery);+ }++ // {!tag=test1 cache=true}str_s:E+ {+ // at the outermost level, we have a WrappedQuery that doesn't cache+ assertTrue(filters[4] instanceof WrappedQuery);+ assertFalse(((WrappedQuery) filters[4]).getCache());+ // inside the WrappedQuery, there's a BooleanQuery with two clauses+ BooleanQuery booleanQuery = (BooleanQuery) ((WrappedQuery) filters[4]).getWrappedQuery();+ assertEquals(2, booleanQuery.clauses().size());+ // the first clause is a FilterQuery that contains the original query+ // (ElevateComponent introduces this FilterQuery to make sure the original query consults+ // the cache)+ Query firstClause = booleanQuery.clauses().get(0).getQuery();+ assertTrue(firstClause instanceof FilterQuery);+ FilterQuery filterQuery = (FilterQuery) firstClause;+ // the first clause is the original query, which is a WrappedQuery because the cache=false+ // local param was provided; the WrappedQuery is set to cache; it contains a TermQuery+ assertTrue(filterQuery.getQuery() instanceof WrappedQuery);+ assertTrue(((WrappedQuery) filterQuery.getQuery()).getCache());+ assertTrue(+ ((WrappedQuery) filterQuery.getQuery()).getWrappedQuery() instanceof TermQuery);+ }++ // {!tag=test1}str_s:F+ {+ // at the outermost level, we have a WrappedQuery that doesn't cache+ assertTrue(filters[5] instanceof WrappedQuery);+ assertFalse(((WrappedQuery) filters[5]).getCache());+ // inside the WrappedQuery there's a BooleanQuery with two clauses+ BooleanQuery booleanQuery = (BooleanQuery) ((WrappedQuery) filters[5]).getWrappedQuery();+ assertEquals(2, booleanQuery.clauses().size());+ // the first clause is a FilterQuery that contains the original query+ Query firstClause = booleanQuery.clauses().get(0).getQuery();+ assertTrue(firstClause instanceof FilterQuery);+ FilterQuery filterQuery = (FilterQuery) firstClause;+ // the original query is a TermQuery+ assertTrue(filterQuery.getQuery() instanceof TermQuery);+ }++ // {!tag=test1}filter(str_s:G)+ {+ // at the outermost level, we have a WrappedQuery that doesn't cache+ assertTrue(filters[6] instanceof WrappedQuery);+ assertFalse(((WrappedQuery) filters[6]).getCache());+ // inside the WrappedQuery there's a BooleanQuery with two clauses+ BooleanQuery booleanQuery = (BooleanQuery) ((WrappedQuery) filters[6]).getWrappedQuery();+ assertEquals(2, booleanQuery.clauses().size());+ // the first clause is the original query, which is a FilterQuery containing a TermQuery+ Query firstClause = booleanQuery.clauses().get(0).getQuery();+ assertTrue(firstClause instanceof FilterQuery);+ FilterQuery filterQuery = (FilterQuery) firstClause;+ assertTrue(filterQuery.getQuery() instanceof TermQuery);+ }++ // {!tag=test1 cache=false}filter(str_s:H)+ {+ // at the outermost level, we have a WrappedQuery that doesn't cache+ assertTrue(filters[7] instanceof WrappedQuery);+ assertFalse(((WrappedQuery) filters[7]).getCache());+ // inside the WrappedQuery there's a BooleanQuery with two clauses+ BooleanQuery booleanQuery = (BooleanQuery) ((WrappedQuery) filters[7]).getWrappedQuery();+ assertEquals(2, booleanQuery.clauses().size());+ // the first clause is the original query, which is a FilterQuery containing a TermQuery+ Query firstClause = booleanQuery.clauses().get(0).getQuery();+ assertTrue(firstClause instanceof FilterQuery);+ FilterQuery filterQuery = (FilterQuery) firstClause;+ assertTrue(filterQuery.getQuery() instanceof TermQuery);+ }+ }+ } finally {+ delete();+ }+ }+@Testpublic void testGroupedQuery() throws Exception {try {diff --git a/solr/core/src/test/org/apache/solr/search/QueryUtilsTest.java b/solr/core/src/test/org/apache/solr/search/QueryUtilsTest.javanew file mode 100644index 00000000000..24afd4d4ccb--- /dev/null+++ b/solr/core/src/test/org/apache/solr/search/QueryUtilsTest.java@@ -0,0 +1,119 @@+/*+ * 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.solr.search;++import java.util.ArrayList;+import java.util.Set;+import org.apache.lucene.search.Query;+import org.apache.solr.SolrTestCaseJ4;+import org.apache.solr.common.params.CommonParams;+import org.apache.solr.handler.component.QueryComponent;+import org.apache.solr.handler.component.ResponseBuilder;+import org.apache.solr.handler.component.SearchComponent;+import org.apache.solr.request.SolrQueryRequest;+import org.apache.solr.response.SolrQueryResponse;+import org.junit.Test;++/** Tests the utility methods in QueryUtils. */+public class QueryUtilsTest extends SolrTestCaseJ4 {++ @Test+ public void testGetTaggedQueries() throws Exception {+ try {+ initCore("solrconfig.xml", "schema.xml");++ SearchComponent queryComponent =+ h.getCore().getSearchComponent(QueryComponent.COMPONENT_NAME);++ // first make sure QueryUtils.getTaggedQueries() behaves properly on an "empty" request+ try (SolrQueryRequest request = req()) {+ ResponseBuilder rb =+ new ResponseBuilder(request, new SolrQueryResponse(), new ArrayList<>());+ assertEquals(0, QueryUtils.getTaggedQueries(request, Set.of("t0")).size());+ queryComponent.prepare(rb);+ assertEquals(0, QueryUtils.getTaggedQueries(request, Set.of("t0")).size());+ }++ // now test with a request that includes multiple tagged queries+ try (SolrQueryRequest request =+ req(+ CommonParams.Q, "{!tag=t0}text:zzzz",+ CommonParams.FQ, "{!tag=t1,t2}str_s:a",+ CommonParams.FQ, "{!tag=t3}str_s:b",+ CommonParams.FQ, "{!tag=t3}str_s:b",+ CommonParams.FQ, "{!tag=t4}str_s:b",+ CommonParams.FQ, "str_s:b",+ CommonParams.FQ, "str_s:c")) {++ ResponseBuilder rb =+ new ResponseBuilder(request, new SolrQueryResponse(), new ArrayList<>());++ // the "tag map" will not be populated in the SolrQueryRequest's "context" until+ // the QParsers have been initialized; before such time, QueryUtils.getTaggedQueries will+ // always return an empty set+ assertEquals(0, QueryUtils.getTaggedQueries(request, Set.of("t0")).size());++ // initialize QParsers and thereby populate the "tag map"+ queryComponent.prepare(rb);++ // the tag t1000 isn't present in any queries+ assertEquals(0, QueryUtils.getTaggedQueries(request, Set.of("t1000")).size());++ // the main "q" is tagged with t0+ assertEquals(1, QueryUtils.getTaggedQueries(request, Set.of("t0")).size());+ assertEquals(+ "text:zzzz",+ QueryUtils.getTaggedQueries(request, Set.of("t0"))+ .toArray(new Query[] {})[0]+ .toString());++ // the first "fq" is tagged with t1 and t2+ assertEquals(1, QueryUtils.getTaggedQueries(request, Set.of("t1")).size());+ assertEquals(1, QueryUtils.getTaggedQueries(request, Set.of("t2")).size());+ assertEquals(1, QueryUtils.getTaggedQueries(request, Set.of("t1", "t2")).size());+ assertEquals(+ "str_s:a",+ QueryUtils.getTaggedQueries(request, Set.of("t1"))+ .toArray(new Query[] {})[0]+ .toString());++ // here our desired tags span q and fq+ assertEquals(2, QueryUtils.getTaggedQueries(request, Set.of("t0", "t2")).size());++ // there are two fq's tagged with t3 and having the same query "str_s:b"+ // these Queries are equal() but not ==+ // QueryUtils.getTaggedQueries returns a Set that uses reference equality, so it should have+ // 2 elements, not 1+ assertEquals(2, QueryUtils.getTaggedQueries(request, Set.of("t3")).size());+ Query[] queries =+ QueryUtils.getTaggedQueries(request, Set.of("t3")).toArray(new Query[] {});+ assertEquals(queries[0], queries[1]);+ assertNotSame(queries[0], queries[1]);++ assertEquals(1, QueryUtils.getTaggedQueries(request, Set.of("t4")).size());+ assertEquals(3, QueryUtils.getTaggedQueries(request, Set.of("t3", "t4")).size());+ assertEquals(+ 5,+ QueryUtils.getTaggedQueries(+ request, Set.of("t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"))+ .size());+ }+ } finally {+ deleteCore();+ }+ }+}diff --git a/solr/solr-ref-guide/modules/query-guide/pages/query-elevation-component.adoc b/solr/solr-ref-guide/modules/query-guide/pages/query-elevation-component.adocindex 25085e095da..160e5ff7861 100644--- a/solr/solr-ref-guide/modules/query-guide/pages/query-elevation-component.adoc+++ b/solr/solr-ref-guide/modules/query-guide/pages/query-elevation-component.adoc@@ -234,5 +234,17 @@ http://localhost:8983/solr/techproducts/elevate?q=ipod&df=text&elevateIds=IW-02,=== The fq Parameter with Elevation-Query elevation respects the standard filter query (`fq`) parameter.+By default, query elevation respects the standard filter query (`fq`) parameter.That is, if the query contains the `fq` parameter, all results will be within that filter even if `elevate.xml` adds other documents to the result set.++If you want elevated documents to be included in the result set whether or not they match specific filter queries, you can tag those filter queries using xref:local-params.adoc[LocalParams syntax] and then specify the tags for exclusion via the `elevate.excludeTags` request parameter.+Both the `tag` local param and the `elevate.excludeTags` request parameter may specify multiple values by separating them with commas.++[source,text]+q=mainquery&fq=status:public&fq={!tag=dt}doctype:pdf&elevate.excludeTags=dt++[source,text]+q=mainquery&fq=status:public&fq={!tag=t1,t2}a:b&fq={!tag=t3}c:d&fq={!tag=t4}e:f&elevate.excludeTags=t1,t4++When a filter is tagged for exclusion, it is not ignored completely; rather it is modified so that the elevated documents can pass through.+Documents that are not elevated are still subject to the filter.\ No newline at end of filediff --git a/solr/solrj/src/java/org/apache/solr/common/params/QueryElevationParams.java b/solr/solrj/src/java/org/apache/solr/common/params/QueryElevationParams.javaindex f74cbf1ebc6..9cc9c2321fc 100644--- a/solr/solrj/src/java/org/apache/solr/common/params/QueryElevationParams.java+++ b/solr/solrj/src/java/org/apache/solr/common/params/QueryElevationParams.java@@ -59,4 +59,15 @@ public interface QueryElevationParams {* set this to true. False by default.*/String ELEVATE_ONLY_DOCS_MATCHING_QUERY = "elevateOnlyDocsMatchingQuery";++ /**+ * By default, the component respects the fq parameter. If you want to elevate documents that do+ * not match the provided filters, tag the filters in question via the local parameter syntax+ * fq={!tag=t1}field1:value1 and then specify the tags for exclusion via elevate.excludeTag=t1+ *+ * <p>Note: This is the first parameter to use a common prefix naming standard ("elevate.X") so it+ * looks different from the other parameters. The other parameters should eventually be reworked+ * to follow this standard, which is used by other SearchComponents.+ */+ String ELEVATE_EXCLUDE_TAGS = "elevate.excludeTags";}