Implementing Local-First Search: FTS5 Indexing in Alif2Ayah
Learn how to use SQLite’s FTS5 extension to build instant, offline-first full-text search for religious texts without the latency of cloud APIs.
When building Alif2Ayah, our companion app for Quranic study, we faced a fundamental engineering challenge: providing a search experience that matches the speed of thought. In a religious context, search is often used during prayer, study, or discussion, meaning a three-second round trip to a server is a failure. Users expect results that appear as they type, even without an internet connection. Most developers default to cloud-based search engines like Algolia or Elasticsearch, but for a privacy-focused studio committed to implementing local-only data, these weren't options. Instead, we leveraged the SQLite FTS5 (Full-Text Search) extension to build a performant, offline-first search engine directly into the client.
The Architecture of Local Full-Text Search
Full-text search is structurally different from standard SQL queries. If you use a LIKE '%keyword%' query in a standard SQLite table, the engine must perform a full table scan. In a text with over 6,000 verses, each potentially including multiple translations and transliterations, this linear scan becomes sluggish on mid-range Android devices.
SQLite FTS5 solves this by creating a virtual table that uses an inverted index. Think of it like the index at the back of a physical book: instead of reading every page to find a word, you look up the word and get a list of page numbers. FTS5 manages this mapping of tokens (words) to row IDs automatically. In Alif2Ayah, this allows us to query the entire text and return ranked results in under 20 milliseconds on hardware from five years ago.
Why FTS5 Over Standard SQLite Tables?
| Feature | Standard SQLite (LIKE) | SQLite FTS5 Virtual Table |
|---|---|---|
| Search Speed | O(N) - Linear Scan | O(log N) - B-Tree Index |
| Partial Matching | Suffix only (word%) is fast | Prefix, suffix, and proximity |
| Ranking | No built-in relevance | BM25 algorithm included |
| Storage | Minimal overhead | Higher (index storage) |
| Complexity | Simple SELECT | Requires virtual table setup |
Setting Up the FTS5 Virtual Table
To implement this in an Android environment, usually via the Room Persistence Library or raw SQLite, you must first define your virtual table. Unlike a standard table, an FTS5 table is declared using CREATE VIRTUAL TABLE.
For Alif2Ayah, we index three primary fields: the Arabic text, the English translation, and the transliteration. This allows the user to find a verse regardless of which script they are most comfortable with—a philosophy we detailed in designing for dual-script navigation.
``sql CREATE VIRTUAL TABLE verse_search_index USING fts5( verse_id UNINDEXED, arabic_text, english_translation, transliteration, tokenize='unicode61' ); ``
Notice the tokenize='unicode61' parameter. This is critical for religious or multi-script apps because it ensures that diacritics and various Unicode accents are handled correctly. Without it, a search for "Musa" might fail to find "Mūsā".
Data Sync and the Shadow Table Pattern
Because FTS5 tables are optimized for searching rather than relational integrity, we treat the FTS table as a "search index" rather than the source of truth. We maintain a standard relational table for the verse metadata (surah number, ayah number, bookmarks) and use a content-sync trigger or a manual update flow to keep the FTS table updated.
When a user downloads a new translation in Alif2Ayah, the app executes a background job that populates the FTS5 table. We recommend using a transaction for this to ensure the database doesn't lock while the index is being built. By separating the search index from the primary data, we can drop and rebuild the index if the user changes search settings or if we update our tokenization logic without risking the user's personal data.
Advanced Querying: BM25 and Proximity
One of the most powerful features of FTS5 is the bm25() ranking function. BM25 (Best Matching 25) is a ranking function used by search engines to estimate the relevance of documents to a given search query. It considers factors like term frequency (how often a word appears in the verse) and inverse document frequency (how rare the word is across the whole Quran).
In Alif2Ayah, we use weighted rankings. For instance, a match in the translation might be ranked lower than a direct match in the Arabic text.
``sql SELECT * FROM verse_search_index WHERE verse_search_index MATCH :query ORDER BY bm25(verse_search_index, 10.0, 2.0, 5.0); ``
In the example above, the weights (10.0, 2.0, 5.0) tell SQLite to prioritize matches in the first column significantly higher than the others. This ensures that when a user searches for a specific Arabic root, the direct script matches appear at the top, even if the word appears commonly in English translations.
Handling Arabic Morphology and Diacritics
Searching Arabic text presents a unique challenge: the Tashkeel (vowels/diacritics). A user might search for a word without diacritics, but the database contains them.
There are two ways we handle this locally:
- 1.Normalization during Indexing: We create a hidden column in the FTS table that contains the "stripped" Arabic text (no diacritics). When a query comes in, we strip the user's query and search against that column. This consumes more storage but results in instant responses.
- 2.Custom Tokenizers: On standard Android SQLite builds, custom tokenizers are difficult because they require compiling native C code. For Alif2Ayah, we found that normalization at the application layer was sufficient and highly portable across different Android versions.
The "Instant Search" UI Checklist
Implementing a fast index is only half the battle. The UI must be able to keep up with the database's speed. To prevent the interface from stuttering as the user types, we follow this checklist:
- Debouncing: Wait for 200–300ms of typing inactivity before firing the query. This prevents the database from being hammered by partial, nonsensical fragments.
- Cancellation: If a new query is triggered before the previous one finishes, cancel the previous database job immediately to free up resources.
- UI Thread Protection: Never run an FTS5 query on the main thread. Even a 20ms query can cause a frame drop if it hits a disk I/O bottleneck.
- Highlighting: Use the FTS5
highlight()function to wrap matching terms in HTML tags (e.g.,<b>). This provides immediate visual feedback to the user on why a result was returned.
Solving the Privacy and Latency Trade-off
By moving search locally, we gain two things that cloud APIs can never offer. First, absolute privacy. What a user searches for in a religious or personal context is their business. By keeping the FTS5 index on-device, that search history never touches our servers or a third-party search provider's logs.
Second, we achieve network independence. In regions with poor connectivity, cloud search simply breaks. By using FTS5, Alif2Ayah remains fully functional in airplane mode. This aligns with our work on Salah Companion, where we ensure prayer time calculations work at sea or in remote areas without signal.
Optimization for Low-End Devices
While FTS5 is fast, it isn't free. The index can grow to double the size of the raw text. For users on devices with limited storage, we offer an "On-Demand Indexing" strategy. We only index the translations currently active in the user’s settings. If they delete a translation to save space, we purge those rows from the FTS5 table and run INSERT INTO verse_search_index(verse_search_index) VALUES('optimize');. This command defragments the FTS5 B-Trees, keeping the database file size as small as possible.
What to do next
- 1.Audit your current search: If you are using
LIKEqueries in your Android app for anything larger than a few hundred rows, replace them with a virtual FTS5 table to improve UI responsiveness. - 2.Normalize your data: Ensure that search queries and index data are normalized (case-folding, diacritic removal) at the application layer before they reach the database.
- 3.Implement BM25 Ranking: Move beyond simple alphabetical results; use FTS5’s built-in ranking to ensure the most relevant content reaches the user first.