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


##########
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:
   Let's add this as a comment in the code too?



##########
lucene/monitor/src/java/org/apache/lucene/monitor/TermWeightor.java:
##########
@@ -21,18 +21,61 @@
 import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
+import java.util.function.DoubleUnaryOperator;
 import java.util.function.ToDoubleFunction;
 import org.apache.lucene.index.Term;
 import org.apache.lucene.util.BytesRef;
 
-/** Calculates the weight of a {@link Term} */
+/**
+ * Calculates the weight of a {@link Term}
+ *
+ * <p>Higher weights mark terms that are more useful for selecting queries, 
typically rarer or
+ * longer ones. {@link #negate(double)} turns a weight into the weight of the 
absence of the term,
+ * for negated clauses.
+ */
 public interface TermWeightor extends ToDoubleFunction<Term> {
 
   /** A default TermWeightor based on token length */
   TermWeightor DEFAULT = lengthWeightor(3, 0.3f);
 
-  /** Combine weightors by multiplication */
+  /** The smallest weight returned by the default {@link #negate(double)} */
+  double MIN_NEGATED_WEIGHT = 1e-6;
+
+  /**
+   * The weight of the absence of a term of weight {@code weight}, used for 
negated clauses
+   *
+   * <p>By default the weight is read as surprisal, {@code w = -ln p} where 
{@code p} is the share

Review Comment:
   "surprisal" is a new term to me, TIL.  Can we add a link to Wikipedia or 
similar?



-- 
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