Algorithm Search⌘K

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
Properties
not concurrentnot externalnot persistent

A k-gram index is a second index over the dictionary of an inverted index: for every string of kk 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 VV of terms, each a nonempty string over an alphabet without the end mark $ and the wildcard *, for a fixed k≥1k \ge 1. The operations are:

  • INSERT(I,t)(I, t) and DELETE(I,t)(I, t): add or remove the term tt.
  • WILDCARD(I,q)(I, q): return the sorted list of the terms of VV that match qq, where each * in qq stands for any string, also the empty one.
  • CANDIDATES(I,q)(I, q): 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 tt such that the gram occurs in the padded term $tt$. 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 ℓ\ell has at most ℓ+3−k≤ℓ+2\ell + 3 - k \le \ell + 2 distinct grams, so the lists hold at most L+2nL + 2n entries.

Operations

The query cuts $qq$ at each * and takes the k-grams of the pieces. Grams that would cross a * are not known, so they are not used.

  1. WILDCARD(I, q)
  2. 1G ← the distinct k-grams of the pieces of $q$, cut at each *
  3. 2if G is empty then C ← all the terms of I ▷ no gram: scan the dictionary
  4. 3else C ← the intersection of the lists of the grams of G, shortest list first
  5. 4R ← ()
  6. 5for each term t of C, in sorted order do
  7. 6if MATCHES(t, q) then append t to R ▷ the postfilter
  8. 7return R
  9. INSERT(I, t)
  10. 8if t is in I.terms then return
  11. 9insert t into the sorted array I.terms
  12. 10for each distinct k-gram g of $t$ do insert t into the sorted list of g

MATCHES checks the first piece of qq as a prefix of tt, 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 k=3k = 3 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 k=3k = 3 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: d1d_1, d2d_2, d4d_4, d5d_5 and d8d_8. 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 gg holds exactly the terms of VV in which gg occurs, sorted, and that no list is empty; lines L8 to L10 and DELETE keep it. If tt matches qq, every piece of $qq$ is a substring of $tt$, so every gram of GG occurs in $tt$ and tt is in each list. So CC 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 k≥1k \ge 1. A term is a nonempty string without the characters $ and *. For a string ss, the kk-grams of ss are its substrings of length kk. The padded form of a term tt is $t$\$t\$. A query qq is a string without $, in which each * stands for any string, also the empty one. Write q=P0∗P1∗⋯∗Prq = P_0 * P_1 * \cdots * P_r, with pieces PiP_i that contain no *, and r≥0r \ge 0 the number of stars. A term tt matches qq if t=P0S1P1S2⋯SrPrt = P_0 S_1 P_1 S_2 \cdots S_r P_r for some strings S1,…,SrS_1, \ldots, S_r. The answer to qq over a vocabulary VV is A(q)={t∈V:t matches q}A(q) = \{t \in V : t \text{ matches } q\}.

Invariant (I). The array termsterms is the vocabulary VV in increasing order without repeats, and for every string gg: if gg is a kk-gram of $t$\$t\$ for some t∈Vt \in V, then postings[g]postings[g] is the sorted list, without repeats, of all such tt; otherwise gg has no list.

Lemma 1. The constructor makes (I) true, and INSERT and DELETE keep it.

Proof. The empty index has V=∅V = \emptyset, no terms and no lists, so (I) holds. INSERT of a term tt already in VV stops at line L8 and changes nothing. Otherwise line L9 puts tt at its sorted place in termsterms, and line L10 takes each distinct kk-gram gg of $t$\$t\$ once and inserts tt at its sorted place in the list of gg, creating the list if needed. Since tt was not in VV, it was in no list, so each of these lists stays sorted and without repeats and is now the list of all terms of V∪{t}V \cup \{t\} whose padded form contains gg. The lists of other grams do not change, and tt does not contain those grams. So (I) holds for V∪{t}V \cup \{t\}.

DELETE of a term not in VV does nothing. Otherwise it removes tt from termsterms and, for each distinct kk-gram gg of $t$\$t\$, removes tt from the list of gg, which contains tt by (I). A list that becomes empty is removed, because no term of V∖{t}V \setminus \{t\} has that gram. Other lists do not contain tt. So (I) holds for V∖{t}V \setminus \{t\}. □\square

Lemma 2 (the candidates contain the answer). Let G(q)G(q) be the set of kk-grams of the strings $P0,P1,…,Pr−1,Pr$\$P_0, P_1, \ldots, P_{r-1}, P_r\$ (for r=0r = 0, the single string $P0$\$P_0\$), as line L1 computes it. If tt matches qq, then every g∈G(q)g \in G(q) is a kk-gram of $t$\$t\$.

Proof. If t=P0S1P1⋯SrPrt = P_0 S_1 P_1 \cdots S_r P_r, then $t$=$P0⋅S1⋅P1⋯Sr⋅Pr$\$t\$ = \$P_0 \cdot S_1 \cdot P_1 \cdots S_r \cdot P_r\$, so each of the strings $P0\$P_0, P1P_1, ..., Pr$P_r\$ is a substring of $t$\$t\$. A kk-gram of a substring of $t$\$t\$ is a kk-gram of $t$\$t\$. □\square

By (I), a term is in the list of gg exactly when gg is a kk-gram of its padded form. So after line L3, the candidate list CC is the sorted list of the terms t∈Vt \in V such that every gram of G(q)G(q) is a gram of $t$\$t\$: the merge of sorted lists keeps exactly the common elements, in order, and the order of the merges does not change the result. When G(q)G(q) is empty, line L2 sets C=VC = V. In both cases Lemma 2 gives A(q)⊆CA(q) \subseteq C.

The inclusion can be strict. For k=3k = 3 and qq = red*, the gram set is {$re,red}\{\$re, red\}, 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(t,q)(t, q) returns true if and only if tt matches qq.

Proof. For r=0r = 0 the term matches exactly when t=P0t = P_0, which is the test of the code. Let r≥1r \ge 1. If tt matches qq, then tt starts with P0P_0, ends with PrP_r, and these two parts do not overlap, so ∣P0∣+∣Pr∣≤∣t∣|P_0| + |P_r| \le |t|; and the middle pieces P1,…,Pr−1P_1, \ldots, P_{r-1} occur in this order, without overlap, inside the window W=t[∣P0∣..∣t∣−∣Pr∣)W = t[|P_0| .. |t| - |P_r|). 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 P1,…,Pr−1P_1, \ldots, P_{r-1} inside WW, each one starting at or after the end of the one before. Let the strings SiS_i be the gaps between consecutive pieces; then t=P0S1P1⋯SrPrt = P_0 S_1 P_1 \cdots S_r P_r, so tt matches qq.

Conversely, let the pieces occur in order in WW at the positions a1≤⋯a_1 \le \cdots, with ai+1≥ai+∣Pi∣a_{i+1} \ge a_i + |P_i|. Let gig_i be the position where the greedy search finds PiP_i. We show gi≤aig_i \le a_i by induction on ii. For i=1i = 1, the search starts at the start of WW, and P1P_1 occurs at a1a_1, so the leftmost occurrence is at g1≤a1g_1 \le a_1. If gi≤aig_i \le a_i, the search for Pi+1P_{i+1} starts at gi+∣Pi∣≤ai+∣Pi∣≤ai+1g_i + |P_i| \le a_i + |P_i| \le a_{i+1}, and Pi+1P_{i+1} occurs at ai+1a_{i+1} inside WW, so the search finds an occurrence at gi+1≤ai+1g_{i+1} \le a_{i+1}. So the greedy search never fails, and the code returns true. □\square

Theorem. If (I) holds, WILDCARD(q)(q) returns A(q)A(q) 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 CC of lines L2 and L3 is sorted and contains A(q)A(q), and every element of CC is in VV. Lines L4 to L6 keep, in the order of CC, exactly the elements tt for which MATCHES(t,q)(t, q) is true, which by Lemma 3 are the elements of CC that match qq. Since A(q)⊆C⊆VA(q) \subseteq C \subseteq V, these are exactly the elements of A(q)A(q), in increasing order. ■\blacksquare

Complexity

operation time notes
INSERT, DELETE O(kℓ+ℓP)O(k\ell + \ell P) at most ℓ+2\ell + 2 grams; each insertion into a sorted array of length at most PP
CANDIDATES O(kq+C)O(kq + C) CC is the total length of the lists of the grams of the query
WILDCARD O(kq+C+c ℓq)O(kq + C + c\,\ell q) plus one MATCHES for each of the cc candidates
WILDCARD, no gram O(nℓq)O(n \ell q) a scan of the dictionary
space O(L+n)O(L + n) entries plus one key for each distinct gram

With lists in balanced trees or with a rebuild in batches, insertion costs O(kℓ+ℓlog⁡P)O(k\ell + \ell \log P) 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 kk gives fewer and longer lists, and more queries with at least one gram. On the toy vocabulary, k=2k = 2 gives 138 grams and 284 entries, k=3k = 3 gives 192 and 234, and k=4k = 4 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 ee 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 kk, such as "t$" for k=3k = 3, 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.

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
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

  1. 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)
  2. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.delete
  • a full proof of time.insert
  • a full proof of time.wildcard
  • a full proof of space.total
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
  • at least three sources