DEV Community

Kinetic Code Labs
Kinetic Code Labs

Posted on Originally published at kineticcodelabs.in

Sub-Millisecond Search in SQLite Without Elasticsearch Using Prefix Chunk Indexing

Why LIKE '%query%' Doesn't Scale

A naive search endpoint like:

SELECT * FROM users WHERE name LIKE '%rohan%' OR username LIKE '%rohan%' OR bio LIKE '%rohan%'
Enter fullscreen mode Exit fullscreen mode

cannot use standard B-tree indexes because of the leading % wildcard—forcing a full-table scan on every keystroke.


Our Solution: Prefix Chunk Tables + Composite Indexes

In bondly-backend/db.js, we added two lightweight index tables:

CREATE TABLE IF NOT EXISTS user_search_chunks (
  chunk TEXT NOT NULL,
  user_id TEXT NOT NULL,
  PRIMARY KEY (chunk, user_id)
);

CREATE TABLE IF NOT EXISTS post_search_chunks (
  chunk TEXT NOT NULL,
  post_id TEXT NOT NULL,
  PRIMARY KEY (chunk, post_id)
);
Enter fullscreen mode Exit fullscreen mode

Whenever a user signs up, updates their profile, or publishes a post, buildSearchChunks(text) splits the text into lowercase alphanumeric tokens and generates prefix chunks from 2 to 14 characters (capped at 45 chunks per record to keep storage minimal).

When /api/users/search?q=roh runs, SQLite performs an exact O(log N) B-tree lookup on WHERE c.chunk = 'roh' joined with users/posts, falling back to LIKE only if fewer than 20 results are found. Combined with targeted indexes on LOWER(username), phone, telegram_chat_id, posts(user_id, created_at DESC), messages(sender_id, receiver_id, created_at), and notifications(user_id, is_read, created_at DESC), the entire database stays responsive without external search infrastructure.

Free Engineering & AI Search Diagnostics

Originally published at Kinetic Code Labs.

Top comments (0)