Algorithm Search⌘K

Algorithmcore

Positional intersection

Also called positional merge for phrase queries.

Intersects two positional posting lists and, inside each common document, merges the position lists to find occurrences within distance k.

Time
O(m + n + P + z) worst
Space
O(k) extra
Where
P = the number of positions of the two terms in their common documents; k = the largest distance; m = the number of documents in the first list; n = the number of documents in the second list; z = the number of output triples
Properties
not comparison baseddeterministiciterative

Positional intersection answers a proximity query "w1w_1 within kk words of w2w_2" from a positional index. It merges the two document lists like the merge-based list intersection, and inside each common document it merges the two position lists with a small window of the positions of w2w_2 that are close to the current position of w1w_1. The output is every triple (d,x,y)(d, x, y) with w1w_1 at position xx and w2w_2 at position yy of document dd and ∣x−y∣≤k|x - y| \le k. Manning, Raghavan and Schuetze give it as PositionalIntersect. A phrase query is the case where the second word must stand exactly one place after the first, and a phrase of rr words checks the offsets 0,1,…,r−10, 1, \ldots, r - 1. The time is linear in the lengths of the lists, the positions in the common documents, and the output.

In plain words

First find the documents that hold both words, by walking the two sorted lists of document numbers side by side.

In each such document, both words come with a sorted list of places. Walk through the places of the first word in order. For each one, move a second finger along the places of the second word, and keep in a small queue every place of the second word that is close enough. Places that are now too far behind fall out of the front of the queue. Every place left in the queue gives one answer.

The second finger never moves back. Since the first word only moves forward, a place of the second word that is too far behind for this place is too far behind for all later ones.

The problem

The input is two positional lists, each a sequence of pairs (document id, positions) with strictly increasing ids and strictly increasing positions, and an integer k≥0k \ge 0. The output is the list of triples (d,x,y)(d, x, y) such that dd is in both lists, xx is a position of the first term in dd, yy is a position of the second term in dd, and ∣x−y∣≤k|x - y| \le k, in increasing order. The distance is symmetric: the second term may stand before or after the first.

The algorithm

  1. POSITIONAL-INTERSECT(p1, p2, k)
  2. 1i ← 0, j ← 0, R ← ()
  3. 2while i < |p1| and j < |p2| do
  4. 3if doc(p1[i]) = doc(p2[j]) then
  5. 4W ← an empty queue, X ← pos(p1[i]), Y ← pos(p2[j]), b ← 0
  6. 5for each x in X, in increasing order do
  7. 6while b < |Y| do
  8. 7if |x - Y[b]| ≤ k then add Y[b] at the end of W
  9. 8else if Y[b] > x then break ▷ Y[b] > x + k
  10. 9b ← b + 1
  11. 10while W is not empty and |front(W) - x| > k do remove front(W)
  12. 11for each y in W do append (doc(p1[i]), x, y) to R
  13. 12i ← i + 1, j ← j + 1
  14. 13else if doc(p1[i]) < doc(p2[j]) then i ← i + 1
  15. 14else j ← j + 1
  16. 15return R

Lines L2, L3, L13 and L14 are the merge of the document ids. Lines L6 to L9 move the index bb of YY forward until Y[b]>x+kY[b] > x + k, add the close positions to WW and skip the positions less than x−kx - k. Line L10 drops from the front of WW the positions that were close to an earlier xx but are now more than kk before xx.

Example

Take the toy collection and the query "list within 2 words of a". The lists are list: ⟨3:9⟩\langle 3: 9 \rangle, ⟨4:2,6⟩\langle 4: 2, 6 \rangle and a: ⟨1:3,6⟩\langle 1: 3, 6 \rangle, ⟨3:7⟩\langle 3: 7 \rangle, ⟨4:0,4⟩\langle 4: 0, 4 \rangle, ⟨6:0,4⟩\langle 6: 0, 4 \rangle, ⟨7:5⟩\langle 7: 5 \rangle. The merge of the ids takes 3 passes of line L2: 3 against 1, then 3, then 4. Document 4 is "a posting list is a sorted list of document ids".

document xx lines L6 to L9 WW after line L10 output
3 9 $ 9 - 7 \le 2$: add 7; end of YY
4 2 $ 2 - 0 \le 2$: add 0; $
4 6 end of YY $ 0 - 6

The inner loop makes 3 passes in total. With k=1k = 1, the query "list within 1 word of sorted" returns (4,6,5)(4, 6, 5): "sorted list" stands at positions 5 and 6 of document 4. The distance has no direction, so this triple is not a match of the phrase "list sorted", which needs y=x+1y = x + 1.

For phrases, keep only the triples with y=x+1y = x + 1. The phrase "posting list" gives (3,8,9)(3, 8, 9) and (4,1,2)(4, 1, 2), so documents 3 and 4. Document 5 holds "posting" and "lists", which is another token, so it is not a match. The phrase "a sorted list" of three words matches only at position 4 of document 4.

Correctness

The merge of the ids handles each common document once, in increasing order, as in the merge. Inside a document, the proof keeps three facts after line L10 for the current xx: every position of YY before bb is at most x+kx + k; the position at bb, if any, is greater than x+kx + k; and WW holds, in increasing order, exactly the positions before bb that are at least x−kx - k. These facts pass from one xx to the next because xx increases: a position that is less than x−kx - k is less than every later xx minus kk. Since every position from bb on is greater than x+kx + k, WW holds exactly the positions within distance kk of xx. The full proof, with the phrase form, is in the proof file below.

Proof: Positional intersection returns exactly the pairs of positions within distance k, in time linear in the input and the outputfull

The input is two positional lists p1p_1 and p2p_2, of lengths mm and nn, and an integer k≥0k \ge 0. Each list holds pairs (d,X)(d, X) with strictly increasing ids dd, and each position list XX is strictly increasing. The output is the set

A={(d,x,y):(d,X)∈p1, (d,Y)∈p2, x∈X, y∈Y, ∣x−y∣≤k},\mathcal{A} = \{(d, x, y) : (d, X) \in p_1,\ (d, Y) \in p_2,\ x \in X,\ y \in Y,\ |x - y| \le k\},

listed in increasing order of (d,x,y)(d, x, y). The line numbers are those of the main block of the page.

Lemma 1 (the documents). Lines L1, L2 and L12 to L14 run the inner block of lines L4 to L11 exactly once for each id common to both lists, in increasing order of the id, and make at most m+n−1m + n - 1 passes of line L2 when m,n≥1m, n \ge 1.

Proof. This is the merge of the two id lists, with the pairs in place of the ids. Before each test of line L2, every common id that has not been handled is at index at least ii in p1p_1 and at least jj in p2p_2: line L13 drops an id less than every id left in p2p_2, line L14 drops an id less than every id left in p1p_1, and line L12 drops a common id after the block has handled it. Each pass adds one to ii or to jj or to both, and the loop stops when one index reaches the end, so there are at most m+n−1m + n - 1 passes. The full proof of the merge is on the merge-based list intersection page. □\square

Lemma 2 (the window). Fix a common document dd with position lists X=(x1<⋯<xa)X = (x_1 < \cdots < x_a) and Y=(y0<⋯<yc−1)Y = (y_0 < \cdots < y_{c-1}). After line L10 runs for x=xix = x_i, the queue WW holds exactly the positions y∈Yy \in Y with ∣xi−y∣≤k|x_i - y| \le k, in increasing order.

Proof. Let bib_i be the value of bb after the loop of lines L6 to L9 for xix_i, and put b0=0b_0 = 0. We prove by induction on ii three facts after line L10 for xix_i:

  • (a) every yqy_q with q<biq < b_i satisfies yq≤xi+ky_q \le x_i + k;
  • (b) if bi<cb_i < c, then ybi>xi+ky_{b_i} > x_i + k;
  • (c) WW holds, in increasing order, exactly the yqy_q with q<biq < b_i and xi−k≤yq≤xi+kx_i - k \le y_q \le x_i + k.

The loop of lines L6 to L9 looks at yby_b for b=bi−1,bi−1+1,…b = b_{i-1}, b_{i-1} + 1, \ldots. Line L7 adds yby_b to WW when ∣xi−yb∣≤k|x_i - y_b| \le k. Line L8 stops the loop, with no change to bb, when yb>xi+ky_b > x_i + k. Otherwise yb<xi−ky_b < x_i - k, and line L9 moves on with no change to WW. So each yqy_q with bi−1≤q<bib_{i-1} \le q < b_i is at most xi+kx_i + k, and it is added to WW if and only if it is at least xi−kx_i - k. Together with (a) for i−1i - 1 and xi−1<xix_{i-1} < x_i, this gives (a) for ii, and the stop rule gives (b).

For (c), the elements of WW are added in increasing order of qq, and so of value, and line L10 removes only from the front, so WW stays increasing. Every element of WW is at most xi+kx_i + k: those added for xix_i by line L7, and the older ones by (a) for i−1i - 1. So the test ∣front(W)−xi∣>k|front(W) - x_i| > k of line L10 means front(W)<xi−kfront(W) < x_i - k, and since WW is increasing, line L10 removes exactly the elements less than xi−kx_i - k. It remains to see that WW, before line L10, holds every yqy_q with q<biq < b_i and yq≥xi−ky_q \ge x_i - k. For bi−1≤q<bib_{i-1} \le q < b_i this was shown above. For q<bi−1q < b_{i-1}, (a) for i−1i - 1 gives yq≤xi−1+ky_q \le x_{i-1} + k, so by (c) for i−1i - 1, yqy_q is in WW after step i−1i - 1 if and only if yq≥xi−1−ky_q \ge x_{i-1} - k. A yq≥xi−ky_q \ge x_i - k satisfies this, because xi>xi−1x_i > x_{i-1}, so it is in WW. For i=1i = 1, the facts for step 0 hold with b0=0b_0 = 0 and WW empty, and the same argument applies.

Finally, by (b) and because YY is increasing, every yqy_q with q≥biq \ge b_i is greater than xi+kx_i + k. So the y∈Yy \in Y with ∣xi−y∣≤k|x_i - y| \le k are exactly the yqy_q with q<biq < b_i and xi−k≤yq≤xi+kx_i - k \le y_q \le x_i + k, which is WW by (c). □\square

Theorem 1 (correctness). POSITIONAL-INTERSECT(p1,p2,k)(p_1, p_2, k) returns A\mathcal{A}, in increasing order of (d,x,y)(d, x, y).

Proof. A triple of A\mathcal{A} has dd common to both lists. By Lemma 1, the block of lines L4 to L11 runs for each common dd once, in increasing order of dd. In it, line L11 appends (d,x,y)(d, x, y) for y∈Wy \in W, which by Lemma 2 are exactly the y∈Yy \in Y with ∣x−y∣≤k|x - y| \le k, in increasing order, for each x∈Xx \in X in increasing order. ■\blacksquare

Theorem 2 (cost). Let PP be the total length of the position lists of the two terms in their common documents, and let z=∣A∣z = |\mathcal{A}|. The algorithm runs in O(m+n+P+z)O(m + n + P + z) time. The passes of line L6 number at most PP, and the queue holds at most min⁡(2k+1,∣Y∣)\min(2k + 1, |Y|) positions.

Proof. Lemma 1 bounds the passes of line L2 by m+n−1m + n - 1. In a common document, each pass of line L6 either moves bb forward, at most ∣Y∣|Y| times, or stops the loop at line L8, at most once for each x∈Xx \in X. So the passes are at most ∣X∣+∣Y∣|X| + |Y| for this document, and at most PP in total. Each position of YY enters WW at most once, so line L10 removes at most ∣Y∣|Y| elements in this document. Line L11 does one step for each output triple. By Lemma 2, WW holds distinct integers of the range [x−k,x+k][x - k, x + k] after line L10, so at most 2k+12k + 1 of them. ■\blacksquare

Theorem 3 (phrases). For a phrase of terms w0,…,wr−1w_0, \ldots, w_{r-1} with positional lists L0,…,Lr−1L_0, \ldots, L_{r-1}, the function phrase_matches of the code returns exactly the pairs (d,x)(d, x) such that wjw_j stands at position x+jx + j of dd for each jj, in increasing order.

Proof. The outer loop takes the largest current id toptop and moves forward every list whose current id is less than toptop. Such an id cannot be common, because the list with id toptop has no smaller id left. When no list moves, all current ids equal toptop, which is then common; after it, all indices move. So the loop handles each common id once, in increasing order, and stops when a list ends. In a common document, let XjX_j be the positions of wjw_j. The candidate list starts as X0X_0 and, for j=1,…,r−1j = 1, \ldots, r - 1, keeps the xx with x∈Xj−jx \in X_j - j, where Xj−j={y−j:y∈Xj}X_j - j = \{y - j : y \in X_j\} is increasing. This is the merge intersection of two increasing lists with one forward index bb: an element y−j<xy - j < x that the loop skips is less than every later candidate. So after round jj the list holds the x∈X0x \in X_0 with x+j′∈Xj′x + j' \in X_{j'} for all j′≤jj' \le j, and after the last round the matches of the phrase in dd. The number of passes of the inner loops is at most ∣Xj∣+∣X0∣|X_j| + |X_0| for round jj, and that of the outer loop is at most ∑j∣Lj∣\sum_j |L_j|. ■\blacksquare

Complexity

  • Ids. At most m+n−1m + n - 1 passes of line L2, as in the merge.
  • Positions. In a common document with position lists XX and YY, each pass of line L6 moves bb forward or stops for one xx, so there are at most ∣X∣+∣Y∣|X| + |Y| passes. Each position of YY enters and leaves WW at most once. In total, O(P)O(P) for the positions of the two terms in the common documents.
  • Output. Line L11 does one step for each triple, so O(z)O(z). The output can be as large as ∣X∣⋅min⁡(2k+1,∣Y∣)|X| \cdot \min(2k + 1, |Y|) in one document.
  • Total. O(m+n+P+z)O(m + n + P + z) time. The queue holds distinct positions in [x−k,x+k][x - k, x + k], so at most min⁡(2k+1,∣Y∣)\min(2k + 1, |Y|) of them.
  • Phrases. For a phrase of rr words, the code intersects the rr document lists, then the position lists after subtracting the offset jj from the positions of word jj. Each round is a merge of two increasing lists, so a common document costs at most ∑j∣Xj∣+(r−1)∣X0∣\sum_j |X_j| + (r - 1)|X_0| steps.

Properties

  • Exact. It finds every pair within distance kk, not only the closest one.
  • Forward only. Both levels read each list once from left to right, so it works on compressed lists that are decoded in order, and skip pointers can speed up the document level.
  • Output order. The triples come out in increasing order of document, then xx, then yy.
  • Not a comparison algorithm. The test ∣x−y∣≤k|x - y| \le k uses the difference of two positions, which needs integer positions.

Variants and improvements

  • Phrases of rr words. Word jj of the phrase must stand at x+jx + j. Subtract jj from the positions of word jj and intersect the shifted lists, as the code does. Starting from the rarest word makes the candidate list small early.
  • Ordered proximity. For "w2w_2 within kk words after w1w_1", keep only 0<y−x≤k0 < y - x \le k; the window is then the range (x,x+k](x, x + k].
  • Only the documents. If only the documents are needed, stop each document at its first match.
  • Biword index. An index of pairs of consecutive words answers two-word phrases with one lookup and longer phrases with candidate checks; Manning, Raghavan and Schuetze compare it with the positional index.
  • Index of collection positions. Buettcher, Clarke and Cormack number the tokens of the whole collection and find phrases with the methods next and prev, which jump from one candidate to the next with no merge of document ids.
  • Ranked proximity. Scores that reward close query words use the same merge to find the smallest window that holds all of them.

When to use it

Use it to answer phrase and proximity queries from a positional index. For common words, the position lists are long, and a biword or phrase index for the frequent pairs can save work. For phrases of any length on raw text, a suffix array avoids the merge.

Pitfalls

  • Resetting the second finger. The index bb of YY must not go back to 0 for each xx. With the reset, the inner loop costs ∣X∣⋅∣Y∣|X| \cdot |Y| in a document. It must go back to 0 for each new document, at line L4.
  • The break condition. Line L8 stops only when Y[b]>x+kY[b] > x + k. A stop at the first far position, also when it is less than x−kx - k, misses the close positions after it.
  • Direction. ∣x−y∣≤k|x - y| \le k has no direction, so k=1k = 1 also matches "list sorted" for the query "sorted list". A phrase needs y=x+1y = x + 1.
  • Stop words and tokenizing. If the index drops stop words, the positions of the words around them shift or have gaps, and the offsets of a phrase with a stop word in the middle are wrong unless the positions keep the gaps.
  • One word twice. For a query such as "a within 2 of a", each position is within distance 0 of itself. Exclude x=yx = y if a pair of two different occurrences is wanted.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

irtoy.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the information retrieval pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy collection of the information retrieval pages.

Eight short documents, four queries with graded judgments and one fixed
run. Tokens are the lower-case words split on spaces, with no stemming
and no stop words. The helper holds only the data and the statistics
tokenize, tf, df, cf, doc_len and avgdl. Scoring and metrics live on the
pages that define them.
"""

DOCS = {
    1: "binary search finds a key in a sorted array",
    2: "merge sort merges two sorted runs into one sorted array",
    3: "an inverted index maps each term to a posting list",
    4: "a posting list is a sorted list of document ids",
    5: "skip pointers speed up the merge of two posting lists",
    6: "a hash table finds a key in constant expected time",
    7: "search engines rank documents by a score for the query",
    8: "the sorted array of ids is compressed with gap encoding",
}

N = len(DOCS)

QUERIES = {
    "q1": "sorted array search",
    "q2": "posting list merge",
    "q3": "rank documents",
    "q4": "quantum circuit",
}

# Graded judgments: 2 is highly relevant, 1 is relevant, absent is 0.
QRELS = {
    "q1": {1: 2, 2: 1, 8: 1},
    "q2": {5: 2, 4: 1, 3: 1},
    "q3": {7: 2},
    "q4": {},
}

# A fixed run for the metric pages, as scores per query.
RUN = {
    "q1": {1: 2.0, 6: 2.0, 8: 1.5, 2: 1.0, 4: 1.0},
}


def tokenize(text):
    """Lower-case words split on spaces."""
    return text.lower().split()


_TOKENS = {d: tokenize(t) for d, t in DOCS.items()}


def tf(term, doc_id):
    """Number of times term occurs in document doc_id."""
    return _TOKENS[doc_id].count(term)


def df(term):
    """Number of documents that contain term."""
    return sum(1 for toks in _TOKENS.values() if term in toks)


def cf(term):
    """Number of occurrences of term in the whole collection."""
    return sum(toks.count(term) for toks in _TOKENS.values())


def doc_len(doc_id):
    """Number of tokens in document doc_id."""
    return len(_TOKENS[doc_id])


def avgdl():
    """Average document length in tokens."""
    return sum(len(toks) for toks in _TOKENS.values()) / N
positional_intersection.py 97 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/positional-intersection/. The authors are listed in prov/DS6M6D.jsonl.

from collections import deque
from typing import Any, Sequence

Entry = tuple[int, Sequence[int]]


def positional_intersect(
    p1: Sequence[Entry], p2: Sequence[Entry], k: int, stats: dict[str, int] | None = None
) -> list[tuple[int, int, int]]:
    """Return the triples (d, x, y) with d in both lists, x a position of the first term in d,
    y a position of the second term in d, and |x - y| <= k, in increasing order of (d, x, y).

    Each list holds (doc_id, positions) pairs with strictly increasing ids, and each
    positions list is strictly increasing. Precondition: k >= 0.

    If stats is a dict, it receives "doc_steps" (the steps of the merge of the ids) and
    "pos_steps" (the passes of the inner scan of the second position list).
    """
    out: list[tuple[int, int, int]] = []
    doc_steps = pos_steps = 0
    i = j = 0  # @line L1
    while i < len(p1) and j < len(p2):  # @line L2
        doc_steps += 1
        d1, d2 = p1[i][0], p2[j][0]
        if d1 == d2:  # @line L3
            xs, ys = p1[i][1], p2[j][1]
            window: deque[int] = deque()  # @line L4
            b = 0
            for x in xs:  # @line L5
                while b < len(ys):  # @line L6
                    pos_steps += 1
                    y = ys[b]
                    if abs(x - y) <= k:  # @line L7
                        window.append(y)
                    elif y > x:  # @line L8
                        break
                    b += 1  # @line L9
                while window and abs(window[0] - x) > k:  # @line L10
                    window.popleft()
                for y in window:  # @line L11
                    out.append((d1, x, y))
            i += 1  # @line L12
            j += 1
        elif d1 < d2:  # @line L13
            i += 1
        else:
            j += 1  # @line L14
    if stats is not None:
        stats["doc_steps"] = doc_steps
        stats["pos_steps"] = pos_steps
    return out  # @line L15


def phrase_matches(lists: Sequence[Sequence[Entry]], stats: dict[str, int] | None = None) -> list[tuple[int, int]]:
    """Return the pairs (d, x) such that term r of the phrase stands at position x + r of
    document d for each r, where lists[r] is the positional list of term r.

    The ids are intersected by a merge, and in each common document the position lists
    are intersected after the offset of each term is taken off. Precondition: at least
    one list. If stats is a dict, it receives "steps", the number of passes of the inner
    loops.
    """
    out: list[tuple[int, int]] = []
    steps = 0
    idx = [0] * len(lists)
    while all(idx[r] < len(lists[r]) for r in range(len(lists))):
        steps += 1
        top = max(lists[r][idx[r]][0] for r in range(len(lists)))
        moved = False
        for r in range(len(lists)):
            if lists[r][idx[r]][0] < top:
                idx[r] += 1
                moved = True
        if moved:
            continue
        cand = list(lists[0][idx[0]][1])
        for r in range(1, len(lists)):
            ys = lists[r][idx[r]][1]
            keep: list[int] = []
            b = 0
            for x in cand:
                while b < len(ys) and ys[b] - r < x:
                    steps += 1
                    b += 1
                steps += 1
                if b < len(ys) and ys[b] - r == x:
                    keep.append(x)
            cand = keep
        out.extend((top, x) for x in cand)
        for r in range(len(lists)):
            idx[r] += 1
    if stats is not None:
        stats["steps"] = steps
    return out
test_positional_intersection.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/positional-intersection/. The authors are listed in prov/DS6M6D.jsonl.

import random

import irtoy
from positional_intersection import phrase_matches, positional_intersect

Lists = dict[str, list[tuple[int, list[int]]]]


def positional_lists(docs: dict[int, list[str]]) -> Lists:
    index: Lists = {}
    for d in sorted(docs):
        for i, t in enumerate(docs[d]):
            lst = index.setdefault(t, [])
            if not lst or lst[-1][0] != d:
                lst.append((d, []))
            lst[-1][1].append(i)
    return index


def toy() -> tuple[dict[int, list[str]], Lists]:
    docs = {d: irtoy.tokenize(t) for d, t in irtoy.DOCS.items()}
    return docs, positional_lists(docs)


def brute_pairs(docs: dict[int, list[str]], s: str, t: str, k: int) -> list[tuple[int, int, int]]:
    out = []
    for d in sorted(docs):
        toks = docs[d]
        for x, a in enumerate(toks):
            if a != s:
                continue
            for y, b in enumerate(toks):
                if b == t and abs(x - y) <= k:
                    out.append((d, x, y))
    return out


def brute_phrase(docs: dict[int, list[str]], phrase: list[str]) -> list[tuple[int, int]]:
    r = len(phrase)
    return [(d, x) for d in sorted(docs) for x in range(len(docs[d]) - r + 1) if docs[d][x:x + r] == phrase]


def check_pair(docs: dict[int, list[str]], ix: Lists, s: str, t: str, k: int) -> None:
    p1, p2 = ix.get(s, []), ix.get(t, [])
    stats: dict[str, int] = {}
    got = positional_intersect(p1, p2, k, stats)
    assert got == brute_pairs(docs, s, t, k)
    if p1 and p2:
        assert stats["doc_steps"] <= len(p1) + len(p2) - 1
    common = {d for d, _ in p1} & {d for d, _ in p2}
    work = sum(len(ps) for d, ps in p1 if d in common) + sum(len(ps) for d, ps in p2 if d in common)
    assert stats["pos_steps"] <= work


def check_phrase(docs: dict[int, list[str]], ix: Lists, phrase: list[str]) -> None:
    lists = [ix.get(t, []) for t in phrase]
    stats: dict[str, int] = {}
    got = phrase_matches(lists, stats)
    assert got == brute_phrase(docs, phrase)
    bound = sum(len(lst) for lst in lists)
    sets = [{d for d, _ in lst} for lst in lists]
    common = set.intersection(*sets)
    for lst in lists:
        bound += sum(len(ps) for d, ps in lst if d in common)
    bound += (len(lists) - 1) * sum(len(ps) for d, ps in lists[0] if d in common)
    assert stats["steps"] <= bound
    if len(phrase) == 2:
        pairs = positional_intersect(lists[0], lists[1], 1)
        assert [(d, x) for d, x, y in pairs if y == x + 1] == got


def test_example() -> None:
    docs, ix = toy()
    assert phrase_matches([ix["posting"], ix["list"]]) == [(3, 8), (4, 1)]
    assert phrase_matches([ix["sorted"], ix["array"]]) == [(1, 7), (2, 8), (8, 1)]
    assert phrase_matches([ix["sorted"], ix["list"]]) == [(4, 5)]
    assert phrase_matches([ix["list"], ix["sorted"]]) == []
    assert phrase_matches([ix["merge"], ix["sort"]]) == [(2, 0)]
    assert phrase_matches([ix["a"], ix["sorted"], ix["list"]]) == [(4, 4)]
    assert positional_intersect(ix["list"], ix["sorted"], 1) == [(4, 6, 5)]
    assert positional_intersect(ix["posting"], ix["list"], 2) == [(3, 8, 9), (4, 1, 2)]
    assert positional_intersect(ix["sorted"], ix["a"], 3) == [(1, 7, 6), (4, 5, 4)]
    stats: dict[str, int] = {}
    got = positional_intersect(ix["list"], ix["a"], 2, stats)
    assert got == [(3, 9, 7), (4, 2, 0), (4, 2, 4), (4, 6, 4)]
    assert stats == {"doc_steps": 3, "pos_steps": 3}


def test_irtoy_all_pairs() -> None:
    docs, ix = toy()
    terms = sorted(ix)
    for s in terms:
        for t in terms:
            check_pair(docs, ix, s, t, 2)
            check_phrase(docs, ix, [s, t])
    rng = random.Random(24)
    for _ in range(300):
        check_phrase(docs, ix, [rng.choice(terms) for _ in range(rng.randint(1, 4))])
    for d in docs:
        toks = docs[d]
        for x in range(len(toks)):
            for r in (1, 2, 3, 4):
                if x + r <= len(toks):
                    check_phrase(docs, ix, toks[x:x + r])


def test_edges() -> None:
    assert positional_intersect([], [(1, [0])], 2) == []
    assert positional_intersect([(1, [0])], [(1, [0])], 0) == [(1, 0, 0)]
    assert positional_intersect([(1, [0, 10])], [(1, [5])], 4) == []
    assert phrase_matches([[]]) == []
    assert phrase_matches([[(2, [0, 3])]]) == [(2, 0), (2, 3)]
    assert phrase_matches([[(1, [0])], []]) == []
    docs = {1: ["a", "a", "a"]}
    ix = positional_lists(docs)
    check_phrase(docs, ix, ["a", "a"])
    check_pair(docs, ix, "a", "a", 1)


def test_random_collections() -> None:
    rng = random.Random(242)
    for _ in range(150):
        vocab = [f"w{i}" for i in range(rng.randint(1, 5))]
        ids = sorted(rng.sample(range(500), rng.randint(0, 25)))
        docs = {d: [rng.choice(vocab) for _ in range(rng.randint(0, 30))] for d in ids}
        ix = positional_lists(docs)
        for _ in range(6):
            s, t = rng.choice(vocab), rng.choice(vocab)
            check_pair(docs, ix, s, t, rng.randint(0, 6))
            check_phrase(docs, ix, [rng.choice(vocab) for _ in range(rng.randint(1, 4))])

History

Manning, Raghavan and Schuetze give the algorithm for two terms within kk words, and the phrase case, in their textbook of 2008, together with the biword index as the other way to answer phrases. Buettcher, Clarke and Cormack give phrase search on an index of collection positions in 2010.

References

  1. Christopher D. Manning, Prabhakar Raghavan and Hinrich Schuetze, Introduction to Information Retrieval, Cambridge University Press, 2008, Chapter 2, Section 2.4.2 (positional indexes, the algorithm PositionalIntersect for two terms within k words, and phrase queries as the case of adjacent positions), and Section 2.4.1 (biword indexes)
  2. Stefan Buettcher, Charles L. A. Clarke and Gordon V. Cormack, Information Retrieval, Implementing and Evaluating Search Engines, MIT Press, 2010, Chapter 2, Section 2.1 (phrase search on an index of positions with the methods next and prev)
  3. Justin Zobel and Alistair Moffat, Inverted files for text search engines, ACM Computing Surveys 38(2), Article 6, 2006, the evaluation of phrase and proximity queries on lists with word positions

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example