How It Works
Reading this the first time
This page describes internals. On a first pass, three steps are enough: split text into n-grams, find candidate documents from those n-grams, and — if configured — verify candidates against stored normalized text.
MygramDB is an in-memory full-text search engine built around n-gram indexing. This page covers the core mechanisms: how text is indexed, how searches execute, and how the cache stays consistent.
N-gram Indexing
MygramDB tokenizes text into overlapping character sequences called n-grams. By default, it uses bi-grams (2 characters) for both ASCII text and CJK ideographs. Set kanji_ngram_size to use a different size for CJK ideographs.
What is tokenization?
Tokenization splits text into smaller units that can be indexed and searched. MygramDB uses no dictionary — it treats the character sequences themselves as n-grams, which is why it works the same across languages.
For example, the word search produces these bi-grams:
"search" → ["se", "ea", "ar", "rc", "ch"]A multibyte string like 東京都 produces bi-grams with the default settings:
"東京都" → ["東京", "京都"]Each n-gram maps to a posting list -- a sorted list of document IDs containing that n-gram. When a document is inserted, its text is tokenized and the document ID is added to each n-gram's posting list.
Document IDs (DocIDs) are uint32_t. A table dump holds at most 1 billion documents, so that is the practical per-table limit.
DocIDs are assigned in the order rows are indexed, so they follow primary-key order only while rows arrive in that order. A row inserted out of primary-key order is an exception, and the default sort works harder for it (see step 7 of the search pipeline). Above 65,536 exceptions the server logs primary_key_order_exceptions_high once. SYNC of the table reassigns DocIDs in primary-key order.
Posting List Compression
Not all n-grams appear with the same frequency. MygramDB chooses between two storage strategies based on list density during OPTIMIZE and list size during inserts:
| Strategy | When Used | Representation |
|---|---|---|
| Delta encoding | Sparse lists (typically density < 18% after OPTIMIZE) | Sorted IDs stored as fixed-width deltas |
| Roaring bitmap | Dense lists (typically density >= 18% after OPTIMIZE), or lists over 4,096 entries | Compressed bitmap via CRoaring library |
Density is defined as: (number of documents containing the n-gram) / (total documents in table).
The default 18% threshold and 0.5x hysteresis apply when OPTIMIZE chooses a representation. Inserts also convert a delta list to Roaring when it grows beyond 4,096 entries, regardless of density. A Roaring list converts back only when it has at most 4,096 entries and its density is below half the configured threshold (9% by default).
What is hysteresis?
Hysteresis means the threshold for switching back differs from the threshold for switching over, so a value hovering near the boundary does not flip state repeatedly. Here, OPTIMIZE uses 18% to switch to Roaring and 9% to switch back by default; the 4,096-entry limit also applies before it can switch back.
Delta encoding is compact for rare terms: it stores [100, 105, 200] as [100, 5, 95]. Roaring bitmaps are more efficient for common terms and enable SIMD-accelerated set operations (intersection, union) during search.
Search Pipeline
A search query flows through a series of stages:
Step by step:
Parse query -- Extract search terms, NOT terms, filter conditions, sort order, and pagination from the query.
Generate n-grams -- Each search term is normalized (Unicode NFKC via ICU) and tokenized into n-grams. Terms are sorted by estimated result size (smallest posting list first) to minimize intermediate result sets.
Intersect posting lists -- For each term, all of its n-gram posting lists are intersected (AND semantics). Then the per-term results are intersected across terms. Starting with the smallest set makes each subsequent intersection cheaper.
NOT filter -- Documents matching NOT terms are removed from the candidate set.
Column filters -- Filter conditions (e.g.,
category = 'science') are evaluated against the candidate set. Each condition can be decided in one of two ways. The bitmap path reads a bitmap from the filter index and intersects it with the candidates (or subtracts it, for!=andIS NULL). The per-document path fetches each candidate's stored value and compares it. Both give the same rows; they differ in cost.=,!=,IS NULLandIS NOT NULLalways run on bitmaps first, because the filter index already holds one bitmap per value and one per column for presence.- Ordering operators (
>,>=,<,<=) run after those, on the candidates that remain. With fewer than 4,096 candidates they are checked per document, since a few comparisons cost less than building a bitmap. From 4,096 candidates up they run on bitmaps: a range bitmap is built from the stored values inside the range, so its cost does not grow with the candidate count. - If a bitmap cannot be allocated, every condition falls back to the per-document check. The rows returned do not change.
Ordering matters for speed. In an in-process benchmark (Release build, 2,000,000 synthetic rows, Apple M5 Max, excluding network, protocol parsing and response formatting), a range covering about half of a high-cardinality column cost about 25 ms when 4,096 or more candidates remained. An equality that narrowed the set to a few thousand rows or fewer, followed by the same kind of range, took about 0.1 ms or less.
verify_text -- Optional post-filter that checks candidates against stored normalized text to eliminate false positives (see below).
Sort and paginate -- Results are sorted by the requested column and sliced to the requested OFFSET/LIMIT. The default order and
SORT <primary key>do not sort the whole match set. DocIDs mostly follow primary-key order already, so only the matches whose DocIDs are out of primary-key order are sorted and then merged with the rest. The page is the same one a full sort would return. If a primary key disappears mid-request (a concurrent delete), the request falls back to a full sort.
Queries without search text. When no search text precedes the first clause (SEARCH articles FILTER category = 'science', or COUNT and FACET the same way), there is nothing to tokenize. Steps 2 and 3 are skipped and the candidate set starts as every indexed row. FILTER conditions narrow it, and rows matching a NOT term are removed. The other steps run as usual. These queries neither consult nor fill the query cache; the answer always comes from the current index. They suit list pages and filtered counts.
A term that appears in several boolean branches is looked up once. Boolean evaluation, NOT filtering, synonym expansion, and verification share that one deduplicated lookup. Ordinary NOT clauses subtract matches from the candidate set; only an expression that needs the complement of a set enumerates all DocIDs. Under memory.verify_text, excluded terms are checked against stored text before a document is removed.
Text-heavy stages also have a fixed memory boundary. Candidate text is copied from the DocumentStore in bounded chunks, then the store lock is released before BM25 scoring, term-frequency counting, and text post-filters run. A large candidate set therefore does not require copying a large fraction of the corpus or holding the store lock throughout scoring.
verify_text Post-Filter
N-gram indexing is inherently approximate. A query for "quantum" generates bi-grams ["qu", "ua", "an", "nt", "tu", "um"]. Any document containing all six bi-grams is a candidate -- but some candidates are false positives:
What is a false positive?
A false positive is a document that survived the n-gram intersection but does not actually contain the search term. N-gram search collects candidates for speed; verify_text then checks normalized search terms against stored text according to the query expression.
| Document text | Contains all bi-grams? | Actually contains "quantum"? |
|---|---|---|
| "quantum mechanics" | Yes | Yes |
| "quantify antum" | Yes (qu, ua from "quantify"; an, nt, tu, um from "antum") | No |
Without verification, the query "quantum" on 1.1M Wikipedia articles returns every document that contains all six bi-grams, including the false positives. With verify_text: all, the normalized query is checked as a substring of each candidate's normalized text, leaving 1,961 matches. MySQL FULLTEXT returned the same count for this tested query; verify_text does not promise MySQL FULLTEXT semantics for all queries.
MygramDB retains normalized text in memory for features such as highlighting. When verify_text applies to a query, each candidate's stored text is checked for an actual substring match after the posting list intersection. False positives are discarded.
The published benchmark measured about 1.78 GB for the document and text stores together on 1.1M articles. verify_text controls candidate checking, not whether this text is stored. Three modes are available:
off(default) -- No post-filter verification; stored text remains available for highlighting.ascii-- Verifies only ASCII-only queries against stored text.all-- Checks normalized search terms against stored text for all eligible candidates.
Choosing a verify_text mode
Use verify_text: all when normalized substring verification is required. It does not make query semantics identical to MySQL FULLTEXT. Highlighting reads stored text in every mode. Choose off when n-gram candidates are sufficient and the extra text check is unnecessary.
Cache and Invalidation
MygramDB caches search results at the query level. Queries without search text neither consult nor fill the cache. For the rest, invalidation metadata records the dependencies of each entry, so a row change can remove affected entries without flushing a whole table.
What is cache invalidation?
Invalidation is discarding cached results when the underlying data changes, so a stale answer is never served. MygramDB looks at which n-grams a changed row touches and drops only the cached queries that involve them.
When a document is inserted, updated, or deleted via binlog replication:
- The changed document's text is tokenized into n-grams.
- Entries whose n-gram sets overlap with the change are invalidated. Entries with filters are also found directly when a filter column changes, and text-sensitive entries, such as NOT queries, are found directly when text changes.
- Unrelated queries remain cached.
Before caching a query result, MygramDB rechecks its pending invalidation registration or captured table data version. A matching write that invalidated the registration, or a version change during execution, rejects the insert and increments cache_rejections. With replication enabled, TCP request dispatch waits until the cache is wired to replication invalidation, so an untracked cache entry cannot be served during startup.
quantum: overlapping n-grams, so the entry is invalidatedalgorithm,database: unaffected, so the entries stay cached
The number of invalidated entries depends on the changed text, filters, and cached queries. A common term or a text-sensitive query can affect many entries; the invalidation manager targets matching dependencies instead of flushing the whole cache.
The invalidation manager keeps reverse indexes for n-grams, filtered entries, and text-sensitive entries. Each trigger visits only the entries it can affect rather than scanning the entire cache. Cache maintenance follows the same rule: each tick examines a bounded, resumable slice of the LRU list, so expiry and recency work do not take one long exclusive sweep across every entry.
For benchmark results, see Benchmarks. For architectural details, see Architecture.