A trigram index maps each distinct three-character slice to document IDs containing that slice. For a substring of at least three characters, every exact match must contain all of its trigrams, so intersecting those postings produces candidates. The intersection is only a filter: a document may contain the trigrams in different places or a different order. The final query checks the full fragment against original text before returning an ID. For fragments shorter than three characters, this implementation scans every document because it stores no shorter grams. Empty strings follow the host language's substring rule and match every stored document. Matching is exact by code point and case; there is no normalization layer or token boundary rule.
Trigram indexes: filter and verify substring candidates
Operational case
Records 103, 218, 347, and 492 contain pressure valve warning, pump pressure warning, valve sensor alert, and pressure pressure. Searching pressure returns 103, 218, and 492. Searching valve returns 103 and 347. The short fragment ps returns none after scanning the source strings. If separate fragments in a document happen to supply every trigram of a requested string, that record is still rejected unless the complete requested string occurs contiguously. This verification step is mandatory for correctness. The static index retains source text because a posting list alone cannot make that final decision.
Working Python program
from collections import defaultdict
class TrigramIncidentIndex:
def __init__(self, documents):
self.documents = dict(documents)
self.candidates = defaultdict(set)
for document_id, text in self.documents.items():
for start in range(len(text) - 2):
self.candidates[text[start:start + 3]].add(document_id)
def containing(self, fragment):
if len(fragment) < 3:
candidates = set(self.documents)
else:
grams = {fragment[start:start + 3] for start in range(len(fragment) - 2)}
postings = [self.candidates.get(gram, set()) for gram in grams]
postings.sort(key=len)
candidates = postings[0].copy()
for posting in postings[1:]:
candidates.intersection_update(posting)
return sorted(document_id for document_id in candidates if fragment in self.documents[document_id])
if __name__ == "__main__":
index = TrigramIncidentIndex({
103: "pressure valve warning",
218: "pump pressure warning",
347: "valve sensor alert",
492: "pressure pressure",
})
print("pressure=", index.containing("pressure"), sep="")
print("valve=", index.containing("valve"), sep="")
print("short=", index.containing("ps"), sep="")Output
pressure=[103, 218, 492]
valve=[103, 347]
short=[]Time, space, and tradeoff
For total text length C, construction takes O(C) expected hash work and up to O(C) document-gram references, in addition to retaining O(C) source text. A query creates O(L) trigrams for a length-L fragment, intersects their posting sets, and verifies candidates by substring search. Its worst case still scans substantial source text; short fragments always check every document. Python's substring-search cost depends on implementation and content, so no blanket constant-time claim is made. The index helps when grams sharply cut the candidate set. A suffix array or automaton serves different substring workloads and may be preferable when exact substring queries dominate and the text snapshot is stable.
Common Mistakes
- Do not return trigram candidates without checking the full fragment.
- Do not forget that a fragment shorter than three characters has no trigram filter.
- Do not normalize only the query or only the stored text.
- Do not treat a trigram match as a token or phrase match.
Connected lessons
- Hashing
- Data Structures
- Inverted indexes: intersect sorted incident postings
- Suffix arrays: indexed substring search and adjacent LCP
- Suffix automata: index substrings as text arrives
- Projects
- Quizzes
Compare its query with Inverted indexes: intersect sorted incident postings, Positional postings: find exact token phrases, Front-coded lexicons: store shared prefixes within sorted term blocks, then run the incident text index audit and index contract quiz.
BK-trees: search incident labels within edit distance adds a distinct structure contract to compare.
MinHash bands: retrieve incident candidates, then check exact overlap adds a related structure with a different operation boundary.
Editable substring fingerprints: join hashes in a segment tree examines a related structure with a different operation boundary.
