Repository navigation
GITHUB#16997 Negative Query Optimizations for Lucene Monitor Presearcher (Part I) - #16998
Conversation
…dNameMapper (DEFAULT, or pass(i) for multipass).
…ngle negation across combines
| queries[i] = new BooleanQuery.Builder(); | ||
| } | ||
| } | ||
| Map<String, List<BytesRef>> negatableTerms = new HashMap<>(); |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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); | |||
There was a problem hiding this comment.
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 + "]"))); |
There was a problem hiding this 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
| if (query instanceof TermQuery | ||
| || query instanceof SynonymQuery | ||
| || (query instanceof TermInSetQuery tisq | ||
| && tisq.getRewriteMethod() != MultiTermQuery.DOC_VALUES_REWRITE) |
There was a problem hiding this 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.
| 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; |
There was a problem hiding this 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 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.
There was a problem hiding this comment.
Let's add this as a comment in the code too?
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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()); |
There was a problem hiding this comment.
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++) { |
There was a problem hiding this 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 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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)) { |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
I explain this in https://github.com/apache/lucene/pull/16998/changes#r4497736806
…notslot # Conflicts: # lucene/CHANGES.txt
romseygeek
left a comment
There was a problem hiding this comment.
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++) { |
There was a problem hiding this comment.
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.
@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:
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
It also vastly improves P99 presearch ratios (times are nearly perfectly correlated):
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:
P99 pre-search ratios:
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. |
I think this would make things a lot easier, so let's do that. |
Done ... I've kept the core |
romseygeek
left a comment
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
"surprisal" is a new term to me, TIL. Can we add a link to Wikipedia or similar?
There was a problem hiding this comment.
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 |
|
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. |
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.
|
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) |
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
MultiPassTermFilteredPresearcherhandles 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_0field, along with a__negdisjunct_0:__T__sentinel. The_0extension 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:
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:
*:* -field:value→{__anytokenfield:__ANYTOKEN__}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
ainfield), 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 (assumingpasses=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]}→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:
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
querymatches adocumentthenpresearcher.buildQuery(document)must matchpresearcher.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
passesinMTFP), 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}→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}→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
MultiPassTermFilteredPresearcheras 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 (withMPTFPS), being able to use negation as a pre-search filter becomes more enticing. For what it's worth I find theMPTFPSto be the bestPresearcherin practice as its default behavior is quite selective and requires little to no tuning.