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


##########
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:
   `BooleanQuery.visit` always visits a query through a sub-visitor for its 
MUST clauses so every nested BooleanQuery adds a builder for its MUST group. 
Under negation that builder combines its clauses with OR, and merging doesn't 
look inside builders that combine with OR. A builder with a single clause is 
the same either way. So a query with only SHOULD clauses, such as `(a OR b)`, 
has a MUST group whose only clause is its SHOULD group. `clauses.size() + 
negatedTerms.size() == 1` lets merging look through such builders.
   
   For example, `*:* -(a OR (b OR c))` is equivalent to `*:* -a -b -c`, but 
without this check it gave two separate negative disjuncts (`{a}`, `{b, c}`) 
yet it could fit in one disjunct just as well.
   



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