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.
- Solves
- Phrase query
- 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
- Model
- Word RAM
- Properties
- not comparison baseddeterministiciterative
- Evidence
- Proof sketchCode in 1 languages
Positional intersection answers a proximity query " within words of " 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 that are close to the current position of . The output is every triple with at position and at position of document and . 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 words checks the offsets . 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 . The output is the list of triples such that is in both lists, is a position of the first term in , is a position of the second term in , and , in increasing order. The distance is symmetric: the second term may stand before or after the first.
The algorithm
POSITIONAL-INTERSECT(p1, p2, k)- 1
i ← 0, j ← 0, R ← () - 2
while i < |p1| and j < |p2| do - 3
if doc(p1[i]) = doc(p2[j]) then - 4
W ← an empty queue, X ← pos(p1[i]), Y ← pos(p2[j]), b ← 0 - 5
for each x in X, in increasing order do - 6
while b < |Y| do - 7
if |x - Y[b]| ≤ k then add Y[b] at the end of W - 8
else if Y[b] > x then break ▷ Y[b] > x + k - 9
b ← b + 1 - 10
while W is not empty and |front(W) - x| > k do remove front(W) - 11
for each y in W do append (doc(p1[i]), x, y) to R - 12
i ← i + 1, j ← j + 1 - 13
else if doc(p1[i]) < doc(p2[j]) then i ← i + 1 - 14
else j ← j + 1 - 15
return R
Lines L2, L3, L13 and L14 are the merge of the document ids. Lines L6 to L9 move the index of forward until , add the close positions to and skip the positions less than . Line L10 drops from the front of the positions that were close to an earlier but are now more than before .
Example
Take the toy collection and the query "list within 2 words of a". The lists are list: , and a: , , , , . 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 | lines L6 to L9 | after line L10 | output | |
|---|---|---|---|---|
| 3 | 9 | $ | 9 - 7 | \le 2$: add 7; end of |
| 4 | 2 | $ | 2 - 0 | \le 2$: add 0; $ |
| 4 | 6 | end of | $ | 0 - 6 |
The inner loop makes 3 passes in total. With , the query "list within 1 word of sorted" returns : "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 .
For phrases, keep only the triples with . The phrase "posting list" gives and , 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 : every position of before is at most ; the position at , if any, is greater than ; and holds, in increasing order, exactly the positions before that are at least . These facts pass from one to the next because increases: a position that is less than is less than every later minus . Since every position from on is greater than , holds exactly the positions within distance of . 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 and , of lengths and , and an integer . Each list holds pairs with strictly increasing ids , and each position list is strictly increasing. The output is the set
listed in increasing order of . 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 passes of line L2 when .
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 in and at least in : line L13 drops an id less than every id left in , line L14 drops an id less than every id left in , and line L12 drops a common id after the block has handled it. Each pass adds one to or to or to both, and the loop stops when one index reaches the end, so there are at most passes. The full proof of the merge is on the merge-based list intersection page.
Lemma 2 (the window). Fix a common document with position lists and . After line L10 runs for , the queue holds exactly the positions with , in increasing order.
Proof. Let be the value of after the loop of lines L6 to L9 for , and put . We prove by induction on three facts after line L10 for :
- (a) every with satisfies ;
- (b) if , then ;
- (c) holds, in increasing order, exactly the with and .
The loop of lines L6 to L9 looks at for . Line L7 adds to when . Line L8 stops the loop, with no change to , when . Otherwise , and line L9 moves on with no change to . So each with is at most , and it is added to if and only if it is at least . Together with (a) for and , this gives (a) for , and the stop rule gives (b).
For (c), the elements of are added in increasing order of , and so of value, and line L10 removes only from the front, so stays increasing. Every element of is at most : those added for by line L7, and the older ones by (a) for . So the test of line L10 means , and since is increasing, line L10 removes exactly the elements less than . It remains to see that , before line L10, holds every with and . For this was shown above. For , (a) for gives , so by (c) for , is in after step if and only if . A satisfies this, because , so it is in . For , the facts for step 0 hold with and empty, and the same argument applies.
Finally, by (b) and because is increasing, every with is greater than . So the with are exactly the with and , which is by (c).
Theorem 1 (correctness). POSITIONAL-INTERSECT returns , in increasing order of .
Proof. A triple of has common to both lists. By Lemma 1, the block of lines L4 to L11 runs for each common once, in increasing order of . In it, line L11 appends for , which by Lemma 2 are exactly the with , in increasing order, for each in increasing order.
Theorem 2 (cost). Let be the total length of the position lists of the two terms in their common documents, and let . The algorithm runs in time. The passes of line L6 number at most , and the queue holds at most positions.
Proof. Lemma 1 bounds the passes of line L2 by . In a common document, each pass of line L6 either moves forward, at most times, or stops the loop at line L8, at most once for each . So the passes are at most for this document, and at most in total. Each position of enters at most once, so line L10 removes at most elements in this document. Line L11 does one step for each output triple. By Lemma 2, holds distinct integers of the range after line L10, so at most of them.
Theorem 3 (phrases). For a phrase of terms with positional lists , the function phrase_matches of the code returns exactly the pairs such that stands at position of for each , in increasing order.
Proof. The outer loop takes the largest current id and moves forward every list whose current id is less than . Such an id cannot be common, because the list with id has no smaller id left. When no list moves, all current ids equal , 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 be the positions of . The candidate list starts as and, for , keeps the with , where is increasing. This is the merge intersection of two increasing lists with one forward index : an element that the loop skips is less than every later candidate. So after round the list holds the with for all , and after the last round the matches of the phrase in . The number of passes of the inner loops is at most for round , and that of the outer loop is at most .
Complexity
- Ids. At most passes of line L2, as in the merge.
- Positions. In a common document with position lists and , each pass of line L6 moves forward or stops for one , so there are at most passes. Each position of enters and leaves at most once. In total, for the positions of the two terms in the common documents.
- Output. Line L11 does one step for each triple, so . The output can be as large as in one document.
- Total. time. The queue holds distinct positions in , so at most of them.
- Phrases. For a phrase of words, the code intersects the document lists, then the position lists after subtracting the offset from the positions of word . Each round is a merge of two increasing lists, so a common document costs at most steps.
Properties
- Exact. It finds every pair within distance , 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 , then .
- Not a comparison algorithm. The test uses the difference of two positions, which needs integer positions.
Variants and improvements
- Phrases of words. Word of the phrase must stand at . Subtract from the positions of word and intersect the shifted lists, as the code does. Starting from the rarest word makes the candidate list small early.
- Ordered proximity. For " within words after ", keep only ; the window is then the range .
- 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 of must not go back to 0 for each . With the reset, the inner loop costs in a document. It must go back to 0 for each new document, at line L4.
- The break condition. Line L8 stops only when . A stop at the first far position, also when it is less than , misses the close positions after it.
- Direction. has no direction, so also matches "list sorted" for the query "sorted list". A phrase needs .
- 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 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.
# 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 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
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag DS6M6D Edit this page History Report an error Markdown