Skip to content

GITHUB#16997 Negative Query Optimizations for Lucene Monitor Presearcher (Part I) - #16998

Merged
romseygeek merged 33 commits into
apache:mainfrom
kotman12:monitor-notslot
Nov 19, 2026
Merged

romseygeek merged 33 commits into
apache:mainfrom
kotman12:monitor-notslot

Conversation

@kotman12

@kotman12 kotman12 commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Description

Hey all, I'm a Solr committer and also a frequent user of the lucene-monitor module. I've had this idea for a while which was greatly inspired by the very clever way that MultiPassTermFilteredPresearcher handles conjunctions. The same approach can actually be extended to more optimally handle negative queries. I never had the courage to actually implement this but in the age of agents you can speed-run the implementation hurdles that come with such a delicate change. I'll also call out that I was extra motivated by a real-world use case that could substantially benefit from this implementation. This work was started during the CoC hackathon in Glasgow. Shout out to @romseygeek for hearing me out on this 😄

AI Usage

Opus 5.5 generated 100% of the code here but I have reviewed it all and iterated many times to get the shape that I present today as the initial implementation was very rough around the edges. The issue and PR description are 100% written by me; if they are slop let it be know that they are human slop!

Design

The TermFilteredPresearcher indexes a query as a disjunction of terms and then an incoming document selects the query if it contains any of them. One can extend this idea and add a "negative disjunct" to that disjunction, which a document satisfies by containing none of its terms. A single negated term or several conjuncted, negated terms are indexed into a special {field}__not_0 field, along with a __negdisjunct_0:__T__ sentinel. The _0 extension assigns an ordinal to the negative disjunct. In the first section I will assume we have only one negative disjunct but queries that need several are covered later.

When converting documents to queries we append the following conjunction of double negations to the existing expansion:

... OR
    (__negdisjunct_0:__T__ AND -field0__not_0:{term00} AND ... 
        AND -field0__not_0:{term0M} AND -field1__not_0:{term10} AND ...
            AND -fieldN__not_0:{termN0} AND ... AND -fieldN__not_0:{termNK})

At first glance it may not seem obvious how this provides any sort of advantage. After all, we are taking the union of this extra clause with the existing pre-filter which makes it look less selective. To fully understand one must remember what happens currently when a negative sub-query is indexed:

  1. *:* -field:value → {__anytokenfield:__ANYTOKEN__}
  2. field:a AND -field:b → {field:a}

Here, __anytokenfield:__ANYTOKEN__ is the existing sentinel term that the presearcher appends to every document → query expansion, ... OR __anytokenfield:__ANYTOKEN__. As a result, query 1 will be returned by every pre-search and run against every document that is processed. Which also means that by safely skipping the sentinel we have an immediate advantage as long as the negative pre-search filters out anything.

Although example 2 has better selectivity (it filters out all documents missing value a in field), the extra information of the negative clause is lost during the pre-search. In many cases negative queries are quite selective so there is a performance gain to be captured here. For instance, if we made the multi-pass extension of the TermFilteredPresearcher negative-aware we can expand 2 in the following ways (assuming passes=2):

query-as-document:
field:a AND -field:b → {field_0:a, __negdisjunct_1_0:__T__, field_1__not_0:b}

document-as-query:
{field:[a, b]} →

(
    (
        field_0:a OR field_0:b OR
        (__negdisjunct_0_0:__T__ AND -field_0__not_0:a AND -field_0__not_0:b)
    )

    AND

    (
        field_1:a OR field_1:b OR
        (__negdisjunct_1_0:__T__ AND -field_1__not_0:a AND -field_1__not_0:b)
    )
)
OR __anytokenfield:__ANYTOKEN__

By handling negative queries we are able to successfully filter out this document which we could not do otherwise. In the current logic the second pass simply repeats the first pass as the pre-searcher cannot extract an indexable term from the negative clause. The end result is the false positive query:

((field_0:a OR field_0:b) AND (field_1:a OR field_1:b)) ...

matches the document which unnecessarily forwards it to the expensive matching stage: {field_0:a, field_1:a}

The motivation for the __negdisjunct_* sentinel is to optimally handle queries without a negative disjunct. Otherwise, the additional clause meant to target negative queries would incidentally pick up positive ones, which would likely lead to performance loss relative to the existing implementation. For instance, x:a OR y:b → {x:a, y:b} would get matched by the final clause in:

{x:c, y:d} → (__anytokenfield:__ANYTOKEN__ OR x:c OR y:d OR (*:* AND -x__not_0:c AND -y__not_0:d)).

By intersecting the last clause with __negdisjunct_0:__T__ instead of *:* we correctly mask queries that have no negative disjunct in their indexed representation.

One has to remember that if a query matches a document then presearcher.buildQuery(document) must match presearcher.indexQuery(query), i.e. a false negatives are not allowed. It is also true that a query which imposes additional conditions apart from the existence of terms (i.e. positional queries), once negated, results in a query that imposes fewer conditions than the nonexistence of those same terms. Thus, negations of positional queries cannot be handled by the proposed, negative-aware pre-searcher as they would violate the aforementioned invariant.

Multiple Negative Disjuncts

So far every query needed a single negative disjunct, but there is a bit of friction when negated terms are themselves disjoined, similar to the friction of positive conjunctions but with many properties reversed. If you recall, our document→query conversion results in an additional query clause which is the intersection of each document term encoded in a negative disjunct field. Put differently we filter out all stored queries which have any of these document terms indexed in their negative disjunct. But once we have a disjunction of two negative terms this idea falls flat. In this case it is possible to have a matching document where none of the terms match the first negated query term or none of the document terms match the second negated term. Thus, during pre-search we have to check for the nonexistence of each term independently. We would not get a correct result by filtering out all stored queries which do not have any of these terms.

The solution to this is to give each branch of the disjunction a negative disjunct of its own, similar to how multi-pass layers the indexed representations of positive conjunctions. We have a budget of negative disjuncts (similar to passes in MTFP), and each branch uses one. Thus,

(*:* -myField:term0) OR (*:* -otherField:term1) → {__negdisjunct_0:__T__, myField__not_0:term0, __negdisjunct_1:__T__, otherField__not_1:term1}

Similarly, a document would be transformed as follows:
{myField:term2, otherField:term1} →

 ... OR
    (__negdisjunct_0:__T__ AND -myField__not_0:term2 AND -otherField__not_0:term1)
        OR (__negdisjunct_1:__T__ AND -myField__not_1:term2 AND -otherField__not_1:term1)

which correctly matches the indexed query despite matching only a single branch of the disjunction. We can only filter out if the document contains both negated terms:
{myField:term0, otherField:term1} →

 ... OR
    (__negdisjunct_0:__T__ AND -myField__not_0:term0 AND -otherField__not_0:term1)
        OR (__negdisjunct_1:__T__ AND -myField__not_1:term0 AND -otherField__not_1:term1)

In this case, the document is correctly filtered out from the result set by the pre-searcher (assuming a budget of 2 negative disjuncts).

A key difference between expanding positive conjunctions into passes and negated disjunctions into negative disjuncts is when we run out of pre-configured budget. In the case of positive conjunctions it is safe to simply stop and keep the existing passes that fit into the budget. On the other hand, a pass that needs more negative disjuncts than the budget allows must select the query for every document, otherwise you open the door to false negatives. For that pass we index only the __negdisjunct_0:__T__ sentinel. When a negative disjunct clause in the document→query conversion has no indexed terms to exclude on, it will match every document (although the remaining passes can still filter).

Another important difference is that each subsequent pass in the positive query case increases selectivity while each additional negative disjunct decreases it, instead. Thus, in practice one may run with a budget of only one, or perhaps two negative disjuncts. I leave it in the implementation because it isn't too much extra work and may turn out to be useful. As a default I would probably recommend one.

Usage

I imagine that this enhancement will be most useful with a MultiPassTermFilteredPresearcher as standalone negative queries (*:* -field:b) queries are rare and when you have a positive branch it is typically more selective than a negative branch. But once you can index more than one branch (with MPTFPS), being able to use negation as a pre-search filter becomes more enticing. For what it's worth I find the MPTFPS to be the best Presearcher in practice as its default behavior is quite selective and requires little to no tuning.

queries[i] = new BooleanQuery.Builder();
}
}
Map<String, List<BytesRef>> negatableTerms = new HashMap<>();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

import org.apache.lucene.index.Term;

/** A TermWeightor with its own weighting of the absence of terms */
record NegatingTermWeightor(TermWeightor weightor, DoubleUnaryOperator negation)

@kotman12 kotman12 Nov 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than having each combined positive weightor get negated individually I try to force users to define at most one negating weightor function. The default negating weightor will assume the final positive weight (possibly the result of combining multiple weights) is a surprisal (inspired by how the doc freq weightor currently works) and then invert it.

It's hard to mathematically justify applying the negating weight multiple times as you may end up with a positive weight or some other garbage.

@@ -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);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a judgement call but I found that defining the QT as a tree of Functions 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.

if (parent instanceof BooleanQuery bq
&& isPureNegative(bq)
&& (!isNegationOptimized || isNegated)) {
clauses.add(new Leaf(_ -> QueryTree.anyTerm("PURE NEGATIVE QUERY[" + parent + "]")));

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

if (query instanceof TermQuery
|| query instanceof SynonymQuery
|| (query instanceof TermInSetQuery tisq
&& tisq.getRewriteMethod() != MultiTermQuery.DOC_VALUES_REWRITE)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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;

@kotman12 kotman12 Nov 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 generally look inside builders that combine with OR. However, a query with only SHOULD clauses, such as (a OR b), is actually always wrapped in a MUST group (whose only clause is that SHOULD group). clauses.size() + negatedTerms.size() == 1 lets merging know we have a single MUST clause wrapping potentially many SHOULD clauses. Under negation SHOULD is conjunctive so we can continue merging.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add this as a comment in the code too?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me know if this comment looks good.

* 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) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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());

@kotman12 kotman12 Nov 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

*/
private static void addRawTerms(Document doc, String field, BytesRefHash terms) {
BytesRef scratch = new BytesRef();
for (int i = 0; i < terms.size(); i++) {

@kotman12 kotman12 Nov 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 some non-UTF8 bytes to some character which you then 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a bug in TermsEnumTokenStream? From a quick look, the current implementation seems to be doing a fairly pointless round-trip to a char[] when we could be using a TermToBytesRefAttribute and operating entirely on bytes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So it looks like registering a literal TermToBytesRefAttribute registers a CharTermAttribute under the hood? I'm assuming you meant a BytesTermAttribute... The one issue I ran into with that idea is that it breaks existing users of CustomQueryHandler::wrapTermStream, who implicitly rely on this being a CharTermAttribute. If we switched to Bytes* they would stop seeing the terms an anything they'd write would get dropped as well. A straight switch would have to be a breaking change. The other tricky part is that it may make things less efficient for them, because some filtering probably relies on char-based input. For instance, the existing regex-supporting n-gram token stream takes substrings, which would be tricky to do on raw bytes. You'd probably want to round-trip bytes->chars->bytes in that case (which is what happens currently, but in the new model you'd do it for every filter). I imagine there's a good chance that anyone who has implemented a custom handler relies on char input.

A possible workaround, though a bit heavyweight, is a custom attribute implementing both BytesTermAttribute and CharTermAttribute, which starts as raw bytes and "downgrades" to chars whenever a filter touches the chars. For Monitors without custom handlers (probably a good majority) it could stay bytes-only. But not sure if this is worth the effort.

@kotman12 kotman12 Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A propos the dual-interface attribute idea, looks like ConcatenateGraphFilter does something similar to what I'm proposing.

// read directly: TermsEnumTokenStream can merge invalid UTF-8 terms, which must not exclude
String notField = field + NOT_SUFFIX;
for (BytesRef term = terms.next(); term != null; term = terms.next()) {
if (terms.docFreq() == maxDoc && termAcceptor.test(notField, term)) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Multi-doc batches don't work well with this feature as currently implemented. I am not a user of the batch feature but analyzing this PR made me realize that they don't work well with the current MultiPassTermFilteredPresearcher either. More details here #17004. I think if we can address the linked issue this won't really be a problem.

static TermWeightor combine(TermWeightor... weightors) {
for (TermWeightor w : weightors) {
if (w instanceof NegatingTermWeightor) {
throw new IllegalArgumentException(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@romseygeek romseygeek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for opening @kotman12, this looks very cool. It is obviously a lot to review at once so I will take some time over it, if that's OK. Do you have any numbers on how it performs for your usecases?

*/
private static void addRawTerms(Document doc, String field, BytesRefHash terms) {
BytesRef scratch = new BytesRef();
for (int i = 0; i < terms.size(); i++) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a bug in TermsEnumTokenStream? From a quick look, the current implementation seems to be doing a fairly pointless round-trip to a char[] when we could be using a TermToBytesRefAttribute and operating entirely on bytes.

@kotman12

kotman12 commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for opening @kotman12, this looks very cool. It is obviously a lot to review at once so I will take some time over it, if that's OK. Do you have any numbers on how it performs for your usecases?

@romseygeek Yes of course, thanks for taking a look!

Re the size:

I apologize for the diff. Although it is mostly tests it is still quite large and touches existing components. As I was putting this together I did two refactors that were tangential but IMO helped the readability of the full change as it stands:

  1. addition of TermsCollector interface (minor breaking change)
  2. Modeling the QueryTree as Leaf and Clauses without the generic functional java glue that obfuscates the call graph.

If it helps with review (and assuming you agree these make sense) I can split these out as separate PRs. Let me know if you'd like me to do that.

Re performance:

Obviously a lot depends on the type of queries and documents. I have two datasets and each had a different response to this patch but both were positive. The main benefit is it makes the MultiPassTermFilteredPresearcher extremely efficient even at high levels of passes. Below are some presearch ratio and Monitor mean wall-time matching one document at a time:

Passes Document Set Baseline ratio PR ratio Baseline ms PR ms
4 Set 1 15.4% 20.6% 67.3 53.0
4 Set 2 4.4% 11.5% 193.5 85.8
6 Set 1 16.2% 23.6% 64.0 48.5
6 Set 2 4.7% 22.9% 169.3 48.5

It also vastly improves P99 presearch ratios (times are nearly perfectly correlated):

Passes Document Set Baseline PR
4 Set 1 2.6% 7.3%
4 Set 2 2.5% 6.7%
6 Set 1 2.8% 11.8%
6 Set 2 2.7% 11.7%

The bigger win for this dataset was actually a separate patch I put together to treat point queries as term queries (both sets have a lot of non-range, single point queries in addition to the negative queries). Once you have this and negative queries handled the performance gets insane as multi-pass "saturation" of the combined effect is even better than any one alone:

Passes Document Set Baseline ratio Points ratio PR + Points ratio Baseline ms Points ms PR + Points ms
4 Set 1 15.4% 41.9% 52.6% 67.3 33.9 28.1
4 Set 2 4.4% 13.9% 27.8% 193.5 93.9 56.9
6 Set 1 16.2% 48.5% 62.5% 64.0 27.6 23.8
6 Set 2 4.7% 16.5% 54.9% 169.3 68.8 27.8

P99 pre-search ratios:

Passes Document Set Baseline Points PR + Points
4 Set 1 2.6% 8.4% 17.6%
4 Set 2 2.5% 8.1% 16.6%
6 Set 1 2.8% 10.1% 41.2%
6 Set 2 2.7% 9.8% 40.0%

As I mentioned the Points handling is a "dirty" patch, ideally we'd also handle range queries (just as percolator does) which is why it is not PR ready. But I did start thinking about this and raised #17005 for your awareness. I think there are some design decisions to iron out before anything should be proposed.

Important

I just want to reiterate how amazed I am that with 6 passes + negation + points handling I am able to get ~40% presearch ratio for the 99th percentile (!) for both datasets. This beats my previous mean presearch ratio by almost 3X.

@romseygeek

Copy link
Copy Markdown
Contributor

If it helps with review (and assuming you agree these make sense) I can split these out as separate PRs. Let me know if you'd like me to do that.

I think this would make things a lot easier, so let's do that.

@kotman12

Copy link
Copy Markdown
Contributor Author

If it helps with review (and assuming you agree these make sense) I can split these out as separate PRs. Let me know if you'd like me to do that.

I think this would make things a lot easier, so let's do that.

Done ... I've kept the core QueryTree changes here and the actual integration of the feature into the Presearchers will move here #17032. Let me know if this split works for you.

@kotman12 kotman12 changed the title GITHUB#16997 Negative Query Optimizations for Lucene Monitor Presearcher GITHUB#16997 Negative Query Optimizations for Lucene Monitor Presearcher (Part II) Nov 16, 2026
@kotman12 kotman12 changed the title GITHUB#16997 Negative Query Optimizations for Lucene Monitor Presearcher (Part II) GITHUB#16997 Negative Query Optimizations for Lucene Monitor Presearcher (Part I) Nov 16, 2026

@romseygeek romseygeek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A couple of small nits round comments, but otherwise LGTM. I'll merge once you've updated, thanks @kotman12!

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add this as a comment in the code too?

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've changed the comment to refer to this as information content since that is wikipedia's primary term for it. Negating weights is easiest to think about when mapping from a common probability space (since it is p for a doc matching the query and then naturally 1-p for it not matching). Then to get the "direction" right you invert the probability. Finally one can apply the natural log to this inverse probability to get the "surprisal" or "information content" in nats. I don't think taking the natural log here is strictly necessary but it has some nice properties (avoiding over/underflow, independent events are additive instead of multiplicative, and it is a standard).

However, none of the existing weightors return information content so currently the negating weightor returns no meaningful units. It pretends it receives nats from the positive weightor when in reality it probably doesn't. Perhaps it makes sense to come up with a positive weightor that attempts to compute information content (with this change or a follow-up)?

For instance, interpreting the current default weightor as information content incidentally results in a negative weightor that is very conservative and always just defers to positive weights over negative ones. But this is partly by chance because of how that weightor is currently calibrated. I think this default is probably fine but I've just added testDefaultWeightsReadSensiblyAsInformationContent to ensure that no one incidentally recalibrates the default weightor too far without considering the effect on the negative weightor as it stands. Going too far in any direction could either result in a term that the negating weightor thinks is in a majority of documents (hard to make this claim based on term length) or in a term so rare that the negative weightor collapses to 0 (also unlikely based on just term length).

Here is a table of how the default weightor currently negates:

Term length Weight w Implied p = e^-w Absence 1 - p Negative weight -ln(1 - p)
1 1.778 16.91% 83.09% 0.1852
3 2.780 6.20% 93.80% 0.0640
5 3.331 3.58% 96.42% 0.0364
10 3.851 2.13% 97.87% 0.0215
32+ 4.000 1.83% 98.17% 0.0185

@romseygeek

Copy link
Copy Markdown
Contributor

LGTM! Let's add a separate CHANGES entry summarizing the new functionality in this PR?

@kotman12

Copy link
Copy Markdown
Contributor Author

LGTM! Let's add a separate CHANGES entry summarizing the new functionality in this PR?

Thanks! I've updated the changes entry to indicate that this is a partial feature at this point.

@romseygeek
romseygeek merged commit 2cf3f57 into apache:main Nov 19, 2026
13 checks passed
romseygeek pushed a commit that referenced this pull request Nov 19, 2026
Monitor's QueryTree now merges each group of conjoined, negated leaf queries
(e.g. -x:a -x:b) into one "negative disjunct", which documents satisfy by containing 
none of its terms. This will later let TermFilteredPresearcher skip a query for 
documents that contain at least one term of each of its negative disjuncts. 
TermWeightor gains negate and withNegation to weigh the absence of a term, and 
CustomQueryHandler gains handleNegatedQuery.  Not wired into any presearchers yet.
@romseygeek

Copy link
Copy Markdown
Contributor

I've merged and backported to lucene_11. Let me know when the follow-ups are ready to review!

@kotman12

Copy link
Copy Markdown
Contributor Author

I've merged and backported to lucene_11. Let me know when the follow-ups are ready to review!

Thanks @romseygeek ... the follow up is https://github.com/apache/lucene/pull/17032/changes and is ready for your review (whenever you are ready of course)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants