lance icon indicating copy to clipboard operation
lance copied to clipboard

perf(fts): equivalent FTS queries run up to ~12× slower depending on how the query tree is written

Open mikewhb opened this issue 1 month ago • 4 comments

+a +b can be written as Match("a b", And) or as Boolean{must:[Match(a), Match(b)]}. Both match the same documents and score each of them identically; only the plan differs. On a Wikipedia benchmark the per-term form is a median 1.8×–12× slower. It is also the form you get by translating Lucene/ES syntax or by building a BooleanQuery clause by clause, so it is common in practice.

This is a measurement report, not a fix proposal.

Measurement

Setup:

  • lance @ 1625d27ff8
  • one text column, inverted index with positions
  • LANCE_FTS_NUM_SHARDS=1, LANCE_FTS_PARTITION_SIZE=65536
  • single-threaded, index in memory, fast_search, limit=10

Only the query tree differs between forms.

Each query is run 60 times and summarized by its median. The ratio for a query is that form's time divided by the fastest form's time. The table gives the median and the p10–p90 of those ratios across queries.

Shape Fastest form Per-term form median p10–p90 n one more Bool{must:[…]}, vs the form it wraps [2]
+a +b Match("a b", And) Bool{must:[Match(a), Match(b)]} 3.28× 1.4–6.5× 299 1.22×
a b [1] Match("a b", Or) Bool{should:[Match(a), Match(b)]} 11.71× 2.9–52× 299 2.57×
+a +b c Bool{must:[Match("a b", And)], should:[Match(c)]} Bool{must:[Match(a), Match(b)], should:[Match(c)]} 2.36× 1.4–4.3× 400 1.00×
+a +b c d as above, should:[Match(c), Match(d)] as above, should:[Match(c), Match(d)] 1.78× 1.3–3.6× 101 1.02×

a b queries have 2 or more terms, all optional; the other shapes have 2–7 mandatory terms (2–6 in the fourth shape).

[1] This row mixes two populations. 2-term queries (198) have a median of 22.9×; queries with 3 or more terms (101) have a median of 4.4×.

[2] The first two shapes wrap the fastest form, and the wrapper alone moves the query into the compound scorer. The last two shapes wrap the per-term form, which is already a Boolean, so the planner does not change.

Raising limit to 100 on a 160-query subset of +a +b changes the per-term ratio from 3.50× to 3.35× and the wrapper cost from 1.26× to 1.38×.

explain for +kasota +stone:

Match("kasota stone", And)
  MatchQuery: column=text, query=[kasota stone]
Bool{must:[Match("kasota"), Match("stone")]}
  CompoundFtsScorer: query=Boolean(must=[Match(... "kasota" ...), Match(... "stone" ...)], ...)
Bool{must:[Match("kasota stone", And)]}
  CompoundFtsScorer: query=Boolean(must=[Match(... "kasota stone" ...)], ...)

Likely cause (from reading the code, not profiled)

  • supports_compound_scorer rejects a bare Match, so it runs as MatchQueryExec. Wrapped in a Boolean, it passes the gate and, in this setup, runs as CompoundFtsScorer. For these shapes MatchQueryExec is the faster of the two.
  • In the compound scorer, each single-term Match is a separate cursor. RequiredConjunctionScorer passes the top-k floor down only when it has a single child, so with K mandatory clauses pruning relies on the conjunction-level bounds alone.
  • A pure should uses ShouldMaxScoreScorer only with 3 or more clauses. With 2 clauses it is a plain sum, which is why footnote [1] shows the largest gap for 2-term queries.

Equivalences

Rewrite Holds when Effect [3]
E1 Bool{must:[X]} or Bool{should:[X]} → X one clause, no must_not 1.22× / 2.57× when X is a Match; about 1.0× otherwise
E2 Bool{must:[Bool{must:[…]}, …]} → one level; same for should the inner Boolean is non-empty and has only must (or only should) clauses; never applied to must_not clauses 1.13–1.17× [4]
E3 Bool{must:[Match(a), Match(b)]} → Match("a b", And); for should, Or every must (or should) clause is merged; same column; fuzziness 0; boost 1; each clause is one distinct token after analysis about 2.7× / 4.6× / 2.36× / 1.78× [5]

Applying E3 and then E1 turns the per-term +a +b into a bare Match.

[3] Measured on queries already written in the target form, not on an implemented rewrite. [4] Measured in reverse, by wrapping each clause. [5] The first two values are medians divided by medians (3.28 / 1.22 and 11.71 / 2.57), not per-query ratios.

Two caveats for any implementation:

  • Scores are summed left to right in f32. A flatten or merge keeps every score bit only when the rewritten clauses come first in their must or should list. This holds in all measured cases.
  • Fuzzy Match clauses cannot be merged, because one Match shares a single max_expansions budget across its terms (#9659).

Correctness

At limit=10, on a fully indexed dataset, I compared every measured form with one reference form of the same query (2,810 comparisons). The multiset of the ten returned scores is bit-identical in all of them. 48 comparisons differ only among equal-scored documents: 16 in their order, and 32 in which of the documents tied with the 10th result make the cut. I make no claim for other limits, or for partially indexed datasets, where corpus statistics already depend on the plan (#9058).

Corpus

The queries come from search-benchmark-game (Wikipedia): its 300 mandatory-only and 301 optional-only queries. The two mixed shapes do not occur in SBG. For those I derived 504 queries from SBG's multi-term queries by appending a common word and/or making the last mandatory term optional. They probe query shapes; they are not a workload.

Reproduction

import lance
from lance.query import BooleanQuery, FullTextOperator, MatchQuery, Occur

ds = lance.dataset("...")  # inverted index on "text"
forms = {
    "match":    MatchQuery("kasota stone", "text", operator=FullTextOperator.AND),
    "per-term": BooleanQuery([(Occur.MUST, MatchQuery("kasota", "text")),
                              (Occur.MUST, MatchQuery("stone", "text"))]),
    "wrapped":  BooleanQuery([(Occur.MUST, MatchQuery("kasota stone", "text",
                                                      operator=FullTextOperator.AND))]),
}
for name, q in forms.items():
    print(name, ds.scanner(full_text_query=q, limit=10, fast_search=True).explain_plan())

I can share the harness, the query lists and the per-query results.

Questions

  1. Is the routing above intentional — a bare Match bypassing the compound scorer, while the same Match wrapped in a Boolean uses it?

  2. If it is not, would you consider normalizing the query tree once, before it is planned, so that equivalent forms reach the same plan? Two reasons:

    • It would make future work in the kernel easier. An optimization added to the scorers or executors could then be designed, benchmarked and argued against one canonical query shape, instead of depending on which of several equivalent forms the caller happened to write.
    • It would make the API simpler, more flexible and more predictable for callers. Writing +a +b as one Match or as a Boolean built clause by clause would stop being a performance decision. Users could follow whatever their syntax translation or query builder produces, and the cost would not jump depending on the form.

mikewhb avatar Oct 27 '26 11:10 mikewhb

Would a planner-side rewrite for this be welcome? I'd like to take it.

The idea: before planning, fold the per-term leaves of a BooleanQuery into the single-leaf form your table shows is fastest.

  • must holding two or more Match leaves becomes one Match(terms joined, And); should with no must becomes one Match(terms joined, Or).
  • Leaves are folded only when they share the same resolved column and boost, each leaf tokenizes to one term or already uses the target operator, and matching is exact (fuzziness == Some(0)). max_expansions is a per-leaf budget, so folding fuzzy leaves would change which terms expand; those stay as they are.
  • must_not, Phrase, Boost, MultiMatch and CombinedFields clauses are left alone, and mixed clauses keep their non-foldable parts in place.

Tests would assert the folded and unfolded trees return the same rows and the same scores on a small corpus, plus a benchmark case for the +a +b and a b shapes.

Since the FTS exec code is being split up right now (#10598, #10645), is there a preferred place for a rewrite like this, or a planner change in progress I should build on instead?

aimanmalib avatar Nov 09 '26 12:11 aimanmalib

Would a planner-side rewrite for this be welcome? I'd like to take it.

The idea: before planning, fold the per-term leaves of a BooleanQuery into the single-leaf form your table shows is fastest.

  • must holding two or more Match leaves becomes one Match(terms joined, And); should with no must becomes one Match(terms joined, Or).
  • Leaves are folded only when they share the same resolved column and boost, each leaf tokenizes to one term or already uses the target operator, and matching is exact (fuzziness == Some(0)). max_expansions is a per-leaf budget, so folding fuzzy leaves would change which terms expand; those stay as they are.
  • must_not, Phrase, Boost, MultiMatch and CombinedFields clauses are left alone, and mixed clauses keep their non-foldable parts in place.

Tests would assert the folded and unfolded trees return the same rows and the same scores on a small corpus, plus a benchmark case for the +a +b and a b shapes.

Since the FTS exec code is being split up right now (#10598, #10645), is there a preferred place for a rewrite like this, or a planner change in progress I should build on instead?

Thanks for picking this up.

I won't have much time for this in the near future, but I had thought about it a bit earlier and wanted to share some notes for discussion. @BubbleCal, would be great to hear your view.

The scope and exclusions look right to me, including leaving fuzzy leaves alone because of the per-leaf max_expansions budget.

The part I'm less sure about is joining the terms into one string. MatchQuery.terms is re-analyzed at execution time, so the fold is only exact if analyzing the joined string yields exactly the concatenation of the per-leaf tokens and term groups. "Each leaf tokenizes to one term" only constrains each leaf, not the joined string, so it can't guarantee that for an arbitrary LanceTokenizer. Two built-in examples:

  • ngram windows across the space: must[Match(abc), Match(xyz)] matches rows {0, 1}, but Match("abc xyz", And) matches only {0}.
  • JSON parses a,str,x b,str,y as a single triplet with value x b,str,y.

Would it work to fold after analysis instead, without building a string? In prepare_compound_query each leaf is already tokenized by tokenize_leaf. We could concatenate those Tokens, keeping each leaf's term groups and offsetting them per clause (Tokens::with_positions + with_term_groups), then call prepare_bm25_query once to get a single PreparedLeaf with Operator::And / Operator::Or.

mikewhb avatar Nov 10 '26 09:11 mikewhb

Thanks for the tokenizer examples. I built the fold after analysis as you described (concatenated Tokens, term groups offset per clause, one prepare_bm25_query), and folded and unfolded trees return the same rows and scores, including on ngram and JSON indexes.

Timing compound_search on a 100k-doc Zipf corpus (release build, top 10, 20 queries per shape, median of 35 runs, µs per query):

shape main folded
must 2 / 3 / 4 terms 1466 / 1528 / 928 633 / 763 / 710
should 2 / 3 / 4 terms 3715 / 1693 / 1726 4076 / 7292 / 9493

Folding must helps (1.3x to 2.3x), but one multi-token Or leaf is 1.1x to 5.5x slower inside the compound scorer than separate should leaves, so the a b shape gets worse. I'm not opening the PR as scoped; the numbers are here in case a must-only fold or a look at the Or leaf path is useful later.

aimanmalib avatar Nov 12 '26 03:11 aimanmalib

Thanks for the tokenizer examples. I built the fold after analysis as you described (concatenated Tokens, term groups offset per clause, one prepare_bm25_query), and folded and unfolded trees return the same rows and scores, including on ngram and JSON indexes.

Timing compound_search on a 100k-doc Zipf corpus (release build, top 10, 20 queries per shape, median of 35 runs, µs per query):

shape main folded must 2 / 3 / 4 terms 1466 / 1528 / 928 633 / 763 / 710 should 2 / 3 / 4 terms 3715 / 1693 / 1726 4076 / 7292 / 9493 Folding must helps (1.3x to 2.3x), but one multi-token Or leaf is 1.1x to 5.5x slower inside the compound scorer than separate should leaves, so the a b shape gets worse. I'm not opening the PR as scoped; the numbers are here in case a must-only fold or a look at the Or leaf path is useful later.

Thanks for running these — the must-only result looks useful.

One question first: in the should 2 / 3 / 4 terms arms, does the folded form end up as a bare MatchQuery("a b", operator=Or) , or as one multi-term Or leaf still inside the Boolean tree? A fold after analysis in prepare_compound_query (concatenated Tokens, one prepare_bm25_query) produces the latter. Could you paste explain_plan() for the unfolded, folded and bare-Match forms?

The reason I ask: a bare Match(And) / Match(Or) has substantially more optimizations available than the same terms placed in a CompoundFtsScorer. supports_compound_scorer (rust/lance/src/dataset/scanner.rs:325) sends a bare Match to MatchQueryExec → Wand::search, which has bulk MAXSCORE (#7603), bulk AND windows (#7624), shared floors and block-max pruning. A Boolean — even one holding a single Or leaf — goes to the compound scorer, whose WandCursor only advances doc-at-a-time via wand.next() (wand.rs:6136) and never reaches Wand::search. So I'd expect the canonical form for pure MUST / pure SHOULD to be one bare Match leaf, not a compound tree.

mikewhb avatar Nov 12 '26 08:11 mikewhb