Data structurecore
k-gram index
Also called character n-gram index.
Maps each character k-gram to the dictionary terms that contain it, for wildcard queries and spelling correction.
- Time
- O(k l + l P) delete · insertO(k q + C + c l q) wildcard
- Space
- O(L + n) total
- Where
- C = the total length of the lists of the query grams; L = the total length of the terms; P = the length of the longest list of the index; c = the number of candidate terms; k = the gram length; l = the length of the longest term; n = the number of terms; q = the length of the query
- Model
- Word RAM
- Properties
- not concurrentnot externalnot persistent
- Evidence
- Proof sketchCode in 1 languages
A k-gram index is a second index over the dictionary of an inverted index: for every string of consecutive characters, it lists the terms that contain that string. Each term is padded with an end mark, so "castle" becomes "$castle$" and has the 3-grams "$ca", "cas", "ast", "stl", "tle" and "le$". A wildcard query such as "re*ve" is answered by intersecting the lists of the grams it must contain, then by a postfilter that removes the terms that contain all the grams and still do not match.
In plain words
Cut every word of the dictionary into short overlapping pieces of three letters, with a mark for the start and the end. For each piece, keep the list of words that contain it. To find the words that match "re*ve", take the pieces the query says a match must have: it starts with "re" and ends with "ve". Words in all those lists are the candidates.
The pieces do not keep their order or their distance, so a candidate can have all of them and still not match. The query "red*" needs the pieces "start re" and "red", and "retired" has both, but it does not start with "red". So every candidate is checked against the query at the end. The index finds a short list of words to check, and the check gives the exact answer.
The abstract type
The structure holds a set of terms, each a nonempty string over an alphabet without the end mark $ and the wildcard *, for a fixed . The operations are:
- INSERT and DELETE: add or remove the term .
- WILDCARD: return the sorted list of the terms of that match , where each * in stands for any string, also the empty one.
- CANDIDATES: return the terms that contain every k-gram of the query, a superset of the answer. Used by itself for spelling correction, where a word is close to a term that shares many of its grams.
Representation
A sorted array of the terms, and a map from each k-gram to its list: the sorted array of the terms such that the gram occurs in the padded term $$. A term is in a list once, even if the gram occurs twice in it, and no list is empty. This is an inverted index whose documents are the terms and whose words are the grams, so the lists can be stored, compressed and intersected like posting lists. A term of length has at most distinct grams, so the lists hold at most entries.
Operations
The query cuts $$ at each * and takes the k-grams of the pieces. Grams that would cross a * are not known, so they are not used.
WILDCARD(I, q)- 1
G ← the distinct k-grams of the pieces of $q$, cut at each * - 2
if G is empty then C ← all the terms of I ▷ no gram: scan the dictionary - 3
else C ← the intersection of the lists of the grams of G, shortest list first - 4
R ← () - 5
for each term t of C, in sorted order do - 6
if MATCHES(t, q) then append t to R ▷ the postfilter - 7
return R INSERT(I, t)- 8
if t is in I.terms then return - 9
insert t into the sorted array I.terms - 10
for each distinct k-gram g of $t$ do insert t into the sorted list of g
MATCHES checks the first piece of as a prefix of , the last piece as a suffix, and the middle pieces in order between them, each at its leftmost place. DELETE undoes line L10 for each gram and removes a list when it becomes empty. The intersection on line L3 is a merge of sorted lists, so its cost is the total length of the lists.
Example
Start empty with and apply these operations.
| operation | terms | grams | entries | notes |
|---|---|---|---|---|
| INSERT list | 1 | 4 | 4 | $li, lis, ist, st$ |
| INSERT lists | 2 | 6 | 9 | $li, lis and ist now hold two terms |
| INSERT sort | 3 | 10 | 13 | |
| INSERT sorted | 4 | 13 | 19 | |
| INSERT speed | 5 | 17 | 24 | ed$ holds sorted and speed |
| WILDCARD li*t | 5 | 17 | 24 | G = {$li}, C = (list, lists), R = (list) |
| WILDCARD s*ed | 5 | 17 | 24 | G = {ed$}, C = R = (sorted, speed) |
| DELETE lists | 4 | 15 | 19 | the lists of ts$ and sts are removed |
| WILDCARD li* | 4 | 15 | 19 | R = (list) |
The query "li*t" shows why line L6 is needed: "t$" has only two characters, so the only gram is "$li", and "lists" is a candidate that does not end with t.
On the 50 terms of the toy collection, the index with has 192 grams and 234 entries. The query "sed" gives the 5 candidates compressed, expected, inverted, sorted and speed, and the postfilter keeps sorted and speed, so the inverted index returns the documents of either: , , , and . The query "sech" uses the grams "$se" and "ch$", and their intersection is "search" alone. The query "or" has no gram of length 3, so line L2 checks all 50 terms and keeps for, score, sort and sorted.
Correctness
The invariant is that the list of each gram holds exactly the terms of in which occurs, sorted, and that no list is empty; lines L8 to L10 and DELETE keep it. If matches , every piece of $$ is a substring of $$, so every gram of occurs in $$ and is in each list. So contains every answer, and line L6 keeps exactly the answers because MATCHES is correct. The inclusion can be strict, as "retired" for "red*" shows, so the postfilter cannot be dropped. The full proof is in the proof file of this page.
Proof: The k-gram index with its postfilter returns exactly the terms that match a wildcard queryfull
Fix . A term is a nonempty string without the characters $ and *. For a string , the -grams of are its substrings of length . The padded form of a term is . A query is a string without $, in which each * stands for any string, also the empty one. Write , with pieces that contain no *, and the number of stars. A term matches if for some strings . The answer to over a vocabulary is .
Invariant (I). The array is the vocabulary in increasing order without repeats, and for every string : if is a -gram of for some , then is the sorted list, without repeats, of all such ; otherwise has no list.
Lemma 1. The constructor makes (I) true, and INSERT and DELETE keep it.
Proof. The empty index has , no terms and no lists, so (I) holds. INSERT of a term already in stops at line L8 and changes nothing. Otherwise line L9 puts at its sorted place in , and line L10 takes each distinct -gram of once and inserts at its sorted place in the list of , creating the list if needed. Since was not in , it was in no list, so each of these lists stays sorted and without repeats and is now the list of all terms of whose padded form contains . The lists of other grams do not change, and does not contain those grams. So (I) holds for .
DELETE of a term not in does nothing. Otherwise it removes from and, for each distinct -gram of , removes from the list of , which contains by (I). A list that becomes empty is removed, because no term of has that gram. Other lists do not contain . So (I) holds for .
Lemma 2 (the candidates contain the answer). Let be the set of -grams of the strings (for , the single string ), as line L1 computes it. If matches , then every is a -gram of .
Proof. If , then , so each of the strings , , ..., is a substring of . A -gram of a substring of is a -gram of .
By (I), a term is in the list of exactly when is a -gram of its padded form. So after line L3, the candidate list is the sorted list of the terms such that every gram of is a gram of : the merge of sorted lists keeps exactly the common elements, in order, and the order of the merges does not change the result. When is empty, line L2 sets . In both cases Lemma 2 gives .
The inclusion can be strict. For and = red*, the gram set is , and the term retired contains both grams but does not start with red. So the postfilter of line L6 is needed.
Lemma 3 (the postfilter). MATCHES returns true if and only if matches .
Proof. For the term matches exactly when , which is the test of the code. Let . If matches , then starts with , ends with , and these two parts do not overlap, so ; and the middle pieces occur in this order, without overlap, inside the window . The code tests the first three facts directly. It remains to show that the greedy search of the middle pieces succeeds exactly when such an occurrence in order exists.
If the greedy search succeeds, it has found inside , each one starting at or after the end of the one before. Let the strings be the gaps between consecutive pieces; then , so matches .
Conversely, let the pieces occur in order in at the positions , with . Let be the position where the greedy search finds . We show by induction on . For , the search starts at the start of , and occurs at , so the leftmost occurrence is at . If , the search for starts at , and occurs at inside , so the search finds an occurrence at . So the greedy search never fails, and the code returns true.
Theorem. If (I) holds, WILDCARD returns in increasing order.
Proof. By Lemma 1 the index satisfies (I) after any sequence of operations. By Lemma 2 and the remark after it, the list of lines L2 and L3 is sorted and contains , and every element of is in . Lines L4 to L6 keep, in the order of , exactly the elements for which MATCHES is true, which by Lemma 3 are the elements of that match . Since , these are exactly the elements of , in increasing order.
Complexity
| operation | time | notes |
|---|---|---|
| INSERT, DELETE | at most grams; each insertion into a sorted array of length at most | |
| CANDIDATES | is the total length of the lists of the grams of the query | |
| WILDCARD | plus one MATCHES for each of the candidates | |
| WILDCARD, no gram | a scan of the dictionary | |
| space | entries | plus one key for each distinct gram |
With lists in balanced trees or with a rebuild in batches, insertion costs per term. The work of a query is in the lists, and the lists of common grams such as "$s" or "ing" are long; the shortest-first order of line L3 bounds the size of each intermediate result by the shortest list.
Variants
- Choice of k. Smaller gives fewer and longer lists, and more queries with at least one gram. On the toy vocabulary, gives 138 grams and 284 entries, gives 192 and 234, and gives 167 and 184.
- Grams for spelling correction. For a misspelled word, take the terms that share many of its grams, rank them by the Jaccard coefficient of the gram sets, then by edit distance. The q-gram lemma bounds how many grams two strings within edit distance must share, and q-gram filtering uses it.
- Positional grams. Store the offset of the gram in the term, so that the query can require two grams at a fixed distance; this removes some candidates before the postfilter.
- Grams over the text. Index the k-grams of the documents themselves, not of the terms. This supports substring search in languages without spaces between words.
When to use it
Use it to answer wildcard queries with a * anywhere, and to find candidates for spelling correction, with one index for both. It is smaller than a permuterm index, which stores every rotation of every term, but every query needs a postfilter, and a query with no gram falls back to a scan. For queries with only a trailing *, a trie or a search tree over the sorted dictionary is simpler and needs no filter.
Pitfalls
- Dropping the postfilter. The candidates of "red*" include "retired", and those of "li*t" include "lists". Always check each candidate against the query.
- Grams across a star. "sed" must not produce the gram "sed" or "se"; take grams only inside the pieces between the stars.
- Short pieces. A piece shorter than , such as "t$" for , gives no gram; a query such as "or" or "*s" then gives no gram at all and a full scan. Fall back on purpose and keep the scan cost in mind.
- The end mark in terms. A term that contains the mark breaks the invariant and the prefix checks. Reject such terms or choose a mark outside the alphabet.
- Repeated grams. A term such as "banana" has the gram "ana" twice. Insert the term into the list once, or the merge on line L3 gets duplicates.
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
k_gram_index.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/k-gram-index/. The authors are listed in prov/HHWFE5.jsonl.
"""A k-gram index of a vocabulary, for wildcard queries.
Each term t is padded as $t$, and every substring of k letters of the padded
term is a k-gram. The index maps each k-gram to the sorted list of the terms
that contain it. A query with the wildcard * is answered by intersecting the
lists of the k-grams of the query, then by a postfilter that keeps only the
terms that match the query.
"""
import bisect
MARK = "$"
STAR = "*"
def grams(s: str, k: int) -> list[str]:
"""Return the k-grams of s, in order, with repeats. Cost O(|s| k)."""
return [s[i : i + k] for i in range(len(s) - k + 1)]
def matches(t: str, q: str) -> bool:
"""Tell if the term t matches the query q, in which * stands for any string, also the empty one.
The first piece of q must be a prefix of t, the last piece a suffix, and the
middle pieces must occur in order in between, each at its leftmost place.
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
def intersect(a: list[str], b: list[str]) -> list[str]:
"""Merge-based intersection of two sorted lists. Cost O(|a| + |b|)."""
i = j = 0
out: list[str] = []
while i < len(a) and j < len(b):
if a[i] == b[j]:
out.append(a[i])
i += 1
j += 1
elif a[i] < b[j]:
i += 1
else:
j += 1
return out
class KGramIndex:
"""A vocabulary of terms with, for each k-gram, the sorted list of the terms that contain it.
Terms are nonempty strings without $ and *. Invariant: postings[g] is the
sorted list, without repeats, of the terms t of the vocabulary such that g
is a k-gram of $t$, and no list is empty.
"""
def __init__(self, k: int = 3) -> None:
if k < 1:
raise ValueError("k must be at least 1")
self.k = k
self.terms: list[str] = []
self.postings: dict[str, list[str]] = {}
def __len__(self) -> int:
return len(self.terms)
def __contains__(self, t: str) -> bool:
i = bisect.bisect_left(self.terms, t)
return i < len(self.terms) and self.terms[i] == t
def insert(self, t: str) -> None:
"""Add the term t. Cost O(|t| k) for the grams, plus O(L) to insert into each of their lists of length L."""
if not t or MARK in t or STAR in t:
raise ValueError("a term is a nonempty string without $ and *")
if t in self: # @line L8
return
bisect.insort(self.terms, t) # @line L9
for g in set(grams(MARK + t + MARK, self.k)): # @line L10
bisect.insort(self.postings.setdefault(g, []), t)
def delete(self, t: str) -> None:
"""Remove the term t if it is present. Same cost as insert."""
if t not in self:
return
self.terms.remove(t)
for g in set(grams(MARK + t + MARK, self.k)):
lst = self.postings[g]
lst.pop(bisect.bisect_left(lst, t))
if not lst:
del self.postings[g]
def query_grams(self, q: str) -> list[str]:
"""Return the distinct k-grams of $q$ that contain no *, sorted. Cost O(|q| k)."""
return sorted({g for piece in (MARK + q + MARK).split(STAR) for g in grams(piece, self.k)})
def candidates(self, q: str) -> list[str]:
"""Return the sorted terms that contain every k-gram of the query: a superset of the answer.
Cost: the sum of the lengths of the lists of the query grams, or the
whole vocabulary when the query has no k-gram.
"""
g = self.query_grams(q)
if not g:
return list(self.terms)
lists = sorted((self.postings.get(x, []) for x in g), key=len)
c = lists[0]
for lst in lists[1:]:
c = intersect(c, lst)
return c
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 $. Cost: that of candidates, plus O(|t| |q|) for each candidate t.
"""
g = self.query_grams(q) # @line L1
if not g: # @line L2
c = list(self.terms)
else:
lists = sorted((self.postings.get(x, []) for x in g), key=len) # @line L3
c = lists[0]
for lst in lists[1:]:
c = intersect(c, lst)
r: list[str] = [] # @line L4
for t in c: # @line L5
if matches(t, q): # @line L6
r.append(t)
return r # @line L7
def check_invariant(self) -> None:
"""Raise AssertionError unless the postings are exactly the k-grams of the terms, as sorted lists."""
assert self.terms == sorted(set(self.terms))
want: dict[str, set[str]] = {}
for t in self.terms:
for g in grams(MARK + t + MARK, self.k):
want.setdefault(g, set()).add(t)
assert set(want) == set(self.postings)
for g, ts in want.items():
assert self.postings[g] == sorted(ts)
test_k_gram_index.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/k-gram-index/. The authors are listed in prov/HHWFE5.jsonl.
import fnmatch
import random
import re
import pytest
import irtoy
from k_gram_index import KGramIndex, grams, matches
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("*")))
by_re = sorted(t for t in vocab if rx.fullmatch(t))
assert by_fn == by_re
return by_fn
def toy_index(k=3):
vocab = sorted({t for d in irtoy.DOCS for t in irtoy.tokenize(irtoy.DOCS[d])})
idx = KGramIndex(k)
for t in vocab:
idx.insert(t)
idx.check_invariant()
return idx, vocab
def test_grams_of_castle():
assert grams("$castle$", 3) == ["$ca", "cas", "ast", "stl", "tle", "le$"]
def test_examples_of_manning_raghavan_schuetze():
idx = KGramIndex(3)
for t in ["beetroot", "metric", "petrify", "retrieval", "relive", "remove", "retrieve", "retired", "red", "reduce"]:
idx.insert(t)
idx.check_invariant()
assert idx.postings["etr"] == ["beetroot", "metric", "petrify", "retrieval", "retrieve"]
assert idx.wildcard("re*ve") == ["relive", "remove", "retrieve"]
# red* has the grams $re and red, and so has retired: the postfilter removes it.
assert idx.query_grams("red*") == ["$re", "red"]
assert idx.candidates("red*") == ["red", "reduce", "retired"]
assert idx.wildcard("red*") == ["red", "reduce"]
def test_worked_example_on_the_toy_vocabulary():
idx, vocab = toy_index()
assert len(vocab) == 50 and len(idx.postings) == 192
assert sum(len(v) for v in idx.postings.values()) == 234
assert idx.query_grams("s*ed") == ["ed$"]
assert idx.candidates("s*ed") == ["compressed", "expected", "inverted", "sorted", "speed"]
assert idx.wildcard("s*ed") == ["sorted", "speed"]
assert idx.query_grams("li*t") == ["$li"]
assert idx.candidates("li*t") == ["list", "lists"]
assert idx.wildcard("li*t") == ["list"]
assert idx.wildcard("*ing") == ["encoding", "posting"]
assert idx.wildcard("se*ch") == ["search"]
assert idx.wildcard("*or*") == ["for", "score", "sort", "sorted"]
def test_sequence_of_operations():
idx = KGramIndex(3)
for t in ["list", "lists", "sort", "sorted", "speed"]:
idx.insert(t)
idx.check_invariant()
assert idx.postings["$li"] == ["list", "lists"]
assert idx.wildcard("li*t") == ["list"]
assert idx.wildcard("s*ed") == ["sorted", "speed"]
idx.delete("lists")
idx.check_invariant()
assert "ts$" not in idx.postings
assert idx.wildcard("li*") == ["list"]
def test_edge_cases():
idx = KGramIndex(3)
assert idx.wildcard("*") == [] and idx.wildcard("a") == []
idx.insert("a")
idx.insert("a")
idx.check_invariant()
assert len(idx) == 1 and idx.postings == {"$a$": ["a"]}
assert idx.wildcard("*") == ["a"] and idx.wildcard("a") == ["a"] and idx.wildcard("a*a") == []
assert idx.wildcard("**a**") == ["a"]
idx.delete("b")
idx.delete("a")
idx.check_invariant()
assert idx.postings == {} and idx.wildcard("*") == []
for bad in ["", "a$", "a*"]:
with pytest.raises(ValueError):
idx.insert(bad)
with pytest.raises(ValueError):
KGramIndex(0)
def test_matches():
assert matches("sorted", "s*ed") and not matches("sed", "se*ed") and matches("seed", "se*ed")
assert matches("abab", "a*b*b") and not matches("aba", "ab*ba") and matches("abba", "ab*ba*")
assert matches("abcb", "a*b*b") and not matches("ab", "a*b*b")
assert matches("x", "*") and matches("", "*") and not matches("x", "")
def test_random_operations_against_a_scan():
rng = random.Random(3)
needed = 0
for _ in range(300):
k = rng.randint(1, 4)
idx = KGramIndex(k)
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(1, 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
cand = idx.candidates(q)
assert set(want) <= set(cand)
needed += cand != want
idx.check_invariant()
assert idx.terms == sorted(model)
# The postfilter is needed: many queries have candidates that do not match.
assert needed > 100
History
Manning, Raghavan and Schuetze present the k-gram index for wildcard queries in Section 3.2.2 with the end mark, the intersection of the lists and the postfilter, and they use the same index again for spelling correction. They cite the study of Zobel and Dart (1995), which shows that k-gram indexing is very effective for finding candidates for a misspelled word but should be combined with a finer method such as edit distance. Witten, Moffat and Bell describe the same index of n-grams of the lexicon for partially specified query terms and compare it with rotated lexicons.
References
- Christopher D. Manning, Prabhakar Raghavan and Hinrich Schuetze, Introduction to Information Retrieval, Cambridge University Press, 2008, Chapter 3, Section 3.2.2 (k-gram indexes for wildcard queries, the end mark $, the 3-grams of castle, the list of the 3-gram etr, the query re*ve, the false match of retired for red* and the postfilter), Section 3.3.4 (k-gram indexes for spelling correction), and Section 3.5 (the study of Zobel and Dart 1995)
- 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, answered with an index of the n-grams of the lexicon, compared with rotated lexicons 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 HHWFE5 Edit this page History Report an error Markdown