Data structurecore
Permuterm index
Also called permuterm vocabulary.
Indexes every rotation of each term with an end marker, so a wildcard query becomes a prefix lookup in a search tree.
- Time
- O(l (l log K + K)) delete · insertO(q log K + r log r + r l q) wildcard_more_starsO(q log K + r log r) wildcard_one_star
- Space
- O(K l) total
- Where
- K = the number of keys (L + n); L = the total length of the terms; l = the length of the longest term; n = the number of terms; q = the length of the query; r = the number of keys in the range of the query
- Model
- Word RAM
- Properties
- not concurrentnot externalnot persistent
- Evidence
- Proof sketchCode in 1 languages
A permuterm index is a search tree, or a sorted array, over all the rotations of the terms of a dictionary, where each term gets an end mark and becomes $-terminated: "hello" gives the keys "hello$", "ello$h", "llo$he", "lo$hel", "o$hell" and "$hello", each pointing back to "hello". A wildcard query X*Y matches exactly the terms that have a rotation starting with Y$X, so it becomes one prefix lookup. The price is space: a term of length has keys, and Manning, Raghavan and Schuetze report an almost ten-fold space increase for a dictionary of English terms.
In plain words
A search tree over sorted words finds all words that start with "mo" quickly, but not all words that end with "on" or that start with "m" and end with "n". The permuterm index fixes this by turning every word around in all possible ways. Add a mark at the end of the word, then move letters one at a time from the front to the back, and store each result.
Now "m*n" asks for the words that end with "n" and start with "m". Rotate the query in the same way so that the star is at the end: "n, mark, m". Every word that matches has a stored form that starts with exactly these letters, and no other word has one. So one search for a prefix answers the query, with no check afterwards.
The abstract type
The structure holds a set of terms, strings over an alphabet without the end mark $ and the wildcard *. The operations are:
- INSERT and DELETE: add or remove the term .
- MEMBER: tell if is in .
- WILDCARD: return the sorted list of the terms of that match , where each * stands for any string, also the empty one.
Representation
For each term , the rotations of the string $ are its keys, with . All keys of all terms are kept in one sorted array, each with a pointer to its term; since the $ marks where the term ends, a key names its term, and two terms never share a key. A balanced search tree or a trie of the keys does the same with cheaper updates. The array has keys, and stored as strings they take characters; stored as a pointer to the term and a rotation offset, they take words.
Operations
A prefix range is found by two binary searches: the first key at least , and the first key at least followed by a character TOP that sorts after every character of a key.
WILDCARD(I, q)- 1
if q has no * then return (q) if q$ is a key of I, else () - 2
X ← the part of q before its first *; Y ← the part after its last * - 3
p ← Y $ X ▷ the rotation of X*Y with the star last - 4
[lo, hi) ← the range of the keys that start with p - 5
if q has exactly one * then return the sorted terms of the keys in [lo, hi) - 6
return the sorted terms t of the keys in [lo, hi) with MATCHES(t, q) ▷ the middle pieces INSERT(I, t)- 7
if t$ is a key of I then return - 8
for each rotation r of t$ do insert (r, t) into the sorted array of keys
DELETE removes the keys of in the same way. MATCHES is the check of the k-gram index page: the first piece as a prefix, the last as a suffix, and the middle pieces in order between them.
The simple forms are cases of line L3: X* gives the prefix $X, X gives the prefix X$, and "mn" gives "n$m", as in Manning, Raghavan and Schuetze. In their query "moer", line L3 gives the prefix "er$"; its range holds "fishmonger" and "filibuster", and line L6 keeps "fishmonger". The code treats X as X*Y with empty X and Y, so its range is every key that starts with $, and line L6 checks every term; the variant below gives the direct lookup.
Example
Start empty and apply these operations.
| operation | terms | keys | notes |
|---|---|---|---|
| INSERT list | 1 | 5 | $list, ist$l, list$, st$li, t$lis |
| INSERT lists | 2 | 11 | adds the 6 rotations of lists$ |
| INSERT sort | 3 | 16 | adds $sort, ort$s, rt$so, sort$, t$sor |
| WILDCARD li*t | 3 | 16 | p = t$li, range (t$lis), answer (list) |
| WILDCARD *t | 3 | 16 | p = t$, range (t$lis, t$sor), answer (list, sort) |
| WILDCARD lss | 3 | 16 | p = s$l, range (s$list), MATCHES keeps lists |
| DELETE lists | 2 | 10 | its 6 keys are removed |
The query "li*t" shows the difference from the k-gram index: the range holds only the rotation of "list", and "lists" is never a candidate.
On the 50 terms of the toy collection the index has 284 keys with 1,834 characters in all, against 234 characters for the terms, a factor of 7.8. The query "sed" becomes the prefix "ed$s", whose range is the two keys "ed$sort" and "ed$spe", so the answer is sorted and speed. The query "st*d" becomes the prefix "d$s"; its range gives sorted and speed, and line L6 keeps sorted alone, because "speed" has no t between its s and its final d.
Correctness
The invariant is that the array is sorted, has no repeats, and holds exactly the rotations of $ for the terms of , each with its term; lines L9 and L10 and DELETE keep it. The key fact is that a term has a rotation starting with Y$X exactly when for some string , and then exactly one of its rotations starts with Y$X, because $ occurs once in each key. So for one star the range of line L4 holds one key for each answer and nothing else, and line L5 needs no filter. For more stars, X*Y is implied by the query, so the range holds every answer, and line L6 keeps exactly the answers. The full proof is in the proof file of this page.
Proof: A key range of the permuterm index holds exactly the terms with a given prefix and suffix, each oncefull
A term is a string, possibly empty, without the characters $, * and TOP, where TOP is a character that sorts after every character of a term and after $. For a term let ; the rotations of are the strings for . A query has no $ and no TOP, and each * in it stands for any string. Write with pieces that contain no *. A term matches if for some strings , and the answer over a vocabulary is .
Invariant (I). The array is strictly increasing and is the set , and is the term with a rotation of .
Lemma 1 (a key names its term). Each rotation of contains $ exactly once, and the rotations are distinct. A string is a rotation of for at most one term .
Proof. The string has one $, and a rotation keeps the multiset of characters. In the $ is at position , so different give different positions of $ and different strings. If is a rotation of , then rotating so that its $ comes last gives back, so determines .
So is well defined, and the number of keys is .
Lemma 2. The constructor makes (I) true, and INSERT and DELETE keep it.
Proof. The empty index has no keys and . By Lemma 1, the key is in if and only if , so line L9 tests membership correctly, and INSERT of a term of changes nothing. For , Lemma 1 says that no rotation of is a key yet. Line L10 inserts each rotation at the place that binary search finds for it, with at the same place of , which keeps strictly increasing and aligned. At the end is the set for . DELETE of finds each rotation of at the place that binary search gives, since it is present, and removes it with its owner; the keys of other terms stay.
Lemma 3 (the prefix range). If is sorted, PREFIX-RANGE returns such that starts with if and only if .
Proof. Here is the number of keys less than , and is the number of keys less than . A key that starts with is at least , and it is less than , because either or the character of after is less than TOP. A key is less than too. A key that does not start with is not a proper prefix of , so it first differs from at a position with , and then . In sorted order the keys are therefore: those less than , then those that start with , then the others, and the second group is the range .
Lemma 4 (the rotated query). Let and be strings without $. A term has a rotation of that starts with if and only if for some string , and then exactly one rotation of starts with .
Proof. If , then starts with . Conversely, let a rotation of start with . Its only $ is at position , and the rotation with $ at that position is , which needs . So is the suffix of of length , and is a prefix of , which is with the rest. Only one rotation has its $ at position , so it is the only one that starts with .
Theorem. If (I) holds, WILDCARD returns in increasing order, with no term twice.
Proof. If has no *, then is when and empty otherwise, and line L1 returns this by the membership test of Lemma 2.
Let have at least one *. Line L2 sets , the part before the first *, and , the part after the last *. Line L3 forms , and by Lemma 3 line L4 finds the keys that start with . By Lemmas 1 and 4, their owners are the terms with for some , each exactly once.
If has exactly one *, then , and matches exactly when . So the owners of the range are , each once, and line L5 returns them sorted with no filter.
If has two or more stars, every that matches has the form with , so is contained in the owners of the range, each once. Line L6 keeps the owners that pass MATCHES. That test is the same as on the k-gram index page, where it is proved to return true if and only if matches . So line L6 returns exactly , sorted, with no repeats.
Complexity
| operation | time | notes |
|---|---|---|
| MEMBER | one binary search with string comparisons | |
| INSERT, DELETE | keys, each placed by binary search and an array shift | |
| WILDCARD, one star | two binary searches, then sort the terms found | |
| WILDCARD, more stars | plus one MATCHES for each of the terms | |
| space | characters | words if a key is a term and an offset |
With a balanced tree in place of the array, an insertion costs . The query cost does not depend on the number of terms that do not match, which is the main gain over a scan of the dictionary.
Variants
- Infix queries. For X, take the keys that start with X: a term contains X exactly when some rotation of $ starts with X. A term can have several such keys, so remove repeats. On the toy vocabulary, "or" gives the four keys "or$f", "ore$sc", "ort$s" and "orted$s", which are the answer.
- Keys as offsets. Store each key as a pointer to the term and a rotation offset, and compare by reading the term from that offset. This cuts the space to words and makes each comparison a little slower.
- Compressed permuterm index. Ferragina and Venturini (2007), as cited by Manning, Raghavan and Schuetze, give an approach to the space blowup of the permuterm index. Sorted rotations are also the base of the Burrows-Wheeler transform and the FM-index, which store them in compressed form.
- Search tree and reverse search tree. For queries with one star only, a B-tree of the terms and one of the reversed terms answer X* and Y; XY is the intersection of the two results. This takes two copies of the dictionary, not , but needs an intersection.
When to use it
Use it when queries have one star, anywhere in the term, and must be fast and exact, and when the dictionary is small enough to store about ten times over. For long dictionaries with frequent updates or tight memory, the k-gram index is smaller, at the cost of a postfilter for every query. For queries with only a trailing star, a plain search tree is enough.
Pitfalls
- Rotating the query the wrong way. The prefix is the part after the last star, then $, then the part before the first star: "m*n" becomes "n$m", not "m$n".
- The end of the range. The range must end at the first key at least the prefix followed by a character above every key character. With a TOP that can occur in a term, keys are lost at the end of the range.
- The end mark in a term. A term that contains $ has two marks in its keys, and a key no longer names its term. Reject such terms.
- More than one star. The range of the outer pieces is a superset of the answer; skip line L6 and "std" returns "speed".
- Space. Each term is stored times, and as strings the keys of a term take characters. On the toy vocabulary the strings take 7.8 times the space of the terms.
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
permuterm_index.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/permuterm-index/. The authors are listed in prov/J3EW3B.jsonl.
"""A permuterm index of a vocabulary, for wildcard queries.
Each term t gets the end mark $, and every rotation of t$ is a key that
points back to t. The keys are kept in one sorted array. A query X*Y is
rotated to Y$X, and the answer is the set of terms whose keys start with
Y$X: one binary search for each end of the range. With more than one *,
the outer pieces give the range and a postfilter checks the middle pieces.
"""
import bisect
MARK = "$"
STAR = "*"
TOP = "\U0010ffff" # sorts after every letter of a term and after $
def rotations(t: str) -> list[str]:
"""Return the |t| + 1 rotations of t$, starting with t$ itself. Cost O(|t|^2)."""
s = t + MARK
return [s[i:] + s[:i] for i in range(len(s))]
def matches(t: str, q: str) -> bool:
"""Tell if t matches q, where * stands for any string. Cost O(|t| |q|) at most."""
pieces = q.split(STAR)
if len(pieces) == 1:
return t == q
first, last = pieces[0], pieces[-1]
if len(first) + len(last) > len(t) or not t.startswith(first) or not t.endswith(last):
return False
pos, end = len(first), len(t) - len(last)
for p in pieces[1:-1]:
i = t.find(p, pos, end)
if i < 0:
return False
pos = i + len(p)
return True
class PermutermIndex:
"""A sorted array of (key, term) pairs, one pair for each rotation of t$ of each term t.
Terms are strings without $, * and the character TOP; the empty term is
allowed. Invariant: keys is sorted, has no repeats, and holds exactly the
rotations of t$ for the terms t of the vocabulary; owner[i] is the term of
keys[i].
"""
def __init__(self) -> None:
self.keys: list[str] = []
self.owner: list[str] = []
self.count = 0
def __len__(self) -> int:
return self.count
def __contains__(self, t: str) -> bool:
key = t + MARK
i = bisect.bisect_left(self.keys, key)
return i < len(self.keys) and self.keys[i] == key
def insert(self, t: str) -> None:
"""Add the term t. Cost O(|t|) binary searches, plus O(|t| K) to shift the arrays of K keys."""
if MARK in t or STAR in t or TOP in t:
raise ValueError("a term has no $, * or TOP")
if t in self: # @line L9
return
for r in rotations(t): # @line L10
i = bisect.bisect_left(self.keys, r)
self.keys.insert(i, r)
self.owner.insert(i, t)
self.count += 1
def delete(self, t: str) -> None:
"""Remove the term t if it is present. Same cost as insert."""
if t not in self:
return
for r in rotations(t):
i = bisect.bisect_left(self.keys, r)
del self.keys[i]
del self.owner[i]
self.count -= 1
def prefix_range(self, p: str) -> tuple[int, int]:
"""Return the range [lo, hi) of the keys that start with p. Cost O(|p| log K)."""
return bisect.bisect_left(self.keys, p), bisect.bisect_left(self.keys, p + TOP)
def wildcard(self, q: str) -> list[str]:
"""Return the sorted list of the terms that match q, where * stands for any string.
Precondition: q has no $ and no TOP. Cost: O(|q| log K) for the range, plus
O(r log r) to sort the r terms found; with two or more *, also
O(|t| |q|) to check each term t of the range.
"""
if STAR not in q: # @line L1
return [q] if q in self else []
x, z = q[: q.index(STAR)], q[q.rindex(STAR) + 1 :] # @line L2
p = z + MARK + x # @line L3
lo, hi = self.prefix_range(p) # @line L4
c = self.owner[lo:hi]
if q.count(STAR) == 1: # @line L5
return sorted(c)
return sorted(t for t in c if matches(t, q)) # @line L6
def range_terms(self, q: str) -> list[str]:
"""Return the terms of the key range of q before any postfilter, sorted. Precondition: q has a *."""
x, z = q[: q.index(STAR)], q[q.rindex(STAR) + 1 :]
lo, hi = self.prefix_range(z + MARK + x)
return sorted(self.owner[lo:hi])
def check_invariant(self) -> None:
"""Raise AssertionError unless keys and owner hold exactly the rotations of the terms, sorted."""
assert len(self.keys) == len(self.owner)
assert all(self.keys[i] < self.keys[i + 1] for i in range(len(self.keys) - 1))
terms = {t for t in self.owner}
assert len(terms) == self.count
want = sorted((r, t) for t in terms for r in rotations(t))
assert want == list(zip(self.keys, self.owner))
test_permuterm_index.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/permuterm-index/. The authors are listed in prov/J3EW3B.jsonl.
import fnmatch
import random
import re
import pytest
import irtoy
from permuterm_index import PermutermIndex, matches, rotations
def scan(vocab, q):
"""The oracle: a direct scan of the vocabulary with fnmatch, checked against a regular expression."""
by_fn = sorted(t for t in vocab if fnmatch.fnmatchcase(t, q))
rx = re.compile(".*".join(re.escape(p) for p in q.split("*")))
assert by_fn == sorted(t for t in vocab if rx.fullmatch(t))
return by_fn
def build(terms):
idx = PermutermIndex()
for t in terms:
idx.insert(t)
idx.check_invariant()
return idx
def test_rotations_of_hello():
assert rotations("hello") == ["hello$", "ello$h", "llo$he", "lo$hel", "o$hell", "$hello"]
def test_examples_of_manning_raghavan_schuetze():
idx = build(["man", "moron", "moon", "melon", "fishmonger", "filibuster", "hello"])
assert idx.wildcard("m*n") == ["man", "melon", "moon", "moron"]
assert idx.wildcard("hel*") == ["hello"] and idx.wildcard("*llo") == ["hello"]
assert idx.wildcard("hello") == ["hello"]
# *mo*er: the key range of er$ holds both terms; the postfilter keeps one.
assert idx.range_terms("*mo*er") == ["filibuster", "fishmonger"]
assert idx.wildcard("*mo*er") == ["fishmonger"]
def test_worked_example_on_the_toy_vocabulary():
vocab = sorted({t for d in irtoy.DOCS for t in irtoy.tokenize(irtoy.DOCS[d])})
idx = build(vocab)
assert len(idx) == 50 and len(idx.keys) == 284
assert idx.wildcard("s*ed") == ["sorted", "speed"]
assert idx.wildcard("li*t") == ["list"]
assert idx.wildcard("*ing") == ["encoding", "posting"]
assert idx.wildcard("in*") == ["in", "index", "into", "inverted"]
assert idx.range_terms("s*t*d") == ["sorted", "speed"]
assert idx.wildcard("s*t*d") == ["sorted"]
lo, hi = idx.prefix_range("ed$s")
assert idx.keys[lo:hi] == ["ed$sort", "ed$spe"]
def test_one_star_needs_no_postfilter():
rng = random.Random(11)
for _ in range(300):
vocab = {"".join(rng.choice("abc") for _ in range(rng.randint(0, 6))) for _ in range(rng.randint(0, 25))}
idx = build(vocab)
for _ in range(10):
x = "".join(rng.choice("abc") for _ in range(rng.randint(0, 3)))
y = "".join(rng.choice("abc") for _ in range(rng.randint(0, 3)))
q = x + "*" + y
assert idx.range_terms(q) == scan(vocab, q)
def test_edge_cases():
idx = PermutermIndex()
assert idx.wildcard("*") == [] and idx.wildcard("a") == [] and idx.wildcard("a*b*c") == []
idx.insert("")
idx.insert("a")
idx.insert("a")
idx.check_invariant()
assert len(idx) == 2 and idx.keys == ["$", "$a", "a$"]
assert idx.wildcard("*") == ["", "a"] and idx.wildcard("") == [""] and idx.wildcard("a*a") == []
assert idx.wildcard("**") == ["", "a"] and idx.wildcard("*a*") == ["a"]
idx.delete("b")
idx.delete("")
idx.check_invariant()
assert idx.wildcard("*") == ["a"]
with pytest.raises(ValueError):
idx.insert("a$")
assert matches("abcb", "a*b*b") and not matches("ab", "a*b*b")
def test_random_operations_against_a_scan():
rng = random.Random(1976)
needed = 0
for _ in range(300):
idx = PermutermIndex()
model: set[str] = set()
letters = "ab" if rng.random() < 0.5 else "abcd"
for _ in range(40):
r = rng.random()
if r < 0.5:
t = "".join(rng.choice(letters) for _ in range(rng.randint(0, 6)))
idx.insert(t)
model.add(t)
elif r < 0.65 and model:
t = rng.choice(sorted(model))
idx.delete(t)
model.discard(t)
else:
pieces = ["".join(rng.choice(letters) for _ in range(rng.randint(0, 3))) for _ in range(rng.randint(1, 4))]
q = "*".join(pieces)
want = scan(model, q)
assert idx.wildcard(q) == want
if "*" in q:
cand = idx.range_terms(q)
assert set(want) <= set(cand)
needed += cand != want
idx.check_invariant()
assert sorted(set(idx.owner)) == sorted(model) and len(idx) == len(model)
# With two or more *, the range alone is often too large.
assert needed > 50
History
Manning, Raghavan and Schuetze credit Garfield (1976) with one of the first complete descriptions of the permuterm index. Witten, Moffat and Bell describe the same idea as a rotated lexicon and compare it with an index of n-grams of the lexicon.
References
- Christopher D. Manning, Prabhakar Raghavan and Hinrich Schuetze, Introduction to Information Retrieval, Cambridge University Press, 2008, Chapter 3, Section 3.2.1 (permuterm indexes, the end mark $ and the rotations of hello$, the query m*n rotated to n$m*, and the query *mo*er, answered by the range of er$ and a filter that keeps fishmonger and removes filibuster), Section 3.2.2 (the almost ten-fold space increase for a dictionary of English terms), and Section 3.5 (Garfield 1976 and Ferragina and Venturini 2007)
- Ian H. Witten, Alistair Moffat and Timothy C. Bell, Managing Gigabytes, Compressing and Indexing Documents and Images, second edition, Morgan Kaufmann, 1999, Chapter 4, Section 4.2 (partially specified query terms, with rotated lexicons compared with an index of n-grams and with a scan of the lexicon)
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 J3EW3B Edit this page History Report an error Markdown