Tools Hub / Blueprints / Linux & DevOps
⚙️ Linux & DevOps

Zero-Elasticsearch Bilingual Full-Text Search with SQLite FTS5 Trigram Index

Build a production-grade bilingual (CJK + Latin) full-text search indexer on SQLite FTS5 with trigram tokenization, atomic incremental upserts, WAL concurrency, and structured logging — no Elasticsearch cluster required.

Stack: Python 3.11 / SQLite FTS5 (trigram + unicode61) RAM: 64 MB RAM Intermediate
📄 fts_indexer.py
#!/usr/bin/env python3
"""Production bilingual FTS5 indexer: trigram (CJK/substring) + unicode61 (word) dual index."""
import argparse
import json
import logging
import os
import sqlite3
import sys
import time
from pathlib import Path

LOG = logging.getLogger("fts")

SCHEMA = """
PRAGMA journal_mode=WAL;
PRAGMA synchronous=NORMAL;
PRAGMA busy_timeout=5000;
CREATE TABLE IF NOT EXISTS docs (
  id INTEGER PRIMARY KEY,
  source TEXT NOT NULL,
  ext_id TEXT NOT NULL,
  title TEXT NOT NULL DEFAULT '',
  body TEXT NOT NULL DEFAULT '',
  updated_at INTEGER NOT NULL,
  UNIQUE(source, ext_id)
);
CREATE VIRTUAL TABLE IF NOT EXISTS docs_uni USING fts5(
  title, body, content='docs', content_rowid='id', tokenize='unicode61 remove_diacritics 2'
);
CREATE VIRTUAL TABLE IF NOT EXISTS docs_tri USING fts5(
  title, body, content='docs', content_rowid='id', tokenize='trigram'
);
CREATE TRIGGER IF NOT EXISTS docs_ai AFTER INSERT ON docs BEGIN
  INSERT INTO docs_uni(rowid,title,body) VALUES (new.id,new.title,new.body);
  INSERT INTO docs_tri(rowid,title,body) VALUES (new.id,new.title,new.body);
END;
CREATE TRIGGER IF NOT EXISTS docs_ad AFTER DELETE ON docs BEGIN
  INSERT INTO docs_uni(docs_uni,rowid,title,body) VALUES('delete',old.id,old.title,old.body);
  INSERT INTO docs_tri(docs_tri,rowid,title,body) VALUES('delete',old.id,old.title,old.body);
END;
CREATE TRIGGER IF NOT EXISTS docs_au AFTER UPDATE ON docs BEGIN
  INSERT INTO docs_uni(docs_uni,rowid,title,body) VALUES('delete',old.id,old.title,old.body);
  INSERT INTO docs_tri(docs_tri,rowid,title,body) VALUES('delete',old.id,old.title,old.body);
  INSERT INTO docs_uni(rowid,title,body) VALUES (new.id,new.title,new.body);
  INSERT INTO docs_tri(rowid,title,body) VALUES (new.id,new.title,new.body);
END;
"""


def connect(db_path: str) -> sqlite3.Connection:
    conn = sqlite3.connect(db_path, timeout=10.0, isolation_level=None)
    conn.execute("PRAGMA busy_timeout=5000")
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA synchronous=NORMAL")
    conn.executescript(SCHEMA)
    return conn


def upsert(conn: sqlite3.Connection, source: str, ext_id: str, title: str, body: str) -> int:
    now = int(time.time())
    with conn:
        conn.execute("BEGIN IMMEDIATE")
        cur = conn.execute(
            "INSERT INTO docs(source,ext_id,title,body,updated_at) VALUES(?,?,?,?,?) "
            "ON CONFLICT(source,ext_id) DO UPDATE SET title=excluded.title, "
            "body=excluded.body, updated_at=excluded.updated_at",
            (source, ext_id, title, body, now),
        )
        rowid = cur.lastrowid
        if rowid is None:
            rowid = conn.execute(
                "SELECT id FROM docs WHERE source=? AND ext_id=?", (source, ext_id)
            ).fetchone()[0]
    return int(rowid)


def search(conn: sqlite3.Connection, query: str, limit: int = 20) -> list[dict]:
    q = query.strip()
    if not q:
        return []
    # CJK / short queries -> trigram substring; latin words -> unicode61
    use_trigram = any(ord(ch) > 0x2E80 for ch in q) or len(q) < 3
    table = "docs_tri" if use_trigram else "docs_uni"
    match = q if use_trigram else " ".join(f'"{w}"' for w in q.split())
    sql = (
        f"SELECT d.id, d.source, d.ext_id, d.title, "
        f"snippet({table}, 1, '<b>', '</b>', '…', 24) AS snip, "
        f"bm25({table}) AS score "
        f"FROM {table} JOIN docs d ON d.id = {table}.rowid "
        f"WHERE {table} MATCH ? ORDER BY score LIMIT ?"
    )
    try:
        rows = conn.execute(sql, (match, limit)).fetchall()
    except sqlite3.OperationalError as exc:
        LOG.warning("query_failed q=%r err=%s", q, exc)
        return []
    return [
        {"id": r[0], "source": r[1], "ext_id": r[2], "title": r[3], "snippet": r[4], "score": r[5]}
        for r in rows
    ]


def main(argv: list[str] | None = None) -> int:
    p = argparse.ArgumentParser(description="SQLite FTS5 bilingual indexer")
    p.add_argument("--db", default=os.environ.get("FTS_DB", "fts.db"))
    p.add_argument("--log-level", default=os.environ.get("FTS_LOG_LEVEL", "INFO"))
    sub = p.add_subparsers(dest="cmd", required=True)
    up = sub.add_parser("upsert")
    up.add_argument("--source", required=True)
    up.add_argument("--ext-id", required=True)
    up.add_argument("--title", default="")
    up.add_argument("--body", default="")
    up.add_argument("--body-file")
    se = sub.add_parser("search")
    se.add_argument("query")
    se.add_argument("--limit", type=int, default=20)
    sub.add_parser("optimize")
    args = p.parse_args(argv)

    logging.basicConfig(
        level=getattr(logging, args.log_level.upper(), logging.INFO),
        format="%(asctime)s %(levelname)s %(name)s %(message)s",
    )
    Path(args.db).parent.mkdir(parents=True, exist_ok=True)
    conn = connect(args.db)
    try:
        if args.cmd == "upsert":
            body = args.body
            if args.body_file:
                body = Path(args.body_file).read_text(encoding="utf-8")
            rid = upsert(conn, args.source, args.ext_id, args.title, body)
            LOG.info("upserted rowid=%d source=%s ext_id=%s", rid, args.source, args.ext_id)
            print(json.dumps({"rowid": rid}))
        elif args.cmd == "search":
            results = search(conn, args.query, args.limit)
            LOG.info("search q=%r hits=%d", args.query, len(results))
            print(json.dumps(results, ensure_ascii=False, indent=2))
        elif args.cmd == "optimize":
            conn.execute("INSERT INTO docs_uni(docs_uni) VALUES('optimize')")
            conn.execute("INSERT INTO docs_tri(docs_tri) VALUES('optimize')")
            LOG.info("optimized db=%s", args.db)
    finally:
        conn.close()
    return 0


if __name__ == "__main__":
    sys.exit(main())

1. Production Pain Points and Architecture Trade-offs

The most common failure mode of Elasticsearch in small teams is not insufficient performance but operational cost disproportionate to actual load: a 3-node cluster starts at 6-8 GB heap, JVM tuning, shard rebalancing, and certificate rotation, while the real corpus is often only a few hundred thousand to a few million documents. SQLite FTS5 on a single box handles this comfortably: roughly 300-600 MB on disk for 1M documents of ~1 KB each, query P99 in the 5-30 ms range (trigram prefix/substring queries are slower than token queries), and resident memory under 64 MB.

Three architectural decisions matter:

2. Step-by-Step Deployment and Permission Hardening

Step 1: Verify SQLite version and compile options. The trigram tokenizer requires SQLite >= 3.34.0 and FTS5 compiled in. Run python3 -c "import sqlite3;print(sqlite3.sqlite_version)". If below 3.34, upgrade the system libsqlite3 or use an official Python build. Verify trigram support with python3 -c "import sqlite3;c=sqlite3.connect(':memory:');c.execute(\"CREATE VIRTUAL TABLE t USING fts5(x, tokenize='trigram')\")" — no exception means it is available.

Step 2: Create a dedicated system user and directories. Never run the indexer as root:

bash
sudo useradd --system --home /var/lib/fts --shell /usr/sbin/nologin fts
sudo install -d -o fts -g fts -m 0750 /var/lib/fts /var/log/fts
sudo install -m 0755 fts_indexer.py /usr/local/bin/fts_indexer.py

Set the database file to 0640 owned by fts:fts. If the search service is separate from the indexer, add the search process to the fts group. Note that SQLite WAL readers need write access to the directory to create -shm/-wal files; alternatively open a read-only connection with PRAGMA query_only=1 and accept the WAL read-only constraints.

Step 3: Systemd unit (optional, for scheduled incremental sync).

ini
[Unit]
Description=FTS5 incremental indexer
After=network.target
[Service]
Type=oneshot
User=fts
Group=fts
Environment=FTS_DB=/var/lib/fts/fts.db FTS_LOG_LEVEL=INFO
ExecStart=/usr/bin/python3 /usr/local/bin/fts_indexer.py upsert --source cms --ext-id %i --body-file /dev/stdin
NoNewPrivileges=true
ProtectSystem=strict
ReadWritePaths=/var/lib/fts
PrivateTmp=true

Step 4: Initial build and bulk import. Use the upsert subcommand per document, or wrap a JSONL reader in a loop. Run optimize every 5000 documents to merge b-tree segments; it briefly holds the write lock, so schedule it off-peak.

Step 5: Backups. Never cp a live database file. Use sqlite3 /var/lib/fts/fts.db ".backup '/var/lib/fts/backup-$(date +%F).db'", which produces a consistent snapshot under WAL.

3. Parameter Tuning and Load Verification

Balancing index size against query latency. Trigram indexes are large; if the corpus is mostly English, keep only docs_uni; if mostly Chinese, keep both. Measure with:

bash
sqlite3 /var/lib/fts/fts.db "SELECT name, SUM(pgsize)/1024/1024 AS mb FROM dbstat GROUP BY name ORDER BY mb DESC LIMIT 10;"

Load testing queries. Use hyperfine or a simple loop to measure P50/P99:

bash
for i in $(seq 1 200); do
  /usr/bin/time -f "%e" python3 /usr/local/bin/fts_indexer.py --db /var/lib/fts/fts.db search "分布式数据库" --limit 10 >/dev/null
done 2>&1 | sort -n | awk '{a[NR]=$1} END{print "P50="a[int(NR*0.5)]" P99="a[int(NR*0.99)]"}'

Key PRAGMA tuning. synchronous=NORMAL under WAL already guarantees crash consistency (at most the last transaction is lost) and is 3-5x faster than FULL. cache_size=-64000 (64 MB page cache) pays off for read-heavy workloads. mmap_size=268435456 (256 MB) reduces read syscalls but must be weighed against RSS. For bulk writes, raising wal_autocheckpoint from the default 1000 pages to 4000 reduces checkpoint jitter.

Query construction pitfalls. Under unicode61 you must quote user input (the code does " ".join(f'"{w}"' ...)), otherwise AND/OR/NEAR are parsed as FTS5 syntax and raise OperationalError. Under trigram, pass the raw string, but reject queries shorter than 3 characters — FTS5 trigram returns nothing for shorter MATCH terms.

4. Troubleshooting and Safe Rollback

Issue 1: database is locked. Usually a long transaction or a missing busy_timeout. Diagnose with sqlite3 fts.db "PRAGMA wal_checkpoint;" to see if it blocks, and fuser -v /var/lib/fts/fts.db* to find the holder. Fix by ensuring every connection sets busy_timeout, routing all writes through BEGIN IMMEDIATE, and never doing network IO inside a transaction.

Issue 2: Results diverge from the source (ghost rows). Almost always caused by bypassing triggers with a direct UPDATE docs or DELETE FROM docs; external content tables do not observe those automatically. Fix by routing all writes through upsert(). If drift has already occurred, rebuild with INSERT INTO docs_uni(docs_uni) VALUES('rebuild') and the same for docs_tri — a full scan, tens of seconds for a million rows.

Issue 3: Chinese queries return nothing. Check whether the query was misrouted to docs_uni. Confirm with EXPLAIN QUERY PLAN, or directly run SELECT * FROM docs_tri WHERE docs_tri MATCH '数据库' to verify the trigram index exists.

Issue 4: Disk usage spikes. An unreclaimed WAL file usually means a long-running read transaction is blocking checkpoint. PRAGMA wal_checkpoint(TRUNCATE) forces truncation but blocks writers. The durable fix is to monitor -wal size and alert above 256 MB.

Safe rollback. Take a .backup snapshot before every schema change or bulk import. To roll back: stop the service, mv fts.db fts.db.broken, cp backup-YYYY-MM-DD.db fts.db, restart. Because the FTS5 indexes can be fully rebuilt from the docs table, the worst case only requires preserving docs data to restore all search capability — a major operational advantage over Elasticsearch snapshot recovery.

Want the full multi-workflow production repo with REST API & ops dashboard?
All blueprints are bundled inside the B2B AI Automation MVP Pack with Docker, Systemd & test suite.
Get Full MVP Pack $499 →
PARTNER ECOSYSTEM

Recommended Cloud & AI Infrastructure

Hand-picked developer infrastructure we use to run 24/7 workflows. Partner links help keep all browser tools free.
📬 WEEKLY BRIEF · ZERO SPAM

Get the Yevrix Indie Dev & AI Digest

One weekly email with new browser-local dev tools, cloud & LLM pricing benchmarks, ready-to-install Agent Skills, and rising OSS repos. 1-click unsubscribe anytime.