kotman12 commented on code in PR #16998:
URL: https://github.com/apache/lucene/pull/16998#discussion_r4497754958


##########
lucene/monitor/src/java/org/apache/lucene/monitor/QueryAnalyzer.java:
##########
@@ -65,80 +82,210 @@ private static BiFunction<Query, TermWeightor, QueryTree> 
buildMapper(
   QueryTree buildTree(Query luceneQuery, TermWeightor weightor) {
     QueryBuilder builder = new QueryBuilder();
     luceneQuery.visit(builder);
-    return builder.apply(weightor);
+    return builder.build(weightor);

Review Comment:
   This is a judgement call but I found that defining the QT as a tree of 
`Function`s made static analysis rather challenging. By making the tree 
structure an explicit interface (via the union over `Clause` and `Leaf`) it was 
a lot easier for me to analyze. 



##########
lucene/monitor/src/java/org/apache/lucene/monitor/NegatingTermWeightor.java:
##########
@@ -0,0 +1,36 @@
+/*
+ * 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.monitor;
+
+import java.util.function.DoubleUnaryOperator;
+import org.apache.lucene.index.Term;
+
+/** A TermWeightor with its own weighting of the absence of terms */
+record NegatingTermWeightor(TermWeightor weightor, DoubleUnaryOperator 
negation)

Review Comment:
   Rather than having each weightor possibly get negated I try to force users 
to define at most one negation function. The default `negate` will assume the 
positive weight is a surprisal (inspired by how the doc freq weightor currently 
works) and invert it. 



##########
lucene/monitor/src/java/org/apache/lucene/monitor/MultipassTermFilteredPresearcher.java:
##########
@@ -100,73 +122,60 @@ private static String field(String field, int pass) {
 
   private class MultipassDocumentQueryBuilder implements DocumentQueryBuilder {
 
-    BooleanQuery.Builder[] queries = new BooleanQuery.Builder[passes];
     Map<String, BytesRefHash> terms = new HashMap<>();
-
-    MultipassDocumentQueryBuilder() {
-      for (int i = 0; i < queries.length; i++) {
-        queries[i] = new BooleanQuery.Builder();
-      }
-    }
+    Map<String, List<BytesRef>> negatableTerms = new HashMap<>();

Review Comment:
   It's a `List<BytesRef>` instead of a `BytesRefHash` (as in the case of 
`terms`) because we don't need to deduplicate.



##########
lucene/monitor/src/java/org/apache/lucene/monitor/QueryAnalyzer.java:
##########
@@ -65,80 +82,210 @@ private static BiFunction<Query, TermWeightor, QueryTree> 
buildMapper(
   QueryTree buildTree(Query luceneQuery, TermWeightor weightor) {
     QueryBuilder builder = new QueryBuilder();
     luceneQuery.visit(builder);
-    return builder.apply(weightor);
+    return builder.build(weightor);
   }
 
-  private class QueryBuilder extends QueryVisitor implements 
Function<TermWeightor, QueryTree> {
+  /** A clause of a {@link QueryBuilder}: a leaf of the tree, or a nested 
builder */
+  private sealed interface Clause permits Leaf, QueryBuilder {}
+
+  /** A leaf, built once the weightor is known */
+  private record Leaf(Function<TermWeightor, QueryTree> tree) implements 
Clause {}
+
+  /** Builds the tree for a group of clauses; under negation its operator 
flips (De Morgan) */
+  private final class QueryBuilder extends QueryVisitor implements Clause {
+
+    /** Whether the query this builder visits is negated */
+    final boolean isNegated;
+
+    /**
+     * Whether this builds a disjunction: clauses combined with OR, or, by De 
Morgan, with AND under
+     * negation
+     */
+    final boolean buildsDisjunction;
+
+    final List<Clause> clauses = new ArrayList<>();
+    final Set<Term> negatedTerms = new LinkedHashSet<>();
+
+    /** The root builder: positive */
+    QueryBuilder() {
+      this(false, false);
+    }
+
+    private QueryBuilder(boolean isNegated, boolean combinesWithOr) {
+      this.isNegated = isNegated;
+      this.buildsDisjunction = combinesWithOr ^ isNegated;
+    }
+
+    /** A child for clauses combined with AND, in this builder's polarity */
+    private QueryBuilder conjunction() {
+      return addChild(new QueryBuilder(isNegated, false));
+    }
+
+    /** A child for clauses combined with OR, in this builder's polarity */
+    private QueryBuilder disjunction() {
+      return addChild(new QueryBuilder(isNegated, true));
+    }
 
-    final List<Function<TermWeightor, QueryTree>> children = new ArrayList<>();
+    /** A child for negated clauses: NOT a AND NOT b = NOT (a OR b), so OR 
with flipped polarity */
+    private QueryBuilder negation() {
+      return addChild(new QueryBuilder(!isNegated, true));
+    }
+
+    private QueryBuilder addChild(QueryBuilder child) {
+      clauses.add(child);
+      return child;
+    }
 
     @Override
     public QueryVisitor getSubVisitor(BooleanClause.Occur occur, Query parent) 
{
+      if (isNegated && !isExactUnderNegation(parent, occur)) {
+        clauses.add(new Leaf(_ -> QueryTree.anyTerm("NOT " + parent)));
+        return QueryVisitor.EMPTY_VISITOR;
+      }
       if (occur == BooleanClause.Occur.MUST || occur == 
BooleanClause.Occur.FILTER) {
-        QueryBuilder n = new QueryBuilder();
-        children.add(n);
-        return n;
+        return conjunction();
       }
       if (occur == BooleanClause.Occur.MUST_NOT) {
-        // Check if we're in a pure negative disjunction
-        if (parent instanceof BooleanQuery bq) {
-          long positiveCount =
-              bq.clauses().stream().filter(c -> c.occur() != 
BooleanClause.Occur.MUST_NOT).count();
-          if (positiveCount == 0) {
-            children.add(_ -> QueryTree.anyTerm("PURE NEGATIVE QUERY[" + 
parent + "]"));
-          }
+        // Lucene matches nothing for a pure negative query such as (-b). 
Negated, it matches every
+        // document, which its clauses can't express (NOT (-b) is not b), so 
select the query for
+        // every document. Positive, it is treated as *:* -b, which selects 
more documents than it
+        // matches. Without negative disjuncts, it always selects the query 
for every document.
+        if (parent instanceof BooleanQuery bq
+            && isPureNegative(bq)
+            && (!isNegationOptimized || isNegated)) {
+          clauses.add(new Leaf(_ -> QueryTree.anyTerm("PURE NEGATIVE QUERY[" + 
parent + "]")));
+          return QueryVisitor.EMPTY_VISITOR;
         }
-        return QueryVisitor.EMPTY_VISITOR;
+        if (!isNegationOptimized) {
+          return QueryVisitor.EMPTY_VISITOR;
+        }
+        return negation();
       }
       // It's a disjunction clause.  If the parent has MUST or FILTER clauses, 
we can
       // ignore it
-      if (parent instanceof BooleanQuery bq) {
-        long requiredCount =
-            bq.clauses().stream()
-                .filter(
-                    c ->
-                        c.occur() == BooleanClause.Occur.MUST
-                            || c.occur() == BooleanClause.Occur.FILTER)
-                .count();
-        if (requiredCount > 0) {
-          return QueryVisitor.EMPTY_VISITOR;
-        }
+      if (parent instanceof BooleanQuery bq && hasRequiredClauses(bq)) {
+        return QueryVisitor.EMPTY_VISITOR;
       }
-      Disjunction n = new Disjunction();
-      children.add(n);
-      return n;
+      return disjunction();
     }
 
     @Override
     public void consumeTerms(Query query, Term... terms) {
+      if (isNegated) {
+        // a doc values query doesn't match on indexed terms, so they must not 
exclude it
+        if (query instanceof TermQuery
+            || query instanceof SynonymQuery
+            || (query instanceof TermInSetQuery tisq
+                && tisq.getRewriteMethod() != 
MultiTermQuery.DOC_VALUES_REWRITE)
+            || query instanceof PhraseQuery) {
+          negatedTerms.addAll(Arrays.asList(terms));
+        } else {
+          clauses.add(new Leaf(_ -> QueryTree.anyTerm("NOT " + query)));
+        }
+        return;
+      }
       for (Term term : terms) {
-        children.add(w -> QueryTree.term(term, w));
+        clauses.add(new Leaf(w -> QueryTree.term(term, w)));
       }
     }
 
     @Override
     public void visitLeaf(Query query) {
-      children.add(
-          w -> {
-            QueryTree q = unknownQueryMapper.apply(query, w);
-            if (q == null) {
-              return QueryTree.anyTerm(query.toString());
-            }
-            return q;
-          });
+      // Under negation only handleNegatedQuery is used: a handler's positive 
tree may select more
+      // documents than the query matches, so negating it would be unsound
+      clauses.add(
+          new Leaf(
+              w -> {
+                QueryTree q = handleCustomQuery(query, w, isNegated);
+                if (q == null) {
+                  return QueryTree.anyTerm(isNegated ? "NOT " + query : 
query.toString());
+                }
+                return q;
+              }));
     }
 
-    @Override
-    public QueryTree apply(TermWeightor termWeightor) {
-      return QueryTree.conjunction(children, termWeightor);
+    /** Whether this combines its clauses with AND; a single clause counts as 
either */
+    private boolean isConjunctive() {
+      return !buildsDisjunction || clauses.size() + negatedTerms.size() == 1;

Review Comment:
   The `clauses.size() + negatedTerms.size() == 1` is added because standalone 
negative clauses are classified as disjunctions in the `QueryTree` but really 
they can be thought of as either for the purposes of conjuction merging. To 
give a concrete example, without this provision `*:* -(a OR (b OR c))` which is 
equivalent to `*:* -a AND -b AND -c` would not be put in the same negative 
disjunct even though conceptually it should.



##########
lucene/monitor/src/java/org/apache/lucene/monitor/QueryAnalyzer.java:
##########
@@ -65,80 +82,210 @@ private static BiFunction<Query, TermWeightor, QueryTree> 
buildMapper(
   QueryTree buildTree(Query luceneQuery, TermWeightor weightor) {
     QueryBuilder builder = new QueryBuilder();
     luceneQuery.visit(builder);
-    return builder.apply(weightor);
+    return builder.build(weightor);
   }
 
-  private class QueryBuilder extends QueryVisitor implements 
Function<TermWeightor, QueryTree> {
+  /** A clause of a {@link QueryBuilder}: a leaf of the tree, or a nested 
builder */
+  private sealed interface Clause permits Leaf, QueryBuilder {}
+
+  /** A leaf, built once the weightor is known */
+  private record Leaf(Function<TermWeightor, QueryTree> tree) implements 
Clause {}
+
+  /** Builds the tree for a group of clauses; under negation its operator 
flips (De Morgan) */
+  private final class QueryBuilder extends QueryVisitor implements Clause {
+
+    /** Whether the query this builder visits is negated */
+    final boolean isNegated;
+
+    /**
+     * Whether this builds a disjunction: clauses combined with OR, or, by De 
Morgan, with AND under
+     * negation
+     */
+    final boolean buildsDisjunction;
+
+    final List<Clause> clauses = new ArrayList<>();
+    final Set<Term> negatedTerms = new LinkedHashSet<>();
+
+    /** The root builder: positive */
+    QueryBuilder() {
+      this(false, false);
+    }
+
+    private QueryBuilder(boolean isNegated, boolean combinesWithOr) {
+      this.isNegated = isNegated;
+      this.buildsDisjunction = combinesWithOr ^ isNegated;
+    }
+
+    /** A child for clauses combined with AND, in this builder's polarity */
+    private QueryBuilder conjunction() {
+      return addChild(new QueryBuilder(isNegated, false));
+    }
+
+    /** A child for clauses combined with OR, in this builder's polarity */
+    private QueryBuilder disjunction() {
+      return addChild(new QueryBuilder(isNegated, true));
+    }
 
-    final List<Function<TermWeightor, QueryTree>> children = new ArrayList<>();
+    /** A child for negated clauses: NOT a AND NOT b = NOT (a OR b), so OR 
with flipped polarity */
+    private QueryBuilder negation() {
+      return addChild(new QueryBuilder(!isNegated, true));
+    }
+
+    private QueryBuilder addChild(QueryBuilder child) {
+      clauses.add(child);
+      return child;
+    }
 
     @Override
     public QueryVisitor getSubVisitor(BooleanClause.Occur occur, Query parent) 
{
+      if (isNegated && !isExactUnderNegation(parent, occur)) {
+        clauses.add(new Leaf(_ -> QueryTree.anyTerm("NOT " + parent)));
+        return QueryVisitor.EMPTY_VISITOR;
+      }
       if (occur == BooleanClause.Occur.MUST || occur == 
BooleanClause.Occur.FILTER) {
-        QueryBuilder n = new QueryBuilder();
-        children.add(n);
-        return n;
+        return conjunction();
       }
       if (occur == BooleanClause.Occur.MUST_NOT) {
-        // Check if we're in a pure negative disjunction
-        if (parent instanceof BooleanQuery bq) {
-          long positiveCount =
-              bq.clauses().stream().filter(c -> c.occur() != 
BooleanClause.Occur.MUST_NOT).count();
-          if (positiveCount == 0) {
-            children.add(_ -> QueryTree.anyTerm("PURE NEGATIVE QUERY[" + 
parent + "]"));
-          }
+        // Lucene matches nothing for a pure negative query such as (-b). 
Negated, it matches every
+        // document, which its clauses can't express (NOT (-b) is not b), so 
select the query for
+        // every document. Positive, it is treated as *:* -b, which selects 
more documents than it
+        // matches. Without negative disjuncts, it always selects the query 
for every document.
+        if (parent instanceof BooleanQuery bq
+            && isPureNegative(bq)
+            && (!isNegationOptimized || isNegated)) {
+          clauses.add(new Leaf(_ -> QueryTree.anyTerm("PURE NEGATIVE QUERY[" + 
parent + "]")));
+          return QueryVisitor.EMPTY_VISITOR;
         }
-        return QueryVisitor.EMPTY_VISITOR;
+        if (!isNegationOptimized) {
+          return QueryVisitor.EMPTY_VISITOR;
+        }
+        return negation();
       }
       // It's a disjunction clause.  If the parent has MUST or FILTER clauses, 
we can
       // ignore it
-      if (parent instanceof BooleanQuery bq) {
-        long requiredCount =
-            bq.clauses().stream()
-                .filter(
-                    c ->
-                        c.occur() == BooleanClause.Occur.MUST
-                            || c.occur() == BooleanClause.Occur.FILTER)
-                .count();
-        if (requiredCount > 0) {
-          return QueryVisitor.EMPTY_VISITOR;
-        }
+      if (parent instanceof BooleanQuery bq && hasRequiredClauses(bq)) {
+        return QueryVisitor.EMPTY_VISITOR;
       }
-      Disjunction n = new Disjunction();
-      children.add(n);
-      return n;
+      return disjunction();
     }
 
     @Override
     public void consumeTerms(Query query, Term... terms) {
+      if (isNegated) {
+        // a doc values query doesn't match on indexed terms, so they must not 
exclude it
+        if (query instanceof TermQuery
+            || query instanceof SynonymQuery
+            || (query instanceof TermInSetQuery tisq
+                && tisq.getRewriteMethod() != 
MultiTermQuery.DOC_VALUES_REWRITE)

Review Comment:
   Adversarial review caught this one. It also flagged that there may be some 
pre-existing issues when doc value term doesn't match the indexed term. But 
this maybe more of a theoretical concern.



##########
lucene/monitor/src/java/org/apache/lucene/monitor/TermFilteredPresearcher.java:
##########
@@ -254,18 +383,99 @@ public final Document indexQuery(Query query, Map<String, 
String> metadata) {
 
   /** Builds a {@link Document} from the terms extracted from a query */
   protected Document buildQueryDocument(QueryTree querytree) {
-    Map<String, BytesRefHash> fieldTerms = collectTerms(querytree);
+    return toDocument(querytree, field -> field);
+  }
+
+  /** Indexes the terms and negative disjuncts of the current path through a 
{@link QueryTree} */
+  Document toDocument(QueryTree querytree, FieldMapper fields) {
     Document doc = new Document();
-    for (Map.Entry<String, BytesRefHash> entry : fieldTerms.entrySet()) {
-      doc.add(
-          new Field(
-              entry.getKey(),
-              new TermsEnumTokenStream(new 
BytesRefHashIterator(entry.getValue())),
-              QUERYFIELDTYPE));
+    CollectedTerms collected = collectTermsAndNegativeDisjuncts(querytree);
+    List<Set<Term>> negativeDisjuncts = collected.negativeDisjuncts();
+    if (negativeDisjuncts.size() > maxNegativeDisjuncts) {
+      // More negative disjuncts than the document side checks: the marker 
alone satisfies the path
+      // for
+      // every document, so its terms are not needed either
+      addField(doc, negativeDisjunctMarkerField(fields, 0), 
NEGATIVE_DISJUNCT_MARKER);
+      return doc;
+    }
+    for (Map.Entry<String, BytesRefHash> entry : collected.terms().entrySet()) 
{
+      if (maxNegativeDisjuncts > 0 && entry.getKey().contains(NOT_SUFFIX)) {
+        // The field could be indexed under the name of a negative disjunct 
field, whose clauses
+        // exclude
+        // queries, so select the query for every document instead
+        addField(doc, ANYTOKEN_FIELD, new BytesRef(ANYTOKEN));
+        continue;
+      }
+      String field = fields.map(entry.getKey());
+      addField(doc, field, entry.getValue());
+      if (!field.equals(entry.getKey())) {
+        // the term filter looks terms up under the document's field names, so 
a renamed field is
+        // also indexed under its own name
+        addField(doc, entry.getKey(), entry.getValue());
+      }
+    }
+    for (int i = 0; i < negativeDisjuncts.size(); i++) {
+      Map<String, BytesRefHash> byField = new HashMap<>();
+      for (Term term : negativeDisjuncts.get(i)) {
+        byField.computeIfAbsent(term.field(), _ -> new 
BytesRefHash()).add(term.bytes());
+      }
+      for (Map.Entry<String, BytesRefHash> entry : byField.entrySet()) {
+        addRawTerms(doc, negativeDisjunctField(fields.map(entry.getKey()), i), 
entry.getValue());
+        addRawTerms(doc, entry.getKey() + NOT_SUFFIX, entry.getValue());
+      }
+      addField(doc, negativeDisjunctMarkerField(fields, i), 
NEGATIVE_DISJUNCT_MARKER);
     }
     return doc;
   }
 
+  private void addField(Document doc, String field, BytesRef term) {
+    BytesRefHash terms = new BytesRefHash();
+    terms.add(term);
+    addField(doc, field, terms);
+  }
+
+  private void addField(Document doc, String field, BytesRefHash terms) {
+    doc.add(
+        new Field(
+            field, new TermsEnumTokenStream(new BytesRefHashIterator(terms)), 
QUERYFIELDTYPE));
+  }
+
+  /**
+   * Indexes exact bytes: TermsEnumTokenStream can merge invalid UTF-8 terms, 
which must not exclude
+   */
+  private static void addRawTerms(Document doc, String field, BytesRefHash 
terms) {
+    BytesRef scratch = new BytesRef();
+    for (int i = 0; i < terms.size(); i++) {

Review Comment:
   Adversarial review caught that folding non-UTF bytes into characters (which 
is possible with binary query terms) can lead to false negatives when negations 
are disabled. Say you fold two bytes to some character which you them index ... 
when a document comes in with a matching character (but not matching bytes) it 
will be a false-positive match by the presearcher but the CandidateMatcher will 
filter it out so it is still correct. In the case of negative queries the same 
principle flips and you get a false negative. So you must faithfully index the 
bytes so that the document doesn't get incorrectly filtered out if it matches 
the folded character (but doesn't match the actual bytes in the query term). 
   
   I tried to see if we could just go full-binary when indexing positive and 
negative terms but it appears a lot of the existing machinery around regex 
handling (i.e. suffixing n-grams) relies on string encoded terms so I've left 
it on a separate path for negative query terms. 



##########
lucene/monitor/src/java/org/apache/lucene/monitor/QueryAnalyzer.java:
##########
@@ -65,80 +82,210 @@ private static BiFunction<Query, TermWeightor, QueryTree> 
buildMapper(
   QueryTree buildTree(Query luceneQuery, TermWeightor weightor) {
     QueryBuilder builder = new QueryBuilder();
     luceneQuery.visit(builder);
-    return builder.apply(weightor);
+    return builder.build(weightor);
   }
 
-  private class QueryBuilder extends QueryVisitor implements 
Function<TermWeightor, QueryTree> {
+  /** A clause of a {@link QueryBuilder}: a leaf of the tree, or a nested 
builder */
+  private sealed interface Clause permits Leaf, QueryBuilder {}
+
+  /** A leaf, built once the weightor is known */
+  private record Leaf(Function<TermWeightor, QueryTree> tree) implements 
Clause {}
+
+  /** Builds the tree for a group of clauses; under negation its operator 
flips (De Morgan) */
+  private final class QueryBuilder extends QueryVisitor implements Clause {
+
+    /** Whether the query this builder visits is negated */
+    final boolean isNegated;
+
+    /**
+     * Whether this builds a disjunction: clauses combined with OR, or, by De 
Morgan, with AND under
+     * negation
+     */
+    final boolean buildsDisjunction;
+
+    final List<Clause> clauses = new ArrayList<>();
+    final Set<Term> negatedTerms = new LinkedHashSet<>();
+
+    /** The root builder: positive */
+    QueryBuilder() {
+      this(false, false);
+    }
+
+    private QueryBuilder(boolean isNegated, boolean combinesWithOr) {
+      this.isNegated = isNegated;
+      this.buildsDisjunction = combinesWithOr ^ isNegated;
+    }
+
+    /** A child for clauses combined with AND, in this builder's polarity */
+    private QueryBuilder conjunction() {
+      return addChild(new QueryBuilder(isNegated, false));
+    }
+
+    /** A child for clauses combined with OR, in this builder's polarity */
+    private QueryBuilder disjunction() {
+      return addChild(new QueryBuilder(isNegated, true));
+    }
 
-    final List<Function<TermWeightor, QueryTree>> children = new ArrayList<>();
+    /** A child for negated clauses: NOT a AND NOT b = NOT (a OR b), so OR 
with flipped polarity */
+    private QueryBuilder negation() {
+      return addChild(new QueryBuilder(!isNegated, true));
+    }
+
+    private QueryBuilder addChild(QueryBuilder child) {
+      clauses.add(child);
+      return child;
+    }
 
     @Override
     public QueryVisitor getSubVisitor(BooleanClause.Occur occur, Query parent) 
{
+      if (isNegated && !isExactUnderNegation(parent, occur)) {
+        clauses.add(new Leaf(_ -> QueryTree.anyTerm("NOT " + parent)));
+        return QueryVisitor.EMPTY_VISITOR;
+      }
       if (occur == BooleanClause.Occur.MUST || occur == 
BooleanClause.Occur.FILTER) {
-        QueryBuilder n = new QueryBuilder();
-        children.add(n);
-        return n;
+        return conjunction();
       }
       if (occur == BooleanClause.Occur.MUST_NOT) {
-        // Check if we're in a pure negative disjunction
-        if (parent instanceof BooleanQuery bq) {
-          long positiveCount =
-              bq.clauses().stream().filter(c -> c.occur() != 
BooleanClause.Occur.MUST_NOT).count();
-          if (positiveCount == 0) {
-            children.add(_ -> QueryTree.anyTerm("PURE NEGATIVE QUERY[" + 
parent + "]"));
-          }
+        // Lucene matches nothing for a pure negative query such as (-b). 
Negated, it matches every
+        // document, which its clauses can't express (NOT (-b) is not b), so 
select the query for
+        // every document. Positive, it is treated as *:* -b, which selects 
more documents than it
+        // matches. Without negative disjuncts, it always selects the query 
for every document.
+        if (parent instanceof BooleanQuery bq
+            && isPureNegative(bq)
+            && (!isNegationOptimized || isNegated)) {
+          clauses.add(new Leaf(_ -> QueryTree.anyTerm("PURE NEGATIVE QUERY[" + 
parent + "]")));

Review Comment:
   This is a nasty little wart. De Morgan's law doesn't apply to pure negative 
queries so we have to handle it explicitly:
   
   `-(-b) = -(null) = *:* != b`



##########
lucene/monitor/src/java/org/apache/lucene/monitor/QueryAnalyzer.java:
##########
@@ -65,80 +82,210 @@ private static BiFunction<Query, TermWeightor, QueryTree> 
buildMapper(
   QueryTree buildTree(Query luceneQuery, TermWeightor weightor) {
     QueryBuilder builder = new QueryBuilder();
     luceneQuery.visit(builder);
-    return builder.apply(weightor);
+    return builder.build(weightor);
   }
 
-  private class QueryBuilder extends QueryVisitor implements 
Function<TermWeightor, QueryTree> {
+  /** A clause of a {@link QueryBuilder}: a leaf of the tree, or a nested 
builder */
+  private sealed interface Clause permits Leaf, QueryBuilder {}
+
+  /** A leaf, built once the weightor is known */
+  private record Leaf(Function<TermWeightor, QueryTree> tree) implements 
Clause {}
+
+  /** Builds the tree for a group of clauses; under negation its operator 
flips (De Morgan) */
+  private final class QueryBuilder extends QueryVisitor implements Clause {
+
+    /** Whether the query this builder visits is negated */
+    final boolean isNegated;
+
+    /**
+     * Whether this builds a disjunction: clauses combined with OR, or, by De 
Morgan, with AND under
+     * negation
+     */
+    final boolean buildsDisjunction;
+
+    final List<Clause> clauses = new ArrayList<>();
+    final Set<Term> negatedTerms = new LinkedHashSet<>();
+
+    /** The root builder: positive */
+    QueryBuilder() {
+      this(false, false);
+    }
+
+    private QueryBuilder(boolean isNegated, boolean combinesWithOr) {
+      this.isNegated = isNegated;
+      this.buildsDisjunction = combinesWithOr ^ isNegated;
+    }
+
+    /** A child for clauses combined with AND, in this builder's polarity */
+    private QueryBuilder conjunction() {
+      return addChild(new QueryBuilder(isNegated, false));
+    }
+
+    /** A child for clauses combined with OR, in this builder's polarity */
+    private QueryBuilder disjunction() {
+      return addChild(new QueryBuilder(isNegated, true));
+    }
 
-    final List<Function<TermWeightor, QueryTree>> children = new ArrayList<>();
+    /** A child for negated clauses: NOT a AND NOT b = NOT (a OR b), so OR 
with flipped polarity */
+    private QueryBuilder negation() {
+      return addChild(new QueryBuilder(!isNegated, true));
+    }
+
+    private QueryBuilder addChild(QueryBuilder child) {
+      clauses.add(child);
+      return child;
+    }
 
     @Override
     public QueryVisitor getSubVisitor(BooleanClause.Occur occur, Query parent) 
{
+      if (isNegated && !isExactUnderNegation(parent, occur)) {
+        clauses.add(new Leaf(_ -> QueryTree.anyTerm("NOT " + parent)));
+        return QueryVisitor.EMPTY_VISITOR;
+      }
       if (occur == BooleanClause.Occur.MUST || occur == 
BooleanClause.Occur.FILTER) {
-        QueryBuilder n = new QueryBuilder();
-        children.add(n);
-        return n;
+        return conjunction();
       }
       if (occur == BooleanClause.Occur.MUST_NOT) {
-        // Check if we're in a pure negative disjunction
-        if (parent instanceof BooleanQuery bq) {
-          long positiveCount =
-              bq.clauses().stream().filter(c -> c.occur() != 
BooleanClause.Occur.MUST_NOT).count();
-          if (positiveCount == 0) {
-            children.add(_ -> QueryTree.anyTerm("PURE NEGATIVE QUERY[" + 
parent + "]"));
-          }
+        // Lucene matches nothing for a pure negative query such as (-b). 
Negated, it matches every
+        // document, which its clauses can't express (NOT (-b) is not b), so 
select the query for
+        // every document. Positive, it is treated as *:* -b, which selects 
more documents than it
+        // matches. Without negative disjuncts, it always selects the query 
for every document.
+        if (parent instanceof BooleanQuery bq
+            && isPureNegative(bq)
+            && (!isNegationOptimized || isNegated)) {
+          clauses.add(new Leaf(_ -> QueryTree.anyTerm("PURE NEGATIVE QUERY[" + 
parent + "]")));
+          return QueryVisitor.EMPTY_VISITOR;
         }
-        return QueryVisitor.EMPTY_VISITOR;
+        if (!isNegationOptimized) {
+          return QueryVisitor.EMPTY_VISITOR;
+        }
+        return negation();
       }
       // It's a disjunction clause.  If the parent has MUST or FILTER clauses, 
we can
       // ignore it
-      if (parent instanceof BooleanQuery bq) {
-        long requiredCount =
-            bq.clauses().stream()
-                .filter(
-                    c ->
-                        c.occur() == BooleanClause.Occur.MUST
-                            || c.occur() == BooleanClause.Occur.FILTER)
-                .count();
-        if (requiredCount > 0) {
-          return QueryVisitor.EMPTY_VISITOR;
-        }
+      if (parent instanceof BooleanQuery bq && hasRequiredClauses(bq)) {
+        return QueryVisitor.EMPTY_VISITOR;
       }
-      Disjunction n = new Disjunction();
-      children.add(n);
-      return n;
+      return disjunction();
     }
 
     @Override
     public void consumeTerms(Query query, Term... terms) {
+      if (isNegated) {
+        // a doc values query doesn't match on indexed terms, so they must not 
exclude it
+        if (query instanceof TermQuery
+            || query instanceof SynonymQuery
+            || (query instanceof TermInSetQuery tisq
+                && tisq.getRewriteMethod() != 
MultiTermQuery.DOC_VALUES_REWRITE)
+            || query instanceof PhraseQuery) {
+          negatedTerms.addAll(Arrays.asList(terms));
+        } else {
+          clauses.add(new Leaf(_ -> QueryTree.anyTerm("NOT " + query)));
+        }
+        return;
+      }
       for (Term term : terms) {
-        children.add(w -> QueryTree.term(term, w));
+        clauses.add(new Leaf(w -> QueryTree.term(term, w)));
       }
     }
 
     @Override
     public void visitLeaf(Query query) {
-      children.add(
-          w -> {
-            QueryTree q = unknownQueryMapper.apply(query, w);
-            if (q == null) {
-              return QueryTree.anyTerm(query.toString());
-            }
-            return q;
-          });
+      // Under negation only handleNegatedQuery is used: a handler's positive 
tree may select more
+      // documents than the query matches, so negating it would be unsound
+      clauses.add(
+          new Leaf(
+              w -> {
+                QueryTree q = handleCustomQuery(query, w, isNegated);
+                if (q == null) {
+                  return QueryTree.anyTerm(isNegated ? "NOT " + query : 
query.toString());
+                }
+                return q;
+              }));
     }
 
-    @Override
-    public QueryTree apply(TermWeightor termWeightor) {
-      return QueryTree.conjunction(children, termWeightor);
+    /** Whether this combines its clauses with AND; a single clause counts as 
either */
+    private boolean isConjunctive() {
+      return !buildsDisjunction || clauses.size() + negatedTerms.size() == 1;
     }
-  }
 
-  private class Disjunction extends QueryBuilder {
+    /**
+     * Moves the negated terms of the conjunctions nested in this one into 
{@code into}, and removes
+     * the builders left empty: (a AND NOT x) AND NOT y = a AND NOT (x OR y), 
one negative disjunct
+     */
+    private void mergeNestedNegatedConjuncts(QueryBuilder into) {

Review Comment:
   Conjuncted negative terms should share the same disjunct to save on 
"disjunct" budget. It's much easier to collapse this once all the 
`QueryBuilder`s have been populated instead of doing this ahead of time because 
you would have to pass mutable state during the build out of said 
`QueryBuilder`s



##########
lucene/monitor/src/java/org/apache/lucene/monitor/TermFilteredPresearcher.java:
##########
@@ -254,18 +383,99 @@ public final Document indexQuery(Query query, Map<String, 
String> metadata) {
 
   /** Builds a {@link Document} from the terms extracted from a query */
   protected Document buildQueryDocument(QueryTree querytree) {
-    Map<String, BytesRefHash> fieldTerms = collectTerms(querytree);
+    return toDocument(querytree, field -> field);
+  }
+
+  /** Indexes the terms and negative disjuncts of the current path through a 
{@link QueryTree} */
+  Document toDocument(QueryTree querytree, FieldMapper fields) {
     Document doc = new Document();
-    for (Map.Entry<String, BytesRefHash> entry : fieldTerms.entrySet()) {
-      doc.add(
-          new Field(
-              entry.getKey(),
-              new TermsEnumTokenStream(new 
BytesRefHashIterator(entry.getValue())),
-              QUERYFIELDTYPE));
+    CollectedTerms collected = collectTermsAndNegativeDisjuncts(querytree);
+    List<Set<Term>> negativeDisjuncts = collected.negativeDisjuncts();
+    if (negativeDisjuncts.size() > maxNegativeDisjuncts) {
+      // More negative disjuncts than the document side checks: the marker 
alone satisfies the path
+      // for
+      // every document, so its terms are not needed either
+      addField(doc, negativeDisjunctMarkerField(fields, 0), 
NEGATIVE_DISJUNCT_MARKER);
+      return doc;
+    }
+    for (Map.Entry<String, BytesRefHash> entry : collected.terms().entrySet()) 
{
+      if (maxNegativeDisjuncts > 0 && entry.getKey().contains(NOT_SUFFIX)) {
+        // The field could be indexed under the name of a negative disjunct 
field, whose clauses
+        // exclude
+        // queries, so select the query for every document instead
+        addField(doc, ANYTOKEN_FIELD, new BytesRef(ANYTOKEN));
+        continue;
+      }
+      String field = fields.map(entry.getKey());
+      addField(doc, field, entry.getValue());
+      if (!field.equals(entry.getKey())) {
+        // the term filter looks terms up under the document's field names, so 
a renamed field is
+        // also indexed under its own name
+        addField(doc, entry.getKey(), entry.getValue());

Review Comment:
   This was moved from `MPTFPS` so you can argue it is leaking some 
pass-related specifics into `TFPS`. However, behaviorally this only matters if 
you have non-identity field mapper.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to