Intersecting Postings Lists

The core algorithms of query processing. The linear merge for AND traced pointer by pointer, with an interactive stepper, the corresponding merges for OR and AND NOT, why OR NOT is expensive, exact comparison counts, several lists intersected shortest first or all at once, and intersection by binary and galloping search when one list is much shorter, with a measured comparison of the three and a lower bound on the comparisons any method needs. Worked problems on AND NOT, OR NOT and arbitrary Boolean formulas.

This article gives the algorithms that answer AND, OR and AND NOT queries on sorted postings lists of lengths $x \le y$, with proved costs. The linear merge makes between $\min(x, y)$ and $x + y - 1$ docID comparisons. Galloping search into the longer list makes at most $2x \log_2(1 + y/x) + 3x$. No method that only compares docIDs can use fewer than $\log_3 \binom{y}{x} \ge x \log_3(y/x)$ comparisons in the worst case. In a measured experiment with $x = 100$ random docIDs, galloping beat the merge once the long list was about 3 times the length of the short one. A NOT that cannot be evaluated as part of an AND NOT costs time proportional to the collection size.

In the Boolean retrieval model, six plays fit in a bit vector. A real collection has millions of documents, and the index stores each term as a sorted postings list instead. To answer Brutus AND Calpurnia, a search engine looks up both terms in the dictionary, fetches their lists, and finds the documents that appear in both. With the lists from Manning, Raghavan, and Schütze (2008, §1.3),

Brutus     1, 2, 4, 11, 31, 45, 173, 174
Calpurnia  2, 31, 54, 101

the answer is documents 2 and 31. How can a program find them without comparing every entry of one list with every entry of the other? It walks the two sorted lists together and, at each step, discards the smaller of the two docIDs in front of it, which cannot occur later in the other list.

Postings intersection finds the documents common to two postings lists. It is the central operation of query processing. AND queries need it, and so do ranked systems that evaluate a query conjunctively, scoring only the documents that contain every query term. The rest of this topic, and the scoring algorithms of the next, build on the algorithms here.

First we trace the linear merge on these two lists and count its comparisons. Then we adapt the same walk to OR and AND NOT, and to more than two lists. Next we measure the merge against binary and galloping search for when one list is far shorter, and prove how few comparisons any method can use. Worked problems close the article.

The merge algorithm

Postings lists are sorted by document identifier, as described in the inverted index. Here is the idea in one sentence: because both lists are sorted, the smaller of the two docIDs under the pointers cannot match anything still ahead in the other list, so it can be discarded. Two lists can therefore be intersected in a single pass, by walking through both at once:

  1. Place a pointer at the start of each list.
  2. Compare the docIDs at the two pointers. If they are equal, the document is in both lists: add it to the result and advance both pointers.
  3. Otherwise, advance the pointer at the smaller docID. That document cannot appear in the other list, because everything from the other pointer onward is larger.
  4. Stop when either pointer passes the end of its list.

The reasoning in step 3 is the whole algorithm. Suppose the pointers show 4 in Brutus and 31 in Calpurnia. Every Calpurnia docID still ahead is at least 31. Every one already passed was matched or ruled out earlier. So 4 cannot be in Calpurnia, and it is safe to discard it and move on. The pointer at the larger docID must stay where it is, because 31 might still appear further along Brutus, as it does.

In Python:

def intersect(p1, p2):
    i = j = 0
    answer = []
    while i < len(p1) and j < len(p2):
        if p1[i] == p2[j]:
            answer.append(p1[i])
            i += 1
            j += 1
        elif p1[i] < p2[j]:
            i += 1
        else:
            j += 1
    return answer

The trace for Brutus and Calpurnia:

Step Brutus Calpurnia Action
1 1 2 1 < 2: advance Brutus
2 2 2 equal: add 2, advance both
3 4 31 advance Brutus
4 11 31 advance Brutus
5 31 31 equal: add 31, advance both
6 45 54 advance Brutus
7 173 54 advance Calpurnia
8 173 101 advance Calpurnia; Calpurnia is exhausted

Eight comparisons produce the answer 2, 31. The last two Brutus postings, 173 and 174, are never examined, because the shorter list ran out first.

The demo below steps through the same merge. Each press of Step performs one comparison. Compared entries are outlined, matches are filled, and the triangles mark the two pointers. The skip setting belongs to the next article, skip pointers; leave it at "no skips" for the plain merge.

Stepping the merge of Brutus and Calpurnia. The comparison count reaches 8 when Calpurnia runs out, with 173 and 174 never compared. The second example, a 49-entry list against four docIDs, needs 49 comparisons without skips.

Cost

Eight comparisons for twelve postings: how does the count grow with longer lists? No faster than the lists themselves: a merge of lists of lengths $x$ and $y$ makes at least $\min(x, y)$ and at most $x + y - 1$ comparisons. Here, and throughout the article, a comparison is one three-way comparison of the two docIDs under the pointers (smaller, equal or larger), one pass through the loop. The Python performs it as up to two tests.

The upper bound. Every comparison advances at least one pointer by one entry. A comparison is made only while both pointers are inside their lists, so before the last comparison the first pointer has advanced at most $x - 1$ times and the second at most $y - 1$ times. At most $(x - 1) + (y - 1)$ comparisons therefore come before the last one, and the total is at most $x + y - 1$.

The lower bound. The loop ends only when one pointer has passed the end of its list, which takes $x$ advances of the first pointer or $y$ of the second. A comparison advances each pointer at most once, so at least $\min(x, y)$ comparisons are needed.

The merge therefore takes $O(x + y)$ time, which is how the course text states the cost: for lists of lengths $x$ and $y$, the intersection takes $O(x + y)$ operations (Manning, Raghavan, and Schütze, 2008, §1.3).

This bound is a main reason postings are kept sorted. Intersecting unsorted lists would require sorting them first or building a hash table of one list. The course text does suggest a hash table, for the long list of a very unequal pair, but notes that such alternatives are difficult to combine with postings compression (Manning, Raghavan, and Schütze, 2008, §1.3).

Example (the two bounds for lengths 4 and 8). A merge of a list of 4 postings with a list of 8, the lengths of Calpurnia and Brutus, needs at least 4 comparisons and at most $4 + 8 - 1 = 11$. It needs 4 when the four short-list docIDs are all smaller than every docID in the long list, as with 1, 2, 3, 4 against 5, 6, ..., 12: four comparisons use up the short list. It needs 11 when the lists interleave to the very end, as with 2, 4, 6, 15 against 1, 3, 5, 7, 8, 9, 10, 16: no two docIDs are equal, so each comparison advances exactly one pointer, and the loop ends at the eleventh comparison, after 7 advances of the long list and 4 of the short one. The actual pair took 8. The script confirms that both bounds are attained for every pair of lengths up to 5, by merging every pair of lists of up to five docIDs drawn from 1 to 10.

The result of an intersection is never longer than the shorter input. That property is what makes the order of operations matter in multi-term queries, the subject of optimizing Boolean queries.

The other operations

AND is one of three operators. Do OR and NOT need new algorithms? They do not: union and difference use the same two-pointer walk, differing only in which documents they output.

OR (union). Output every docID from either list, once, in order. When the docIDs at the pointers are equal, output it once and advance both. Otherwise, output the smaller and advance its pointer. When one list is exhausted, copy the rest of the other. On the example lists:

Step Brutus Calpurnia Action
1 1 2 output 1, advance Brutus
2 2 2 equal: output 2 once, advance both
3 4 31 output 4, advance Brutus
4 11 31 output 11, advance Brutus
5 31 31 equal: output 31 once, advance both
6 45 54 output 45, advance Brutus
7 173 54 output 54, advance Calpurnia
8 173 101 output 101; Calpurnia is exhausted
copy the rest of Brutus: 173, 174

The result is 1, 2, 4, 11, 31, 45, 54, 101, 173, 174. The comparisons are the same eight as for AND, but the copying step means every posting of both lists is touched. The cost is again $O(x + y)$, and unlike intersection the result can be as long as both inputs combined, $x + y$ when the lists share nothing.

AND NOT (difference). For Brutus AND NOT Calpurnia, output the docIDs of the first list that do not appear in the second:

Step Brutus Calpurnia Action
1 1 2 1 < 2: output 1, advance Brutus
2 2 2 equal: drop 2, advance both
3 4 31 output 4, advance Brutus
4 11 31 output 11, advance Brutus
5 31 31 equal: drop 31, advance both
6 45 54 output 45, advance Brutus
7 173 54 173 > 54: advance Calpurnia
8 173 101 advance Calpurnia; Calpurnia is exhausted
copy the rest of Brutus: 173, 174

The result is 1, 4, 11, 45, 173, 174, again in $O(x + y)$.

Example (difference is not symmetric). AND and OR give the same result whichever list comes first, but Calpurnia AND NOT Brutus does not give the result of Brutus AND NOT Calpurnia. It returns 54, 101, the Calpurnia docIDs missing from Brutus, after the same eight comparisons. In the trace above, 54 is passed over without being output, because it is found only in the list being subtracted.

OR NOT. Brutus OR NOT Calpurnia matches every document that contains Brutus or lacks Calpurnia, which is nearly the entire collection. Computing it requires the complement of Calpurnia's list: every document in the collection except a few. Its cost is therefore proportional to the collection size $N$, not to the lengths of the postings lists. NOT on its own has the same problem. A system can therefore evaluate NOT cheaply only as part of AND NOT, and it may choose to reject or warn about queries whose result is dominated by a complement. A standalone NOT is computed by subtracting from a list of all documents, which is how my course assignment handled it (see parsing and evaluating Boolean queries). This site's own search box does the same: how this site's search works evaluates NOT as the complement against all pages, before ranking the matches with BM25F.

Multi-term queries

What about a query of more than two terms? A query A AND B AND C is evaluated as a sequence of pairwise intersections. Intersect two lists, then intersect the result with the third, and so on.

In order of increasing length

The order of the pairwise steps is free, since intersection is associative and commutative. The course text's rule is to process the terms in order of increasing document frequency, that is, shortest list first (Manning, Raghavan, and Schütze, 2008, §1.3, Figure 1.7). Its reason is a guarantee about sizes. An intersection is never longer than its shorter input, so once the shortest list has taken part, every intermediate result is at most as long as that list.

The text presents the rule as a heuristic, a point taken up in optimizing Boolean queries. It states the cost of a two-list merge as an upper bound, $O(x + y)$ operations, and the complexity of querying as a whole as $\Theta(N)$ in the number of documents. It gives no lower bound on the number of comparisons in terms of $x$ and $y$. One is proved below, under "How few comparisons can any method use?".

The textbook's own three-term example is Brutus AND Caesar AND Calpurnia. Its figure shows the first eight postings of Caesar, and we take them as the whole list:

Brutus     1, 2, 4, 11, 31, 45, 173, 174
Caesar     1, 2, 4, 5, 6, 16, 57, 132
Calpurnia  2, 31, 54, 101

Only document 2 is in all three. Calpurnia is the shortest list, and Brutus and Caesar tie at eight postings, so the rule allows two plans. The table gives every plan, with the comparisons of each merge:

Plan First merge Intermediate result Second merge Total
(Calpurnia AND Brutus) AND Caesar 8 2, 31 7 15
(Calpurnia AND Caesar) AND Brutus 10 2 2 12
(Brutus AND Caesar) AND Calpurnia 11 1, 2, 4 3 14

The first row's second merge, of 2, 31 with Caesar, runs as follows. 1 < 2, advance Caesar. 2 = 2, output 2. Then Caesar's 4, 5, 6 and 16 are each smaller than 31, four more comparisons. Finally 57 > 31 advances the intermediate list past its end. That is 7 comparisons.

On lists this short the totals say little: the two plans the rule allows cost 12 and 15, and the plan it forbids costs 14. What the rule guarantees is the size of the intermediate result, at most 4 here whichever long list comes second. That guarantee pays when the lists are long and the second step can search instead of scan. Optimizing Boolean queries measures that case, and one of its worked problems shows a query on which shortest-first is not the cheapest plan.

Intersecting many lists at once

An alternative evaluates all the lists together and never stores an intermediate result. Here is the idea in one sentence: keep one candidate docID, and ask each list in turn for its first docID at or after the candidate. The only operation a list must offer is that one, advance to a target docID.

  1. Take the first docID of the shortest list as the candidate. One list now agrees on it.
  2. Go to the next list, cycling through the lists in order of length, and advance it to its first docID at or after the candidate.
  3. If that docID equals the candidate, one more list agrees. When all the lists agree, output the candidate, move the current list one entry forward, and take the docID there as the new candidate.
  4. If that docID is larger, it becomes the new candidate, and only the current list agrees on it. No docID in between can be in the intersection, because the current list has none.
  5. Stop when any list runs out.

On the three lists, in the order Calpurnia, Brutus, Caesar:

Call List Advance to Entries passed Lands on Outcome
Calpurnia 2 first candidate: 2
1 Brutus 2 1 2 two lists agree
2 Caesar 2 1 2 all agree: output 2; next Caesar entry, 4, is the candidate
3 Calpurnia 4 2 31 new candidate 31
4 Brutus 31 2, 4, 11 31 two lists agree
5 Caesar 31 4, 5, 6, 16 57 new candidate 57
6 Calpurnia 57 31, 54 101 new candidate 101
7 Brutus 101 31, 45 173 new candidate 173
8 Caesar 173 57, 132 end of list stop

Eight calls return the answer, document 2. Document 31 came within one list of matching: Calpurnia and Brutus agreed on it, and Caesar jumped past it to 57.

The cost of the method is the cost of its advance calls, and the method does not fix how a call is carried out. A call can step through the entries it passes, as the table shows, or it can use the binary and galloping searches below, or the skip pointers of the next article. Each call hands the next list a target at least as large as the last, so every list is read front to back once.

This is the form used by document-at-a-time query processing in ranked systems, where each candidate document is scored completely before moving to the next. Dynamic pruning with MaxScore and WAND keeps one cursor per list in the same way and adds score upper bounds, so that a cursor can be advanced past documents that cannot reach the top $k$. Culpepper and Moffat (2010) compare the pairwise and the all-at-once methods on real queries. The trace is produced by intersect_many in the script, which also checks the method against a set intersection on 300 random groups of lists.

When one list is much shorter

The merge examines every posting of both lists in the worst case. That is wasteful when one list is short and the other long, for example a rare term with 4 postings and a common term with a million. Almost all of the long list's postings are passed over without matching anything. Can the short list look up its few docIDs instead of walking past everything? It can, when the long list allows a jump to any of its positions.

The alternative is to search instead of scan. For each posting of the short list, search for its docID in the long list. The course text suggests exactly this when the lengths differ greatly, as a sequence of binary searches in the long list (Manning, Raghavan, and Schütze, 2008, §1.3). A binary search halves the range it is looking in with every probe. Over a range of $n$ entries it makes $\lfloor \log_2 n \rfloor$ or $\lfloor \log_2 n \rfloor + 1$ probes, as the script confirms for every $n$ up to 69. Each search covers at most the whole list, so the intersection makes at most $x(\log_2 y + 1)$ probes of the long list, which is $O(x \log y)$. A probe is a docID comparison, and each search ends with one more, the test of whether the entry it found equals its target. For $x = 4$ and $y = 1{,}000{,}000$, each search makes at most $\lfloor \log_2 10^6 \rfloor + 1 = 20$ probes, so the intersection makes at most 80 probes, or 84 docID comparisons with the four equality tests, instead of up to a million. Each search can begin where the previous one ended, since the short list is sorted too, which trims the range a little.

Binary search spends the same $\log_2$ of the remaining list on every lookup, even when the next match is only a few entries ahead. Galloping, or exponential search, starts from the current position and probes the entries 0, 1, 3, 7, 15, and so on positions ahead, doubling its reach each time, until it finds a docID at least as large as the target. It then performs a binary search between its last two probes.

How many probes is that? Let the target's place be $\delta$ entries ahead of the current position. The doubling phase stops at its first probe $2^k - 1$ entries ahead with $2^k - 1 \ge \delta$, that is, at $k = \lceil \log_2(\delta + 1) \rceil$, after $k + 1$ probes. The binary search then covers the $2^{k-1} - 1$ entries strictly between the last two probes, and needs at most $k - 1$ probes. One search therefore costs at most $2k$ probes when $\delta \ge 1$ and one probe when $\delta = 0$:

$$\text{probes for one target} \;\le\; \max\bigl(1,\; 2 \lceil \log_2(\delta + 1) \rceil\bigr) \;\le\; 2\log_2(\delta + 1) + 2.$$

Now add up the $x$ searches. Write $\delta_i$ for the distance the $i$-th search covers. Each search starts where the previous one ended, so the distances add up to at most the length of the long list: $\delta_1 + \dots + \delta_x \le y$. The logarithm is concave, so the average of the logarithms is at most the logarithm of the average (Jensen's inequality):

$$\sum_{i=1}^{x} \log_2(\delta_i + 1) \;\le\; x \log_2\!\left(\frac{1}{x}\sum_{i=1}^{x} (\delta_i + 1)\right) \;\le\; x \log_2\!\left(1 + \frac{y}{x}\right).$$

The whole intersection therefore makes at most

$$2x \log_2\!\left(1 + \frac{y}{x}\right) + 2x$$

probes of the long list, whatever the lists contain. With the equality test that ends each search, at most $x$ of them, the bound on all docID comparisons is $2x \log_2(1 + y/x) + 3x$. Jensen's inequality is tight when all the $\delta_i$ are equal, so the logarithmic term $2x \log_2(1 + y/x)$ is approached when the short list's docIDs are spread evenly through the long list, about $y/x$ entries apart. For $y$ much larger than $x$ the bound on probes is close to

$$2x \log_2 \frac{y}{x}.$$

When the targets are bunched, most $\delta_i$ are small and the cost is far below the bound. Galloping therefore adapts to how the lists are distributed. It costs little when matches are close together and at most about twice a binary search of a gap of $y/x$ entries when they are far apart (Bentley and Yao, 1976; Demaine, López-Ortiz, and Munro, 2000). The script checks the one-target bound for every $\delta$ up to 3,000.

On the small example, searching for each Calpurnia docID in Brutus:

Target Binary search probes Galloping probes Found?
2 31, 4, 2, 1 1, 2 yes
31 45, 11, 31 4, 11, 45, 31 yes
54 173, 45 45, 173 no
101 174, 173 173 no
total 11 9

The totals count probes of the long list. One equality test per target adds 4 to each, for 15 and 13 docID comparisons. The binary search for 2 probes 31, 4 and 2, and then 1 as well. The search used here looks for the first docID at least as large as the target, and it keeps halving its range until the range is empty, so it does not stop early when a probe happens to equal the target. The galloping search for 31 starts at 4, where the search for 2 left off.

Both use more comparisons than the 8 of the merge. With lists of similar length there is nothing to skip, and searching only adds overhead. Searching pays off when the length ratio is large, and the experiment below finds how large.

Measuring the three methods

The figure measures where each method wins. A list of $x = 100$ random docIDs is intersected with lists of $y = 100$ to $y = 1{,}000{,}000$ random docIDs, drawn from a collection of ten million. The counts are docID comparisons: one per step of the merge, and one per probe of the long list for the two searches. The searches also need one test per short-list docID of whether the entry found equals it. Those 100 tests are left out, and they would add 100 to every search count. Each point is the median of 30 seeded runs, with the interquartile range shaded, though the bands are too narrow to see at most points.

Comparisons to intersect 100 docIDs with a longer list (for the two searches, probes of the long list), on log scales. Notice that the merge grows in step with the long list and reaches about a million, while binary and galloping search grow only logarithmically and stay below 3,000. At the left edge, with equal lengths, galloping matches the merge and binary search costs about three times as much.
Comparisons to intersect 100 docIDs with a longer list (for the two searches, probes of the long list), on log scales. Notice that the merge grows in step with the long list and reaches about a million, while binary and galloping search grow only logarithmically and stay below 3,000. At the left edge, with equal lengths, galloping matches the merge and binary search costs about three times as much.
$y$ Merge Binary search Galloping
100 199 571 211
1,000 1,091 876 640
10,000 10,022 1,202 1,256
100,000 99,429 1,530 1,922
1,000,000 994,616 1,860 2,588

The searches overtake the merge once the long list is a few times the short one. At $y = 300$ the script's medians are 398 for the merge, 718 for binary search and 374 for galloping. In this experiment galloping is therefore ahead of the merge from a ratio of about 3, and binary search from a ratio between 3 and 10.

The medians follow the formulas:

  • The merge makes close to $x + y$ comparisons. It makes slightly fewer because it stops when the short list runs out, typically within 1 percent of the end of the long one.
  • Binary search makes about $x \log_2 (y/e)$ probes, since each search covers only the part of the long list that remains. With the targets spread evenly, the search for the target a fraction $u$ of the way through the short list covers about $y(1 - u)$ entries and costs about $\log_2 y + \log_2(1 - u)$. The average of $\log_2(1 - u)$ over $u$ from 0 to 1 is $\int_0^1 \log_2(1 - u)\, du = -1/\ln 2 \approx -1.44$, so the total is about $x \log_2(y / e)$ probes for searches that each start where the previous one ended, taking a search of $n$ entries to cost about $\log_2 n$ probes. For $y = 10^{6}$, that is $100 \times \log_2 367{,}879 \approx 1{,}849$, against a measured 1,860.
  • Galloping makes about $2x \log_2(y/x)$ probes, close to the bound derived above, because random docIDs are spread nearly evenly. For $y = 10^{6}$, that is $200 \times \log_2 10{,}000 \approx 2{,}660$, and the proved bound on probes, $2x\log_2(1 + y/x) + 2x$, is 2,858. All 30 runs stay below the bound.

Galloping is never far from the better of the other two, as the table shows at both ends. When matches cluster, galloping's short searches make it cheaper than binary search. The script is tools/experiments/boolean/postings_intersection.py.

How few comparisons can any method use?

The measurements compare three methods with each other. They do not say whether a fourth could do much better. It cannot: no method that learns about docIDs only by comparing them can intersect a list of $x$ docIDs with a list of $y \ge x$ using fewer than

$$\log_3 \binom{y}{x} \;\ge\; x \log_3 \frac{y}{x}$$

comparisons in the worst case. Here is the idea in one sentence: on inputs where the short list lies entirely inside the long list, a correct method must have seen each docID of the short list equal to some entry of the long list, and for each of the $\binom{y}{x}$ ways the short list can sit inside the long one, the equalities seen are different, so the decision tree needs that many leaves.

The formal version. Count a comparison of two docIDs as one step with three possible outcomes: smaller, equal, larger. A deterministic method is then a decision tree. Each node compares two docIDs, the outcome chooses one of at most three branches, and each leaf reports an answer (it reports which entries of the short list are in the intersection, since the method knows the docIDs only through comparisons). If the method never makes more than $c$ comparisons, the tree has at most $3^c$ leaves.

Fix the long list as the even docIDs $2, 4, \dots, 2y$, and let the short list be any $x$ of them. There are $\binom{y}{x}$ such inputs. We show that no two of them reach the same leaf, so $3^c \ge \binom{y}{x}$.

Take one of these inputs, with short list $S$, and the leaf it reaches. Let $a$ be any docID of the short list. Suppose no comparison on the way to the leaf found $a$ equal to an entry of the long list. Change the input by replacing $a$ with the odd number $a + 1$. Both lists are still sorted lists of distinct docIDs. Every comparison on the path gives the same outcome as before. A comparison of $a$ with a different even number $b$ gave smaller or larger, and $a + 1$ is on the same side of $b$ as $a$ is, because $b$ differs from $a$ by at least 2. The comparison of $a$ with the long list's own entry $a$ was never made, by assumption. So the changed input reaches the same leaf and gets the same answer. But its correct answer is different: $a + 1$ is in the short list and not in the long one, so that entry of the short list has left the intersection. The method would be wrong on one of the two inputs. So on the way to the leaf, every docID of the short list was found equal to an entry of the long list. The path to the leaf thereby identifies the $x$ entries of the long list that make up $S$. Two inputs with different $S$ cannot follow the same path, and so reach different leaves. $\blacksquare$

For the second inequality, write $\binom{y}{x} = \frac{y}{x} \cdot \frac{y-1}{x-1} \cdots \frac{y-x+1}{1}$. Each factor $\frac{y - j}{x - j}$ is at least $\frac{y}{x}$ because $y \ge x$, so $\binom{y}{x} \ge (y/x)^x$.

Counting the outcomes a method must tell apart is a classical technique. Applied to merging two sorted lists, where the $\binom{x + y}{x}$ ways of interleaving them must be told apart by two-way comparisons, it gives the lower bound $\log_2 \binom{x + y}{x}$, the benchmark against which Hwang and Lin (1972) set their merging algorithm.

On the article's numbers:

Lengths $\binom{y}{x}$ $\log_3 \binom{y}{x}$ $x \log_3 (y/x)$
$x = 4$, $y = 8$ 70 3.87 2.52
$x = 100$, $y = 10^6$ about $10^{442}$ 926 838

For lengths 4 and 8 the bound says at least 4 comparisons, since $\binom{8}{4} = 70 > 3^3$. For $x = 100$ and $y = 10^6$, the experiment under "Measuring the three methods" measured medians of 1,860 probes for binary search and 2,588 for galloping. They have to be completed before they are compared with the bound. (The script's counts for the two searches are probes of the long list. They leave out one final test per target, of whether the docID found equals the target, 100 tests in all.) With the 100 tests, binary search is at 1,960 docID comparisons, 2.1 times the bound, and galloping at 2,688, 2.9 times. The bound is a worst case over all inputs of those lengths, and the measured lists are random ones, so the comparison is indicative only. What it settles is the shape of the cost. When $x$ is much smaller than $y$, about $x \log(y/x)$ comparisons are necessary, galloping's $2x\log_2(1 + y/x) + 3x$ is within a constant factor of that, and the merge's $x + y$ is not.

Searching in a real index

Two practical points limit pure search. Postings are usually compressed as sequences of gaps, which must be decoded sequentially, so arbitrary positions in a list cannot be reached directly. And lists stored on disk are cheapest to read in long sequential runs. Skip pointers solve the first problem. They store, at intervals, the docID and position needed to resume decoding partway through a list, so an intersection can jump ahead without decoding everything it skips. Some modern codes build this access into the layout itself. Modern postings compression traces how the upper bits of the Elias–Fano representation find the first docID at least as large as a target, the operation called NextGEQ, without separate skip pointers. That is the "advance to" operation of the all-at-once intersection above. Culpepper and Moffat (2010) compare these approaches in detail.

Summary

Operation Algorithm Cost for lists of length $x \le y$
AND Linear merge $O(x + y)$
AND, one list much shorter Binary search into the longer list $O(x \log y)$
AND, adaptive Galloping search into the longer list at most $2x \log_2(1 + y/x) + 2x$ probes of the long list, plus one equality test per target: $2x \log_2(1 + y/x) + 3x$ comparisons
AND, any method using comparisons (lower bound) at least $\log_3 \binom{y}{x} \ge x \log_3(y/x)$ comparisons in the worst case
AND of several lists Pairwise, shortest first, or all at once by advance calls every intermediate result at most the shortest list
OR Linear merge, output everything $O(x + y)$
AND NOT Linear merge, output first-list-only docIDs $O(x + y)$
NOT, OR NOT Complement against all documents $O(N)$

In practice

A practical rule for two lists of lengths $x \le y$ follows from the measurements above. Merge when $y/x$ is below about 3, and gallop into the longer list otherwise. The crossover of about 3 was measured for $x = 100$ random docIDs; clustered lists favor galloping further. For three or more lists, order them by length (the document frequencies in the dictionary give the lengths before any list is read), and either intersect pairwise from the shortest or advance every list to a common candidate.

Galloping needs one operation on the long list, the "advance to" of the all-at-once method: the first position at or after a given one that holds a docID at least as large as a target. In Python, with the probes 0, 1, 3, 7, ... positions ahead used in this article:

def next_geq(lst, lo, target):
    """First index k >= lo with lst[k] >= target, or len(lst) if there is none."""
    step = 1
    hi = lo
    while hi < len(lst) and lst[hi] < target:   # doubling phase
        lo = hi + 1
        hi = hi + step
        step *= 2
    hi = min(hi, len(lst))
    while lo < hi:                              # binary search in lst[lo:hi]
        mid = (lo + hi) // 2
        if lst[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo


def gallop_intersect(short, long):
    answer, pos = [], 0
    for d in short:
        pos = next_geq(long, pos, d)
        if pos == len(long):
            break
        if long[pos] == d:
            answer.append(d)
            pos += 1
    return answer

gallop_intersect([2, 31, 54, 101], [1, 2, 4, 11, 31, 45, 173, 174]) returns [2, 31]. Replacing the call to next_geq with a binary search over long[pos:] gives the binary-search method. The script tools/experiments/boolean/postings_intersection.py checks these two functions against a set intersection and contains the counting versions used for the measurements (search_and) and the all-at-once method (intersect_many). On compressed lists the same next_geq interface is provided by skip pointers or by the block structure of the code.

Worked problems

Problems 1, 2 and 3 are Exercises 1.4, 1.11 and 1.5 of the course text (Manning, Raghavan, and Schütze, 2008), restated in our own words and worked on this article's lists. Problem 4 is posed here. The script checks every count.

Problem 1. Let $x$ and $y$ be the lengths of the postings lists of Brutus and Caesar. Can (a) Brutus AND NOT Caesar and (b) Brutus OR NOT Caesar still be evaluated in time $O(x + y)$? If not, what can be achieved?

Solution. (a) Yes. The difference merge of the section on AND NOT walks both lists once. Its loop advances the pointers as the intersection's does, so the upper bound proved under "Cost" applies to it unchanged: at most $x + y - 1$ comparisons. The copying step at the end touches at most $x$ further postings, and the result has at most $x$ postings.

(b) No. The result contains every document that lacks Caesar. In a collection of $N$ documents that is at least $N - y$ documents, and writing the result down already takes that many steps, however it is computed. What can be achieved is time $O(N)$: walk the docIDs from 1 to $N$ with a pointer in each list, and output a docID unless it is in Caesar and not in Brutus. With the lists of this article, the documents left out are those in Caesar but not in Brutus, which are 5, 6, 16, 57 and 132. The result has $N - 5$ documents, whatever $N$ is.

Problem 2. How should the query x AND NOT y be evaluated? Why is the naive evaluation expensive? Write out a merge algorithm that evaluates it efficiently, and run it on Brutus AND NOT Caesar.

Solution. The naive evaluation follows the query's shape. It computes NOT y first, as a list of every document that lacks $y$, and then intersects that list with $x$. The complement has $N - \mathit{df}_y$ postings, close to the whole collection for most terms, so the cost is proportional to $N$ although the answer has at most $\mathit{df}_x$ postings.

The efficient evaluation never forms the complement. It walks the two lists together and keeps a docID of $x$ exactly when the walk shows that $y$ does not have it:

def and_not(p1, p2):
    i = j = 0
    answer = []
    while i < len(p1) and j < len(p2):
        if p1[i] == p2[j]:        # in both: drop it
            i += 1
            j += 1
        elif p1[i] < p2[j]:       # p2 has passed it: keep it
            answer.append(p1[i])
            i += 1
        else:                     # p2 is behind: catch up
            j += 1
    return answer + p1[i:]        # p2 is used up: the rest of p1 survives

The middle branch is correct for the reason the intersection is. If p1[i] is smaller than p2[j], every docID still ahead in p2 is larger, and every one already passed was smaller or was matched, so p1[i] is not in p2. On Brutus 1, 2, 4, 11, 31, 45, 173, 174 and Caesar 1, 2, 4, 5, 6, 16, 57, 132:

Step Brutus Caesar Action
1 1 1 equal: drop 1, advance both
2 2 2 equal: drop 2, advance both
3 4 4 equal: drop 4, advance both
4 11 5 11 > 5: advance Caesar
5 11 6 advance Caesar
6 11 16 11 < 16: output 11, advance Brutus
7 31 16 advance Caesar
8 31 57 output 31, advance Brutus
9 45 57 output 45, advance Brutus
10 173 57 advance Caesar
11 173 132 advance Caesar; Caesar is exhausted
copy the rest of Brutus: 173, 174

The result is 11, 31, 45, 173, 174, after 11 comparisons, within the bound $8 + 8 - 1 = 15$.

Problem 3. Extend the merge to arbitrary Boolean queries, taking (Brutus OR Caesar) AND NOT (Antony OR Cleopatra) as the example. What is its time complexity? Is it always linear, and linear in what?

Solution. Evaluate the query tree from the leaves up, with one merge per operator: the union merge for OR, the intersection merge for AND, and the difference merge for AND NOT. Each merge reads sorted lists and writes a sorted list, so its output can feed the next merge.

Take the six plays of the Boolean retrieval model with docIDs 1 to 6 in the order of the incidence matrix. The postings are Antony 1, 2, 6, Brutus 1, 2, 4, Caesar 1, 2, 4, 5, 6 and Cleopatra 1.

Operation Inputs Result Comparisons
Brutus OR Caesar 1, 2, 4 and 1, 2, 4, 5, 6 1, 2, 4, 5, 6 3
Antony OR Cleopatra 1, 2, 6 and 1 1, 2, 6 1
AND NOT 1, 2, 4, 5, 6 and 1, 2, 6 4, 5 5

The answer is documents 4 and 5, Hamlet and Othello, as the bit vectors gave in the worked problems of that article. The three merges make 9 comparisons, and the four lists hold 12 postings.

For the complexity, let $L$ be the total length of the postings lists of the query's terms, counting a term once for each time it appears. A merge costs at most the sum of the lengths of its two inputs. The result of an OR is at most as long as its inputs together, and the result of an AND or an AND NOT is no longer than its first input. By induction up the tree, the output of every node is therefore at most as long as all the leaf lists below it together, which is at most $L$. A query with $q$ operators then costs at most $q$ merges of at most $2L$ postings each, so the time is $O(qL)$: linear in the total length of the postings involved, for a query of fixed size.

It is linear in the lists, not in the collection, only as long as every NOT sits directly under an AND, where it becomes a difference. A NOT anywhere else, as in Problem 1(b), needs a complement and costs $O(N)$. Within those limits the work can still be reduced, by choosing the order of the operations (optimizing Boolean queries) and by searching or skipping in the long lists instead of scanning them.

Problem 4. Take the long list 2, 4, ..., 18 of $y = 9$ docIDs, and short lists of $x = 2$ docIDs. By the lower bound of this article, how many three-way comparisons must an intersection method make in the worst case? How many docID comparisons does the merge make on the short list 16, 18, and how many does galloping search make?

Solution. The bound is $\log_3 \binom{9}{2} = \log_3 36 \approx 3.26$, so at least 4 comparisons, since $3^3 = 27 < 36$.

The merge compares 16 with 2, 4, 6, 8, 10, 12 and 14, advancing the long list each time. It then finds 16 = 16 and 18 = 18. That is 9 comparisons, more than twice the bound.

Galloping search for 16 probes the entries 0, 1, 3 and 7 positions ahead, which hold 2, 4, 8 and 16. The last is not smaller than 16, so the doubling stops after 4 probes. The binary search then covers the three entries between the last two probes, 10, 12 and 14. It probes 12 and then 14, both smaller than 16, and so settles on 16: 6 probes in all, which is $2\lceil \log_2(7 + 1) \rceil$ for a target $\delta = 7$ entries ahead. The search for 18 starts at the next entry, which is 18 itself: 1 probe. Galloping makes 7 probes of the long list. With the test of each found docID against its target, two more, it makes 9 docID comparisons, the same as the merge on this input. A galloping search that used three-way probes and stopped at an equal docID would need only $4 + 1 = 5$: the fourth probe for 16 and the first for 18 land on the targets. The bound of 4 holds under any of these counts.

What we have learned

Sorted lists can be intersected in one pass, advancing the pointer at the smaller docID. The same walk computes OR and AND NOT, and later extends to positions for phrase queries, while a complement costs time proportional to the whole collection. Several lists are intersected shortest first, or all at once by advancing each list to a candidate docID. When one list is much shorter, searching beats scanning by orders of magnitude, and a counting argument bounds from below what any comparison method can achieve.

But search needs random access, and compressed lists must be decoded in order. The next article, Skip Pointers, shows how a list that is read in order can still let an intersection jump ahead.

References

  • Bentley, J. L., and Yao, A. C.-C. (1976). An almost optimal algorithm for unbounded searching. Information Processing Letters, 5(3), 82–87. record
  • 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
  • Hwang, F. K., and Lin, S. (1972). A simple algorithm for merging two disjoint linearly ordered sets. SIAM Journal on Computing, 1(1), 31–39. record
  • 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 · second opinion, 23 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 9 revisions