System Design Part 3 Storage basics

Full-Text Search and Inverted Indexes: Chinese Tokenization, BM25 Ranking, Index Sync, and the Authorization Boundary of Search

Bill.Lin 19 min read

System Design series Part 3-7 | Previous: Bloom Filters and HyperLogLog | Next: Geohash and Geospatial Indexes | Series map

Read first: Part 3-2 Indexes and B+Trees, Part 3-3 B-Tree vs LSM-Tree.

Scenario and problem

The talk platform has built up 200,000 talks, each with a title, speakers, a summary, and tags. The search box has to:

  1. Find the related talks when you type 微服務 (microservices), most relevant first
  2. Accept several words, such as 資料庫 交易 (database, transaction)
  3. Filter further by category and date
  4. Never show unpublished talks (drafts, internal sessions) in the results

The current implementation is WHERE title LIKE '%微服務%' OR summary LIKE '%微服務%'. As the indexes post mentioned, a LIKE that starts with a wildcard cannot use an index. Summaries average 1 KB, so every search compares 200,000 rows, about 200 MB of text; at a peak of 50 searches a second, that is 10 GB scanned every second.

Searching talks with LIKE1 / 4
Searching talks with LIKEUserTalk searchMySQLUserTalk search微服務Most relevant firstTalk searchMySQLLIKE '%微服務%'Leading wildcard, no indexTalk searchMySQLmatch 200k rowsAbout 200 MB each timeUserTalk searchMySQL50 searches/sscan 10 GB/sNo relevance ranking
  1. What the search box needs200,000 talks, each with a title, speakers, a summary, and tags. A user types 微服務 (microservices) and expects the related talks, most relevant first. They can also enter several words and filter by category and date, and unpublished talks must never show up.
  2. LIKE cannot use an indexThe current implementation is title LIKE '%微服務%' OR summary LIKE '%微服務%'. A LIKE that starts with a wildcard cannot use an index.
  3. 200 MB scanned per searchSummaries average 1 KB, so every search compares 200,000 rows, about 200 MB of text.
  4. 10 GB a second at peakAt a peak of 50 searches a second, that is 10 GB scanned every second. And LIKE has nothing to rank by: 微服務 in the title and a passing mention at the end of the summary look the same to it.

The simplest approach and its limits

The problem with LIKE is not just speed:

  • Nothing to rank by: 微服務 in the title and a passing mention at the end of the summary look the same to LIKE
  • Fixed word order: '%資料庫%交易%' cannot find 交易與資料庫 (“transactions and databases”)
  • No understanding of language: you have to handle case, full-width and half-width characters, and synonyms yourself

Full-text search starts by organizing the data the other way round.

Core mechanism

Inverted index: from “which terms a document has” to “which documents a term is in”

A regular table maps “document → content”. An inverted index goes the other way: it first splits each document into terms, then records, for each term, which documents it appears in, how many times, and at which positions. This list is called a posting list:

flowchart LR
    D1["#1 微服務拆分實戰…"] --> A["Analyzer: tokenize, lowercase…"]
    D2["#6 Redis 快取策略…"] --> A
    A --> T1["微服 → #1, #5, #6"]
    A --> T2["服務 → #1, #3, #5, #6, #7"]
    A --> T3["快取 → #6, #8"]

At query time you only look up each term’s posting list; when several terms must all appear, you take the intersection. Posting lists are sorted by document ID, so the intersection can be walked in a single pass, like a merge sort, with skip pointers (a skip list) to jump over ranges that cannot intersect.

Analyzers

Documents and queries must go through the same analyzer, or the terms they produce will not match:

  1. Character filters: strip HTML tags, convert full-width characters to half-width
  2. Tokenizer: split the text into terms
  3. Token filters: lowercase, remove stop words, stemming (running → run), synonyms

English can be tokenized on spaces and punctuation. Chinese has no spaces, which makes this the hardest step. There are two common approaches:

Bigram (every two characters) Dictionary-based (IK, jieba, smartcn, etc.)
How 微服務 → 微服, 服務 Split by the dictionary into 微服務
New words, brand names Never missed Split wrongly if not in the dictionary
Noise High; see the run below Low
Index size Large Small

Building an inverted index

A minimal search engine with 8 talks, bigram tokenization, and BM25 ranking:

Implementation (java MiniSearchEngine.java)
java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;

/** A minimal inverted index: Chinese is split into bigrams and English is lowercased; it records the documents and positions of every term and ranks with BM25. */
public class MiniSearchEngine {

    static final double K1 = 1.2;                                   // the Lucene / Elasticsearch default
    static final double B = 0.75;

    record Token(String term, int position) {}

    // term -> (docId -> positions); TreeMap keeps each posting list sorted by docId
    final Map<String, TreeMap<Integer, List<Integer>>> index = new HashMap<>();
    final Map<Integer, Integer> docLength = new HashMap<>();
    final Map<Integer, String> titles = new HashMap<>();

    static List<Token> analyze(String text) {
        List<Token> tokens = new ArrayList<>();
        StringBuilder run = new StringBuilder();
        boolean cjk = false;
        for (int i = 0; i <= text.length(); i++) {
            char c = i < text.length() ? text.charAt(i) : ' ';
            boolean isCjk = Character.UnicodeScript.of(c) == Character.UnicodeScript.HAN;
            boolean isWord = Character.isLetterOrDigit(c) && !isCjk;
            if (run.length() > 0 && (!(isCjk || isWord) || isCjk != cjk)) {
                emit(run.toString(), cjk, tokens);
                run.setLength(0);
            }
            if (isCjk || isWord) {
                run.append(c);
                cjk = isCjk;
            }
        }
        return tokens;
    }

    static void emit(String run, boolean cjk, List<Token> tokens) {
        if (!cjk) {
            tokens.add(new Token(run.toLowerCase(Locale.ROOT), tokens.size()));
        } else if (run.length() == 1) {
            tokens.add(new Token(run, tokens.size()));
        } else {
            for (int i = 0; i + 2 <= run.length(); i++) {          // "微服務" → "微服", "服務"
                tokens.add(new Token(run.substring(i, i + 2), tokens.size()));
            }
        }
    }

    void add(int docId, String title, String body) {
        titles.put(docId, title);
        List<Token> tokens = analyze(title + "。" + body);
        docLength.put(docId, tokens.size());
        for (Token t : tokens) {
            index.computeIfAbsent(t.term(), k -> new TreeMap<>())
                    .computeIfAbsent(docId, k -> new ArrayList<>()).add(t.position());
        }
    }

    /** Every bigram of every query word must appear; with phrase = true the bigrams must also be at adjacent positions. */
    List<String> search(String query, boolean phrase) {
        List<List<Token>> words = new ArrayList<>();
        for (String word : query.trim().split("\\s+")) {
            words.add(analyze(word));
        }
        Map<Integer, Double> scores = new HashMap<>();
        int n = docLength.size();
        double avgLength = docLength.values().stream().mapToInt(Integer::intValue).average().orElse(1);
        candidates:
        for (int docId : docLength.keySet()) {
            for (List<Token> word : words) {
                if (!contains(docId, word, phrase)) {
                    continue candidates;
                }
            }
            double score = 0;
            for (List<Token> word : words) {
                for (Token t : word) {
                    TreeMap<Integer, List<Integer>> postings = index.get(t.term());
                    int tf = postings.get(docId).size();
                    double idf = Math.log(1 + (n - postings.size() + 0.5) / (postings.size() + 0.5));
                    score += idf * tf * (K1 + 1) / (tf + K1 * (1 - B + B * docLength.get(docId) / avgLength));
                }
            }
            scores.put(docId, score);
        }
        return scores.entrySet().stream()
                .sorted(Map.Entry.<Integer, Double>comparingByValue(Comparator.reverseOrder()))
                .map(e -> String.format("%5.2f  #%d %s", e.getValue(), e.getKey(), titles.get(e.getKey())))
                .toList();
    }

    boolean contains(int docId, List<Token> word, boolean phrase) {
        for (Token t : word) {
            TreeMap<Integer, List<Integer>> postings = index.get(t.term());
            if (postings == null || !postings.containsKey(docId)) {
                return false;
            }
        }
        if (!phrase || word.size() == 1) {
            return true;
        }
        for (int start : index.get(word.get(0).term()).get(docId)) {
            boolean adjacent = true;
            for (int i = 1; i < word.size() && adjacent; i++) {
                adjacent = index.get(word.get(i).term()).get(docId).contains(start + i);
            }
            if (adjacent) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        MiniSearchEngine engine = new MiniSearchEngine();
        engine.add(1, "微服務拆分實戰", "以報名系統為例,說明如何依業務能力拆分微服務,以及服務之間的資料一致性。");
        engine.add(2, "資料庫交易與隔離等級", "從 MVCC 到 lost update,說明資料庫交易在並行環境下的行為。");
        engine.add(3, "Kafka 事件驅動入門", "用 Kafka 串接訂單與通知服務,處理重複投遞與訊息順序。");
        engine.add(4, "資料庫索引設計", "B+Tree、複合索引與最左前綴,避免資料庫全表掃描。");
        engine.add(5, "API 設計規範", "稍微服從團隊既有的規範,就能讓服務的 API 更一致。");
        engine.add(6, "Redis 快取策略", "快取穿透、擊穿與雪崩,以及微服務架構下的多層快取。");
        engine.add(7, "分散式交易與 Saga", "跨服務的交易無法用單一資料庫完成,改用 Saga 與補償。");
        engine.add(8, "前端效能優化", "圖片延遲載入與 CDN 快取設定。");

        int postings = engine.index.values().stream().mapToInt(Map::size).sum();
        System.out.printf("8 documents, %d distinct terms, %d postings%n", engine.index.size(), postings);
        System.out.println("Posting list for '服務': " + engine.index.get("服務").keySet());
        System.out.println("'微服務' is split into: " + analyze("微服務").stream().map(Token::term).toList());

        System.out.println("\nSearch '微服務', requiring only that both bigrams appear:");
        engine.search("微服務", false).forEach(r -> System.out.println("  " + r));
        System.out.println("Search '微服務', requiring adjacent bigram positions (phrase):");
        engine.search("微服務", true).forEach(r -> System.out.println("  " + r));
        System.out.println("Search '資料庫 交易':");
        engine.search("資料庫 交易", true).forEach(r -> System.out.println("  " + r));
        System.out.println("Search 'KAFKA':");
        engine.search("KAFKA", true).forEach(r -> System.out.println("  " + r));
    }
}
text
8 documents, 162 distinct terms, 182 postings
Posting list for '服務': [1, 3, 5, 6, 7]
'微服務' is split into: [微服, 服務]

Search '微服務', requiring only that both bigrams appear:
   1.86  #1 微服務拆分實戰
   1.51  #5 API 設計規範
   1.49  #6 Redis 快取策略
Search '微服務', requiring adjacent bigram positions (phrase):
   1.86  #1 微服務拆分實戰
   1.49  #6 Redis 快取策略
Search '資料庫 交易':
   3.84  #2 資料庫交易與隔離等級
   3.40  #7 分散式交易與 Saga
Search 'KAFKA':
   2.44  #3 Kafka 事件驅動入門
  • Bigram noise: #5 reads “稍微服從團隊既有的規範,就能讓服務的 API 更一致” (“follow the team’s existing conventions a little, and the services’ APIs become more consistent”). Both 微服 and 服務 appear in it, so it comes back as a result for 微服務, and even ranks above #6, which really is relevant
  • Positions fix this: require 微服 and 服務 to sit at adjacent positions (a phrase query), and #5 is excluded. The cost is that the index also has to store the positions of every term
  • Searching several words: 資料庫 交易 requires both words to appear; #4 only has 資料庫, so it does not show up in the results
  • Case: English is lowercased during analysis, so KAFKA also finds Kafka

Relevance ranking: BM25

Once you have the matching documents, you have to decide which come first. Lucene and Elasticsearch use BM25 by default. It computes a score for each query term and adds them up:

score = IDF × tf × (k1 + 1) ÷ (tf + k1 × (1 − b + b × document length ÷ average document length))

  • IDF: the fewer documents contain a term, the better it tells documents apart. 服務 appears in 5 documents, so it scores lower than kafka, which appears in only 1
  • tf and k1: the more often a term appears in a document, the higher the score, but it saturates: 10 occurrences are not worth 10 times one occurrence. k1 defaults to 1.2
  • Length and b: the same single occurrence counts for more in a short document than in a long one. b defaults to 0.75

In the run, #2 ranks above #7 for 資料庫 交易: 交易 (transaction) appears twice in both documents, but 資料庫 (database) appears twice in #2 and only once in #7.

Updating the index: segments and near real-time

A Lucene index is made of many segments that are never modified once written. New documents go into new segments, and small segments are merged into larger ones in the background; a delete only marks the document, which is actually removed during a merge. This is the same idea as the LSM-Tree in the B-Tree vs LSM post.

A new document becomes searchable only after a refresh. Elasticsearch refreshes once a second by default, so it is near real-time: data you just wrote may not be searchable for up to a second.

Distributed search and deep pagination

An Elasticsearch index is split into several shards. On a search, each shard finds its own top from + size hits, and the coordinating node merges and sorts them. For page 500 (20 per page), every shard has to prepare its top 10,020 hits. That is why Elasticsearch by default does not allow from + size above 10,000 (index.max_result_window). For deep pagination, use search_after instead. It is the same idea as keyset pagination in the indexes post: remember the sort values of the last hit on the previous page and continue from there.

Comparing options

What to search with

LIKE MySQL FULLTEXT (ngram parser) Elasticsearch/OpenSearch
Chinese String matching Bigram tokenization Bigram or a dictionary tokenizer plugin
Relevance ranking None Yes BM25, with adjustable field weights
Filters and counts (facets) Plain SQL Plain SQL Built in and fast
Scale Small Medium (hundreds of thousands to millions of rows) Large, scales horizontally
Consistency with business data Same transaction Same transaction Eventually consistent, needs a sync mechanism
Operating cost None None One more cluster

PostgreSQL’s built-in full-text search cannot split Chinese; it needs an extension such as zhparser or pg_bigm.

Syncing data to Elasticsearch

The search index is derived data, and the database is the single source of truth. This is the same idea as the read model in CQRS. Common ways to sync:

Approach How Problem
Dual writes The application writes to the database, then to Elasticsearch If the second step fails, the two disagree, and nobody knows
Outbox Write an event to an event table in the same transaction as the business data, then a background process sends it to the index (see Outbox Pattern) One more table and one more background process
CDC Read the database binlog and send the changes to the index One more CDC component
Periodic full rebuild Build a new index, load the data, then switch over with an alias Only for data that can tolerate the delay

In practice, real-time sync through an outbox or CDC is often combined with a periodic full rebuild: the real-time sync handles day-to-day changes, and the full rebuild fixes accumulated inconsistencies. The rebuild is also how you roll out a change to the mapping or the analyzer.

In Java

1. Start with MySQL FULLTEXT

200,000 talks are still within what MySQL can handle, so there is no need to run an Elasticsearch cluster from day one:

sql
ALTER TABLE lecture
    ADD FULLTEXT INDEX ft_lecture (title, summary) WITH PARSER ngram;

By default the ngram parser splits every two characters (ngram_token_size = 2), the same as the bigrams above. The difference between the query modes matters:

  • Natural language mode: the query is also split into bigrams, and the results are their union. 微服務 becomes “contains 微服 or 服務”, which is very noisy
  • Boolean mode: the query becomes a phrase search over its bigrams, which requires adjacent positions, the equivalent of the phrase query in the run above

So use boolean mode, but never put user input into it as it is:

java
package search;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.jdbc.core.simple.JdbcClient;

public class LectureSearchRepository {

    private static final int MAX_TERMS = 5;
    private static final int MAX_LIMIT = 50;

    private final JdbcClient jdbc;

    public LectureSearchRepository(JdbcClient jdbc) {
        this.jdbc = jdbc;
    }

    public record Hit(long id, String title, double score) {}

    /** The visibility condition is in the same query as the search condition, so results never include unpublished talks. */
    public List<Hit> search(String userInput, int limit) {
        String query = toBooleanQuery(userInput);
        if (query.isEmpty()) {
            return List.of();
        }
        return jdbc.sql("""
                SELECT id, title, MATCH(title, summary) AGAINST (:q IN BOOLEAN MODE) AS score
                  FROM lecture
                 WHERE MATCH(title, summary) AGAINST (:q IN BOOLEAN MODE)
                   AND visibility = 'PUBLIC'
                 ORDER BY score DESC, id DESC
                 LIMIT :limit
                """)
                .param("q", query)
                .param("limit", Math.min(limit, MAX_LIMIT))
                .query(Hit.class)
                .list();
    }

    /** User input is treated only as text: boolean mode operators are removed, every term must appear, at most 5 terms. */
    static String toBooleanQuery(String userInput) {
        return Arrays.stream(userInput.replaceAll("[+\\-<>()~*\"@]", " ").trim().split("\\s+"))
                .filter(term -> !term.isBlank())
                .limit(MAX_TERMS)
                .map(term -> "+\"" + term + "\"")
                .collect(Collectors.joining(" "));
    }
}

What toBooleanQuery actually does:

text
微服務                          -> +"微服務"
資料庫 交易                       -> +"資料庫" +"交易"
+微服務 -kafka                  -> +"微服務" +"kafka"
"交易" (隔離) <等級> ~mvcc* @3     -> +"交易" +"隔離" +"等級" +"mvcc" +"3"
a b c d e f g                -> +"a" +"b" +"c" +"d" +"e"

The boolean mode operators that users type, such as +, -, *, and ~, are all removed, and every term is wrapped as a phrase that must appear. The “exclude” meaning of something like -kafka goes away too; in return, the query behaves completely predictably. Both the number of terms and the number of rows are capped.

2. When you move to Elasticsearch

When the data volume or the features you need outgrow MySQL (facet counts or autocomplete, for example), the index mapping names a Chinese analyzer, and visibility uses the keyword type for exact filtering:

json
PUT /lectures-v2
{
  "mappings": {
    "properties": {
      "title":      { "type": "text", "analyzer": "cjk" },
      "summary":    { "type": "text", "analyzer": "cjk" },
      "visibility": { "type": "keyword" },
      "startsAt":   { "type": "date" }
    }
  }
}

cjk is a built-in Elasticsearch analyzer, and it uses bigrams. At query time, put the user input in a multi_match whose fields the server decides, and put visibility in filter:

json
GET /lectures/_search
{
  "query": {
    "bool": {
      "must":   { "multi_match": { "query": "微服務", "fields": ["title^3", "summary"], "type": "phrase" } },
      "filter": { "term": { "visibility": "PUBLIC" } }
    }
  },
  "size": 20
}

title^3 gives the title three times the weight of the summary. Conditions in filter do not take part in scoring, and their results can be cached.

The application always reaches the index through an alias (lectures). To change the mapping or the analyzer, create a new index lectures-v2, load the data, and switch the alias in one step:

json
POST /_aliases
{
  "actions": [
    { "remove": { "index": "lectures-v1", "alias": "lectures" } },
    { "add":    { "index": "lectures-v2", "alias": "lectures" } }
  ]
}

The alias actions in one request are atomic, so searches do not fail halfway through the switch.

Pitfalls and gotchas

  • Indexing and querying with different analyzers: the terms do not match, and documents that clearly exist simply cannot be found
  • Bigrams without positions: 稍微服從 (“follow a little”) also counts as 微服務
  • Dictionary tokenizers missing new words: new technical terms and brand names that are not in the dictionary get split wrongly, so you need a process for updating the dictionary
  • Searching right after writing: near real-time means a new document may not be searchable for up to a second. A flow like “create, then jump to the search page” should read straight from the database
  • Changing synonyms or stop words without rebuilding the index: the analyzer applied at indexing time has changed, but the terms of existing documents are not updated automatically
  • Assuming a field type can be changed in place: Elasticsearch cannot change the type of an existing field; you can only create a new index and reindex, which is why you use an alias from the start
  • Deep pagination with from + size: anything past 10,000 hits is rejected; use search_after instead
  • Dual writes: the database and the index will diverge sooner or later
  • Using Elasticsearch as the primary database: it has no cross-document transactions, and when the cluster has problems you must be able to rebuild it from the database

Security

  • Search is another read path, and authorization has to follow it: the database API checks permissions, but if the index also holds drafts and internal talks, then the search results, the highlighted snippets of summaries, the autocomplete suggestions, and even the “N results found” total all reveal that they exist. Visibility and tenant conditions belong in the query itself; if you filter in the application after the query, the number of hits per page and the total still leak. This is another form of BOLA (Part 8)
  • Query syntax injection: Elasticsearch’s query_string lets users name fields in their input (for example internal_note:*) and use wildcards and regular expressions, which opens the query language to outsiders. The official documentation also advises against using it for search boxes; use match or simple_query_string instead, with the fields decided by the server. The same goes for MySQL’s boolean mode: remove the operators first
  • An expensive query is a DoS: leading wildcards, regular expressions, a huge size, very deep pagination, and queries with hundreds of terms can all keep the cluster too busy to serve anyone else. Cap the number of terms, the number of hits, and the page depth, and set a query timeout
  • Deletes must reach the index: if a record is deleted from the database but is still in the index, search keeps returning deleted personal data; deleted documents also stay on disk until their segment is merged, and they are in snapshots too. The delete process has to cover the index, for the same reason as “delete is not erase” in the B-Tree vs LSM post. The cluster itself must also have authentication turned on and must not be exposed to the network (see the SQL vs NoSQL post)

When to use it, and when not to

  • MySQL FULLTEXT: hundreds of thousands to millions of rows, strong consistency with business data required, no wish to run another system
  • Elasticsearch/OpenSearch: large data volumes, facet counts and autocomplete, complex relevance tuning, log search
  • Don’t use it: for exact lookups (a regular B+Tree index is enough), or as the only source of the data

References

Comments