Optimizing Boolean Queries

Choosing the order in which to evaluate a Boolean query. Processing terms by increasing document frequency, estimating the size of OR clauses, where to apply NOT, rewriting queries with Boolean identities, why ordering matters most when combined with search-based intersection, general cost bounds, and the plans measured on random postings with every intermediate result size. Worked problems on ordering OR clauses, on a query where shortest-first is not the cheapest plan, and on where to apply NOT.

For a conjunction, intersecting terms in increasing order of document frequency, which the dictionary stores, keeps every intermediate result within the rarest term's frequency $f_1$. With search-based intersection the cost is then at most about $f_1 \sum_{i \ge 2} \log_2 f_i$ comparisons, while a merge reads every list whatever the order. On random postings of 1,000, 100,000 and 500,000 documents in a million (medians of 30 seeds), rarest first took 17,082 comparisons with binary search and the worst order 1,784,374; every merge took about 600,000. The rule is a heuristic: overlaps can make another order cheaper. OR clauses are ordered by estimated size (the summed frequencies overestimated three Cranfield clauses by up to 36 percent but ordered them correctly), and NOT is applied last, to a small result.

Skip pointers and search-based intersection make one intersection cheap when one list is short. A query of three terms joined by AND takes two intersections, in any of three orders. Suppose the terms have document frequencies of 1,000, 100,000, and 500,000. Intersecting the two common terms first means merging lists of 100,000 and 500,000 postings, only to throw almost all of the result away when it meets the rare term. Starting with the rare term keeps every intermediate result at no more than 1,000 documents. Which order should a system choose, and how can it know before reading any postings? It should start with the rarest term, and it knows which term that is because the dictionary stores every term's document frequency.

Query optimization chooses an evaluation order that produces the same answer with less work. The ideas are those of database query optimization, applied to postings lists: use statistics about the data to estimate the size of intermediate results, and keep them small. This article follows Manning, Raghavan, and Schütze (2008, §1.3), with extensions.

First we derive the rarest-first rule for conjunctions and measure every plan for the three-term query. Then we estimate the sizes of OR clauses and check the estimate on a real collection. Next we decide where NOT belongs, and which rewrites help further. Worked problems close the article.

Conjunctions: rarest first

For a query of terms joined only by AND, the rule is simple:

  1. Look up each term's document frequency, $\mathit{df}$, stored in the dictionary. It is the length of the term's postings list.
  2. Sort the terms by increasing $\mathit{df}$.
  3. Intersect the two shortest lists, then intersect the result with each remaining list in order.

Here is the idea in one sentence: an intersection is never longer than its shorter input, so starting with the rarest term bounds every intermediate result by that term's document frequency. Each later step then intersects a short list with a long one, which is exactly the case where skip pointers and search-based intersection save the most. Storing document frequency in the dictionary, next to the pointer to each postings list, is what makes the plan cheap to compute before any postings are read. The course text calls the rule the standard heuristic and claims only that it is likely to do the least total work (Manning, Raghavan, and Schütze, 2008, §1.3). Problem 2 below gives a query on which another order is cheaper.

How much does the order matter? Little with a plain merge, and a factor of about fifty with search. Both costs can be bounded for the frequencies above, $\mathit{df}_a = 1{,}000$, $\mathit{df}_b = 100{,}000$, and $\mathit{df}_c = 500{,}000$:

Plan Linear merge, upper bound on comparisons With binary search, approximately
$(b \cap c) \cap a$ $(100{,}000 + 500{,}000) + (100{,}000 + 1{,}000) = 701{,}000$ $100{,}000 \log_2 500{,}000 + 1{,}000 \log_2 100{,}000 \approx 1{,}910{,}000$
$(a \cap b) \cap c$ $(1{,}000 + 100{,}000) + (1{,}000 + 500{,}000) = 602{,}000$ $1{,}000 \log_2 100{,}000 + 1{,}000 \log_2 500{,}000 \approx 35{,}500$

With a plain linear merge, the order changes the worst case only modestly, because every long list is scanned to the end in either plan. The large gain comes from combining the order with intersection by search. Once the intermediate result is small, each of its few documents can be looked up in the long list in logarithmic time. With search, the two orders differ by a factor of about fifty. Ordering and search-based intersection work together, and neither achieves much without the other.

The bounds in general

Does the same hold for more than three terms? The same reasoning gives bounds for any conjunction. Sort the $t$ terms so that $f_1 \le f_2 \le \dots \le f_t$, where $f_i$ is the document frequency of the $i$-th, and write $r_i$ for the size of the intermediate result after the first $i$ terms have been intersected. Every $r_i \le f_1$, since an intersection is no longer than its shorter input. Step $i$ intersects a result of size $r_{i-1}$ with a list of size $f_i$, so

$$\text{merge cost} \le \sum_{i=2}^{t} (r_{i-1} + f_i) \le (t - 1)\, f_1 + \sum_{i=2}^{t} f_i,$$

$$\text{search cost} \approx \sum_{i=2}^{t} r_{i-1} \log_2 f_i \le f_1 \sum_{i=2}^{t} \log_2 f_i.$$

The merge bound is dominated by the sum of all the list lengths. No order can lower that worst case, since in the worst case each list is read to the end. The search bound is proportional to the shortest list, $f_1$, and only logarithmic in the others, so it is the search bound that the choice of first term controls.

A third saving applies to both. If any intermediate result is empty, evaluation stops, because nothing can survive later intersections. Manning, Raghavan, and Schütze's algorithm (2008, Figure 1.7) stops in this way, and starting with the rarest terms makes an early empty result more likely.

Measured on random postings

The bounds assume the worst intermediate sizes. How large are the intermediate results really? That depends on how the terms co-occur. If terms occur independently, a document contains both $a$ and $b$ with probability $(\mathit{df}_a / N)(\mathit{df}_b / N)$. The expected size of their intersection in a collection of $N$ documents is then

$$|a \cap b| \approx \frac{\mathit{df}_a \, \mathit{df}_b}{N}.$$

With $N = 1{,}000{,}000$ and the frequencies above, that gives $|a \cap b| \approx 100$, $|a \cap c| \approx 500$, $|b \cap c| \approx 50{,}000$, and $|a \cap b \cap c| \approx 50$.

To check the plans against these sizes, each term's documents were drawn at random from a million. Each plan was run with the merge, binary search, and galloping search of intersecting postings lists, counting docID comparisons. In each step, the shorter of the two inputs is searched for in the longer. The table gives medians over 30 seeded runs; the interquartile ranges of the costs are within 2 percent of the medians.

Example (which plan wins depends on the intersection method). With the merge, no plan wins by much: all three read every list to the end, at about 600,000 comparisons. With binary search, the rarest-first plan $(a \cap b) \cap c$ wins, at about a hundredth of the cost of the plan that starts with the two common terms. The table below gives the measured costs.

Plan First result (median) Final result (median) Merge Binary search Galloping
$(a \cap b) \cap c$ 104 51 598,260 17,082 15,117
$(a \cap c) \cap b$ 498 51 600,315 25,182 24,576
$(b \cap c) \cap a$ 49,972 51 600,906 1,784,374 464,593

Four things stand out:

  • The merge costs about 600,000 comparisons whatever the order, as the bound predicts.
  • The rarest-first plan, $(a \cap b) \cap c$, is the cheapest with search. The plan that starts with the two common terms costs about a hundred times as much with binary search.
  • The rarest-first plan with binary search costs about half its bound of 35,500, because the intermediate result is about 100 documents, not the 1,000 the bound allows.
  • Galloping softens the penalty of a bad plan. It cuts the cost of $(b \cap c)$ by a factor of almost four over binary search. Intersecting 100,000 entries with 500,000 is a case of similar lengths, where galloping behaves like a merge.

The script is tools/experiments/boolean/query_optimization.py.

Real terms are not independent. San and Francisco co-occur far more often than their frequencies predict, and two words from unrelated fields far less. The rarest-first rule does not depend on the estimate, since it uses only the guaranteed bound $r_i \le f_1$. That is one reason it is the standard heuristic.

Mixed queries: estimating OR clauses

Many queries are not pure conjunctions. Queries in conjunctive normal form, an AND of OR clauses, are common in practice. Their clauses must be ordered too, but the size of an OR clause's result is not stored anywhere. It must be estimated.

The size of A OR B lies between two extremes. It is $\max(\mathit{df}_A, \mathit{df}_B)$ if one term's documents include all of the other's, and $\mathit{df}_A + \mathit{df}_B$ if the two never co-occur. The usual estimate is the sum, a conservative upper bound (Manning, Raghavan, and Schütze, 2008, §1.3). If the collection size $N$ is known and the terms are assumed independent, inclusion and exclusion give a closer estimate:

$$|A \cup B| \approx \mathit{df}_A + \mathit{df}_B - \frac{\mathit{df}_A \, \mathit{df}_B}{N}.$$

The last term subtracts the documents expected to contain both. For rare terms the correction is negligible, and the sum serves as well.

How good are these estimates on real text? On the example below the sum is off by as much as 36 percent, and both estimates still put the clauses in the right order. The Cranfield collection (Cleverdon, 1967) has 1,400 abstracts of aerodynamics papers. Tokenized without stemming, as in phrase and proximity queries, it keeps singular and plural apart, so a searcher would join them with OR. Take the query

(wing OR wings) AND (swept OR sweep) AND (supersonic OR hypersonic)

The two estimates and the true clause sizes are:

Clause Document frequencies Sum Independence Actual
swept OR sweep 33 and 20 53 53 43
wing OR wings 181 and 124 305 289 224
supersonic OR hypersonic 267 and 170 437 405 409

Every estimate puts the clauses in the same order, and so does the truth. The plan evaluates swept OR sweep first and intersects it with wing OR wings, leaving 38 documents. Intersecting those with supersonic OR hypersonic leaves 13.

The sizes also show where independence fails. Wing and wings often share an abstract, so their union, 224, is well below even the independence estimate. The sum overestimates every clause but keeps the order. When one clause is much smaller than the others, as swept OR sweep is here, choosing it first matters as much as choosing the rarest term in a conjunction. The numbers come from tools/experiments/boolean/query_optimization.py.

Where to apply NOT

What about the negated parts of a query? An AND NOT can only remove documents, so it never makes a result larger. The question is when to apply it. Subtracting a common term's list early means reading that whole list, while subtracting it last, from a small intermediate result, lets the algorithm search the NOT list for just the few remaining documents. A reasonable plan therefore evaluates the positive part of a query first, in increasing order of size, and applies AND NOT clauses to the small result at the end. A standalone NOT, or an OR NOT, requires a complement against the whole collection, as explained in intersecting postings lists, and is best avoided or rewritten.

Rewriting queries

So far the query's structure was taken as given. Can it be changed? Boolean identities can turn a query into an equivalent one that is cheaper to evaluate:

  • De Morgan's laws. NOT (A OR B) equals NOT A AND NOT B. Inside a conjunction, the right-hand form becomes two AND NOT operations applied to an existing result, which avoids computing a complement.
  • Factoring. (A AND B) OR (A AND C) equals A AND (B OR C). The factored form reads A's list once instead of twice, and intersects it with one union instead of performing two intersections.
  • Flattening. Nested ANDs, such as A AND (B AND C), can be flattened into one conjunction, so that all its terms are ordered together by document frequency.

Example (factoring helps only when the shared term is the common one). Count the linear merge's upper bound, the sum of the two input lengths, for each operation, with the document frequencies used throughout: 1,000, 100,000 and 500,000.

Shared term $A$ $B$ $C$ (A AND B) OR (A AND C) A AND (B OR C)
500,000 1,000 100,000 1,202,000 702,000
1,000 100,000 500,000 604,000 1,201,000

In the first row the unfactored form merges $A$ with $B$ (501,000), $A$ with $C$ (600,000), and the two results, which are at most 1,000 and 100,000 long (101,000). The factored form merges $B$ with $C$ (101,000) and the union, at most 101,000 long, with $A$ (601,000). Reading the long list once instead of twice saves 500,000 comparisons. In the second row the shared term is the rare one. The unfactored form costs $101{,}000 + 501{,}000 + 2{,}000 = 604{,}000$. The factored form builds the union of the two long lists, up to 600,000 postings, and then merges it with $A$, for $600{,}000 + 601{,}000 = 1{,}201{,}000$. There the rewrite doubles the work. An optimizer should therefore apply it by estimated cost, not as a rule. These figures are bounds for the plain merge. With search-based intersection the rare-$A$ case favors the unfactored form even more, since each of its intersections then looks up only 1,000 docIDs.

These rewrites are applied to the query tree produced by the parser, before evaluation (see parsing and evaluating Boolean queries). Database systems apply far more elaborate rewriting with cost models. The same choice by estimated size returns when a metadata filter is combined with a nearest-neighbor search: Vector Search on Disk and with Filters shows that whether to filter before, after or during the search depends on the share of vectors that pass the filter. For most Boolean queries, though, ordering by document frequency and applying NOT last capture most of the available gain.

Beyond a single query

Several further optimizations apply across queries rather than within one:

  • Caching stores the results of frequent queries, and of frequent subexpressions such as a common OR clause, so that they are computed once (see search at scale).
  • Adaptive intersection decides as it goes whether to merge or to search, depending on how far apart the matches in the two lists turn out to be (Demaine, López-Ortiz, and Munro, 2000; Culpepper and Moffat, 2010).
  • Evaluating all lists simultaneously, rather than pairwise, avoids storing intermediate results at all. Ranked query processing generalizes this into document-at-a-time evaluation. There, MaxScore and WAND use an upper bound on each term's score to skip postings that cannot reach the top $k$, the ranked counterpart of skipping documents that cannot survive an intersection.

The principle behind all of them is the one this article began with. Use what the index knows about its own contents, especially the lengths of its postings lists, to avoid work whose result would be thrown away.

Worked problems

Problems 1 and 2 are Exercises 1.7 and 1.9 of the course text (Manning, Raghavan, and Schütze, 2008), restated in our own words. Problem 3 is posed here on the three terms of this article. The script checks every number.

Problem 1. Recommend a processing order for

(tangerine OR trees) AND (marmalade OR skies) AND (kaleidoscope OR eyes)

given these postings list sizes:

Term Postings
eyes 213,312
kaleidoscope 87,009
marmalade 107,913
skies 271,658
tangerine 46,653
trees 316,812

Solution. Evaluate kaleidoscope OR eyes first, intersect it with tangerine OR trees, and intersect the result with marmalade OR skies.

The query is a conjunction of three OR clauses, so the rule is the one for conjunctions, smallest operand first, applied to the clauses. A clause's size is not stored, so estimate it by the sum of its two document frequencies, as in the section on OR clauses. The true size lies between the larger of the two frequencies (if one term's documents contain the other's) and their sum (if the two never share a document):

Clause At least Estimate (sum), at most
kaleidoscope OR eyes 213,312 $87{,}009 + 213{,}312 = 300{,}321$
tangerine OR trees 316,812 $46{,}653 + 316{,}812 = 363{,}465$
marmalade OR skies 271,658 $107{,}913 + 271{,}658 = 379{,}571$

By the estimates the order is kaleidoscope OR eyes, then tangerine OR trees, then marmalade OR skies.

How much of that order is certain? Only one comparison. kaleidoscope OR eyes has at most 300,321 documents, fewer than the 316,812 that tangerine OR trees has at the least, so it is certainly the smaller of those two. The range of marmalade OR skies, from 271,658 to 379,571, overlaps both of the others, so the sizes alone cannot place it. By the lower limits it would even come second, before tangerine OR trees. The sum is a heuristic, as the section on OR clauses says. What is guaranteed is the consequence of starting with kaleidoscope OR eyes: every intermediate result has at most 300,321 documents.

The three unions must be computed whatever the order, at a cost of at most the 1,043,357 postings of the six lists. The order matters for the two intersections that follow.

Problem 2. For a conjunctive query, is processing the postings lists in order of increasing size guaranteed to be optimal? Explain why it is, or give an example where it is not.

Solution. It is not guaranteed. The rule looks only at the lengths of the lists, and the cost also depends on how the lists overlap, which the lengths do not reveal. Take three terms with the postings

A   1, 2, 3
B   1, 2, 3, 4
C   5, 6, 7, 8, 9

Increasing size gives the plan $(A \cap B) \cap C$. The merge of $A$ and $B$ finds $1 = 1$, $2 = 2$ and $3 = 3$, three comparisons, and returns 1, 2, 3. The merge of that result with $C$ compares 1, 2 and 3 with 5, three more comparisons, and returns nothing. The plan costs 6 comparisons.

The plan $(B \cap C) \cap A$ starts with the two longest lists. The merge of $B$ and $C$ compares 1, 2, 3 and 4 with 5, four comparisons, and returns nothing. Evaluation stops there, since an empty intermediate result settles the answer. The plan costs 4 comparisons, fewer than 6.

The example works because $B$ and $C$ share no document, which only the postings show. The rule's guarantee is weaker than optimality and still useful. It bounds every intermediate result by the shortest list, whatever the overlaps are.

Problem 3. With the frequencies of this article, $\mathit{df}_a = 1{,}000$, $\mathit{df}_b = 100{,}000$, $\mathit{df}_c = 500{,}000$ and $N = 1{,}000{,}000$, and assuming the terms occur independently, compare two plans for a AND b AND NOT c: applying the NOT last, and applying it first. Use the merge bound for each merge and a binary search for the final step where one input is small.

Solution. Applying the NOT last costs about 103,000 comparisons and applying it first about 602,000, for the same expected result of 50 documents.

NOT last. Merge $a$ with $b$: at most $1{,}000 + 100{,}000 = 101{,}000$ comparisons. The expected result has $\mathit{df}_a \mathit{df}_b / N = 100$ documents. For each of them, search for its docID in $c$'s list and keep the document if it is absent: about $100 \times \log_2 500{,}000 \approx 1{,}893$ comparisons. A document lacks $c$ with probability $1 - 500{,}000/1{,}000{,}000 = 0.5$, so about 50 documents remain. The total is about 102,893.

NOT first. Compute a AND NOT c by a difference merge: at most $1{,}000 + 500{,}000 = 501{,}000$ comparisons. The expected result has $1{,}000 \times 0.5 = 500$ documents. Merge it with $b$: at most $500 + 100{,}000 = 100{,}500$. The total is 601,500, and the result is the same 50 documents in expectation, $500 \times 100{,}000 / 1{,}000{,}000$.

The second plan reads the 500,000 postings of $c$ to remove 500 documents. The first consults $c$ only for the 100 documents that survived the positive part. Searching $c$ in the second plan would help too ($1{,}000 \times \log_2 500{,}000 \approx 19{,}000$ comparisons instead of 501,000), but the first plan would still do a tenth of that work at this step, because it brings ten times fewer documents to it.

What we have learned

Processing terms by increasing document frequency keeps every intermediate result small. With search-based intersection, the rarest-first plan cost about a hundredth of the worst plan. OR clauses need an estimated size, and the sum overestimated every Cranfield clause but ordered them correctly. NOT is best applied last, to a small result.

Every query so far has asked only whether a document contains a term. A searcher who types "swept wing" wants the words side by side. The next article, Phrase and Proximity Queries, shows how the index must change to answer that: it stores the position of every occurrence.

References

  • Cleverdon, C. W. (1967). The Cranfield tests on index language devices. Aslib Proceedings, 19(6), 173–194. record · 11 pages
  • Culpepper, J. S., and Moffat, A. (2010). Efficient set intersection for inverted indexing. ACM Transactions on Information Systems, 29(1), article 1. record · 3 pages
  • Demaine, E. D., López-Ortiz, A., and Munro, J. I. (2000). Adaptive set intersections, unions, and differences. In Proceedings of SODA 2000, 743–752. record · 2 pages
  • Manning, C. D., Raghavan, P., and Schütze, H. (2008). Introduction to Information Retrieval, section 1.3. Cambridge University Press. record · 102 pages

Reviewed: verified, 16 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 8 revisions