Document Search System Design: Scalable Search Architecture
Short answer
Document search system design combines a document parsing pipeline, an inverted index scored with BM25, a vector index of embeddings searched by approximate nearest neighbor, and sharded storage with replicas. Queries scatter to every shard, gather the top hits, and merge keyword and vector lists with reciprocal rank fusion. Engines such as Elasticsearch and Apache Solr provide these parts out of the box.
Source: Vervelio, https://vervelio.com/blog/document-search-system-design

Document search system design comes down to five stages: a document parsing pipeline, an inverted index for BM25 keyword scoring, a vector index of embeddings for semantic matches, sharded storage with replicas, and a ranking layer that fuses the results. Each stage has its own failure mode. Search slows down when text arrives faster than the indexer can absorb it, so production systems keep document storage and the search index as separate, loosely coupled parts.
Document Search System Design: Core Components and Architecture#
A document search system has separate layers to ingest, store and retrieve text. Storage keeps the source of truth. The search index keeps a derived, rebuildable copy tuned for fast lookups. An inverted index is the core structure: it maps each term to the IDs of the documents that contain it.
- Text Extraction
- Tokenization and Filtering
- Indexing (Inverted Index)
- Distributed Shard Routing
- Ranking and Score Fusion
In the CiteSeerX digital library architecture, document full text from a production storage repository and document metadata from a MySQL relational database are indexed by Apache Solr to power search functionality (cs.odu.edu). Modern systems also consolidate these storage and indexing layers. An updated CiteSeerX design consolidates MySQL and Apache Solr into a single Elasticsearch instance that serves the dual functions of document storage and full-text retrieval.
| Component Role | Traditional Architecture | Consolidated Architecture | Primary Function |
|---|---|---|---|
| Metadata Storage | MySQL Relational Database (cs.odu.edu) | Elasticsearch Instance | Persists schemas, access policies, and record attributes |
| Document Store | Dedicated Production Repository (cs.odu.edu) | Elasticsearch Instance | Stores raw document text and extracted content |
| Search Indexer | Apache Solr (cs.odu.edu) | Elasticsearch Instance | Ingests documents, builds inverted indexes, and evaluates queries |
Document Parsing Pipeline: Asynchronous Ingestion, OCR and Text Extraction#
Raw files are not searchable until a document parsing pipeline turns them into clean text and metadata. Parsing is slow and uneven, since a long scanned PDF costs far more than a short web page. Put it behind a queue so uploads return fast and workers catch up at their own pace.
Queue-Based Parsing Workers#
A typical flow writes the original file to object storage, then puts a job on a message queue. Worker processes pull jobs, detect the file type and extract text. Apache Tika, for example, detects and extracts metadata and text from over a thousand different file types (tika.apache.org). Tika's 4.0.0 release (August 2026) added in-process Tesseract OCR for scanned pages.
Keep OCR in its own queue. It is the slowest step, and a spike of scans should not delay plain text files. Failed jobs go to a dead-letter queue with the error, so one corrupt file never blocks the rest. When a worker finishes, it writes the extracted text to storage and sends an index request. Because storage stays the source of truth, you can replay every document through a new parser later.
Inverted Index Engineering and Memory Optimization#
Text preprocessing and memory layout decide how inverted lists perform under steady ingestion and heavy query load. Normalization shrinks the dictionary and the postings lists. Chunked, compressed postings cut memory use and cache misses during traversal.
Postings Structure and Preprocessing Trade-offs#
Lexical indexing pipelines tokenize text and apply linguistic filters before writing to postings lists. A postings list is a sorted sequence of document IDs containing a specific term, optionally augmented with term frequencies and token positions.
Information retrieval analysis shows that stemming and case folding reduce the total count of distinct dictionary terms by 17% each (nlp.stanford.edu). These transformations also reduce the count of nonpositional postings by 4% and 3%, respectively. Removing the 150 most frequent terms as stop words strips 25% to 30% of nonpositional postings from the index.
Aggressive filtering reduces memory footprint but limits exact-match and phrase-search precision. Engineers must evaluate whether domain-specific terminology tolerates aggressive stemming without corrupting relevance.
Inverted Index Compression: Chunked Postings in RAM#
In-memory inverted index traversal is often bottlenecked by RAM latency and cache line misses during postings intersection. A cache line is the minimum unit of memory transferred between main memory and CPU cache.
Evaluations on an in-memory, list-based inverted file indexer across 8.5 billion (doi.org) word occurrences demonstrate that dynamic list chunking almost halves the memory required for linked lists. This chunking structure significantly diminishes CPU cache-line reads during traversal. Furthermore, in-chunk postings compression halves the remaining memory footprint without significantly impacting index construction speeds.
Raw Postings: [Doc1] -> [Doc4] -> [Doc8] -> [Doc12] -> [Doc19] (High pointer overhead, random cache reads)
Chunked Postings: [Block 0: Doc1, Doc4, Doc8] -> [Block 1: Doc12, Doc19,...] (Contiguous memory, reduced traversal latency)
Operating systems manage physical RAM using virtual memory page tables. Employing virtual memory large pages reduces the CPU overhead of page table walks, accelerating both phases of in-memory index construction (doi.org).
Distributed Indexing, Sharding, and Replication#

Large document collections outgrow one machine, so the index is split into shards spread across nodes. Each shard has replicas for failover and read capacity. A routing rule decides which shard owns each document, and a leader on each shard orders the writes.
Document Sharding and Update Routing#
Sharding is the horizontal partitioning of an index into independent subsets called shards. Each shard contains an autonomous inverted index.
SolrCloud clusters implement prefix-based document routing via the compositeId router (solr.apache.org). This router uses a prefix embedded in the document identifier, separated by an exclamation point, to direct the document to a specific shard. For example, assigning an identifier such as IBM!12345 hashes the IBM prefix, guaranteeing that all records sharing that prefix reside on the same shard.
Document Ingest ("IBM!12345")
│
▼
[Hash Function on Prefix: "IBM"] ───► Target Shard Assigned
│
▼
[Active Shard Leader]
│ │
Forward Update │ │ Forward Update
▼ ▼
[Replica 1] [Replica 2]
When an indexing operation arrives at a node, the system determines the target shard and routes the document to that shard's active leader (solr.apache.org). The shard leader commits the change and forwards the update to all remaining shard replicas to preserve cluster consistency.
SolrCloud Replica Recovery After a Node Failure#
Replicas give read redundancy and fault tolerance. A node that drops out of the cluster must catch up before it serves traffic again. In SolrCloud, when a PULL replica disconnects, fails, or becomes unreachable, it cannot serve distributed queries upon reconnection until it completes an initial state recovery from the active shard leader (solr.apache.org). If the shard leader is offline or unavailable, the rejoining replica remains offline for query execution until leader election completes.
Write-Ahead Logging for Durable Index Writes#
Search engines buffer writes in memory and commit them to disk in batches, so they need a write-ahead log to survive crashes. Elasticsearch notes that Lucene commits are too expensive to run on every change (elastic.co). Each shard copy therefore writes operations into a transaction log, the translog. After a crash, acknowledged operations missing from the last commit are replayed from the translog when the shard recovers.
Handling Updates, Deletions and Tombstoning at Scale#
Index segments are immutable, so an update is a delete plus a new write. Elasticsearch describes segments as immutable storage units that are periodically merged into larger ones to keep index size down and to expunge deletes (elastic.co). Until a merge runs, a deleted document is only marked as gone. It still takes disk space and is filtered out at query time.
Two habits keep this manageable. First, store a tombstone record (ID, deleted flag, timestamp) in the source database, so a full rebuild never brings a deleted file back. Second, watch the share of deleted documents per index. A high share means merges are falling behind and queries are scanning dead entries.
Query Execution: Scatter-Gather Retrieval and Query Parsing#
A query on a sharded index runs as scatter-gather: a coordinating node sends the query to one copy of every shard, each shard scores its own documents, and the coordinator merges the top hits. Before that, the query parser fixes typos, normalizes word forms and expands synonyms so the right terms reach the index.
Scatter-Gather Across Shards#
Elasticsearch forwards a search to a node holding a copy of each shard's data, and by default picks replicas with adaptive replica selection, which weighs past response times (elastic.co). With the default query_then_fetch mode, documents are scored using term and document frequencies local to each shard. That is faster but less accurate (elastic.co). The dfs_query_then_fetch mode uses global frequencies across all shards, which is slower but more accurate. The slowest shard sets the latency for the whole query, so keep shard sizes even.
Typo Tolerance, Lemmatization and Synonym Expansion#
Typo tolerance usually relies on edit distance. The Elasticsearch fuzzy query returns documents with terms similar to the search term, measured by Levenshtein edit distance: the number of one-character changes needed to turn one term into another (elastic.co). Lemmatization maps a word to its dictionary form, such as "ran" to "run". Stemming only cuts suffixes, which is cheaper but cruder.
Synonyms belong at query time where possible. The Elasticsearch synonym_graph filter handles multi-word synonyms correctly and is designed for search analyzers only (elastic.co). Query-time synonyms can change without a full reindex.
Multi-Tenant Isolation and Document Access Control at Query Time#
Every query in a shared index must carry the caller's permissions, or one tenant can see another's files. Enforce this inside the search engine, not only in the app, so a missed filter in one code path cannot leak documents.
Role-Based Document Filters#
Elasticsearch document level security restricts the documents a user can read with a query defined per role (elastic.co). Documents that do not match the role query are never returned. If a user has several roles, the role queries combine with OR, so one match is enough. Filtered aliases are a lighter option: an alias can carry a filter that limits which documents it can access (elastic.co). Elastic warns that alias filters apply only to Query DSL searches, not to fetching a document by ID.
Choose the layout by tenant size. Many small tenants fit one shared index with a tenant_id field and a forced filter. A few large or regulated tenants are better on their own index, which also makes deleting a tenant a single index drop.
Zero-Downtime Index Migration and Blue-Green Reindexing#
Mapping changes, new analyzers or a new embedding model all need a full rebuild. Blue-green reindexing builds the new index next to the live one and then flips traffic in one step.
Alias Swaps for Blue-Green Reindexing#
Point the application at an alias, never at a raw index name. Elasticsearch lists reindexing data without downtime as a core use of aliases, and its aliases API runs multiple actions in a single atomic operation (elastic.co). The steps are: create the green index, backfill it from the source of truth, replay writes that arrived during the backfill, compare result sets on sample queries, then swap the alias. Keep the blue index for a day so you can swap back.
Relevance Ranking Models and Query Scoring#
First-pass lexical retrieval ranks documents by term weight and proximity before heavier scoring runs. BM25 is the usual default: it weighs rare terms more, caps the gain from repeated terms and adjusts for document length.
Term Weighting and Score Saturation Mechanics#
Traditional term weighting functions compute matching scores based on term frequency and corpus document frequency. Term frequency represents the count of times a term appears in a document, while inverse document frequency measures term rarity across the collection.
In the Okapi TF vector space model, the score for term w in document d is calculated by normalizing term frequency against document length (khoury.northeastern.edu):
okapi_tf(w, d) = tf(w, d) / (tf(w, d) + 0.5 + 1.5 × (len(d) / avg(len(d))))
Here, tf(w, d) denotes term frequency, len(d) is document length, and avg(len(d)) is the mean document length across the corpus (khoury.northeastern.edu). Standard TF-IDF calculates matching scores by multiplying okapi_tf(w, d) by the inverse document frequency factor log(D / df(w)) across each query term w, where D is the corpus document count and df(w) is the document frequency of term w:
tf_idf(d, q) = Σ (okapi_tf(w, d) × log(D / df(w)))
BM25 and Okapi TF prevent long documents from dominating results by comparing document length directly against average collection length (khoury.northeastern.edu), (emschwartz.me). Unlike basic TF-IDF models where repeated terms continuously push scores upward, BM25 uses a saturation curve that limits the marginal impact of repeated query terms.
Accumulator Scoring and Proximity Evaluation#
Query execution engines evaluate sparse term vectors using postings accumulators. Postings lists for each query term are traversed sequentially, accumulating term weights into a total score accumulator for any document containing at least one matching term (nlp.stanford.edu).
Proximity scoring boosts documents where query terms appear close together. The minimum span metric measures the shortest window of tokens in a document containing all matched query tokens. The minimum span score is evaluated using an exponential decay function (khoury.northeastern.edu):
score = λ^((s - k) / k)
In this expression, λ represents a constant base set to approximately 0.8, s is the minimum token span found, and k is the length of the matched query n-gram (khoury.northeastern.edu). If an n-gram of length 5 matches within an 8-word window, the proximity component calculates as 0.8^((8 - 5) / 5) = 0.8^0.6.
Hybrid Retrieval: Vector Embeddings, Approximate Nearest Neighbor and Reciprocal Rank Fusion#
Hybrid search runs BM25 keyword retrieval and vector search side by side, then merges the two ranked lists. Keywords catch exact IDs, codes and names. Vector embeddings catch paraphrases. Reciprocal rank fusion combines both lists without tuning score scales.
Vector Embeddings and Approximate Nearest Neighbor Search#
Dense vector retrieval maps passages into vector embeddings so queries match on meaning rather than shared tokens. In Elasticsearch, kNN search is the main way to query dense_vector fields after embeddings are stored (elastic.co). Approximate nearest neighbor search narrows the search to likely matches instead of scoring every document, which cuts latency on large datasets. Exact kNN gives accurate results but does not scale well. Query vectors must have the same dimension and come from the same model as the document vectors, so changing models means a blue-green reindex.
Combining Keyword and Semantic Results In hybrid architectures such as EPIC.search, systems execute both keyword searches and semantic vector searches against the underlying document store, then rank and combine the candidate pools to generate responses (github.com).#
User Query
│
├───► Sparse Inverted Index (BM25 Retrieval) ───► Candidate Set A (Lexical)
│ │
└───► Dense Vector Store (Embedding Distance) ───► Candidate Set B (Semantic)
│
▼
[Rank & Combine Fusion]
│
▼
[Top-K Scored Documents]
Reciprocal Rank Fusion for Score Merging#
BM25 scores and vector distances sit on different scales, so adding them directly is unreliable. Reciprocal rank fusion (RRF) avoids this by using rank positions only. Elasticsearch describes RRF as a method for combining result sets with different relevance indicators that requires no tuning (elastic.co). Each document scores the sum of 1 / (k + rank) across the lists it appears in, and the ranking constant k defaults to 60.
Worked example: a passage ranked 1st by BM25 and 3rd by vectors scores 1/61 + 1/63, about 0.0323. A passage ranked 2nd in only one list scores 1/62, about 0.0161. Agreement between the two retrievers wins.
Passage-to-Document Score Aggregation#
When documents are split into passages, each passage gets its own score, and those scores must roll up to the document. ScaleText aggregates matched passages per document by arithmetic mean, maximum, or a sum normalized by document length (nlp.fi.muni.cz). Maximum favors one strong passage. A length-normalized sum favors documents that match all the way through.
Next Step: Build Checklist for a Document Search Engine#
Use this order when you build or review a document search system. Each step removes one common failure before the next layer depends on it.
- Benchmark text normalization filters to confirm whether stemming or stop-word pruning aligns with query expectations without inflating memory (nlp.stanford.edu).
- Structure postings lists into chunked blocks and configure virtual memory large pages to accelerate traversal throughput (doi.org).
- Establish prefix-based routing across shard leaders and verify node recovery rules before deploying updates to production clusters (solr.apache.org).
- Pair lexical BM25 saturation with dense vector search, normalizing passage scores using length-adjusted aggregation functions (github.com), (nlp.fi.muni.cz), (emschwartz.me).
- Merge keyword and vector lists with reciprocal rank fusion, and serve every index through an alias so model or mapping changes ship as a blue-green swap (elastic.co).
- Enforce tenant and role filters inside the search engine, then test that a user from one tenant gets zero hits on another tenant's documents.
| Technique | Primary Mechanism | Dictionary Term Impact | Postings / Memory Impact |
|---|---|---|---|
| Stemming | Linguistic root reduction | Reduces distinct terms by 17% | Reduces nonpositional postings by 4% |
| Case Folding | Uniform lowercasing | Reduces distinct terms by 17% | Reduces nonpositional postings by 3% |
| Stop Word Removal (Top 150) | Pruning frequent vocabulary | Not specified | Cuts nonpositional postings by 25% to 30% |
| Inverted Index Compression (1:4) | Bit-level postings compression | Not specified | Reduces disk storage space by up to 75% |
| Dynamic List Chunking | Contiguous postings block layout | Not applicable | Almost halves linked-list memory; cuts cache-line reads |
| In-Chunk Compression | Encoding postings inside chunks | Not applicable | Halves remaining in-memory footprint with stable build speed |
| Retrieval / Scoring Model | Primary Scoring Inputs | Term Saturation Handling | Length Normalization Approach |
|---|---|---|---|
| Okapi TF | Term frequency, document length, average collection length | Controlled via fractional term frequency formula | Normalized against average document length (len(d) / avg(len(d))) |
| TF-IDF (Okapi-based) | Okapi TF score multiplied by inverse document frequency (log(D / dfw)) | Lacks saturation ceiling for recurring terms | Inherits Okapi TF document-to-corpus length normalization |
| Okapi BM25 | Term frequency, IDF, document length, average collection length | Includes explicit saturation function to limit repeated terms | Normalizes document length against corpus average length |
| Proximity Search (Min Span) | Minimum span window (s), matched n-gram length (k), constant base (λ ≈ 0.8) | Evaluated via exponential decay formula λ^((s - k) / k) | Calculated across span distance rather than full document length |
| ScaleText Document Aggregation | Passage/nugget similarity scores | Inherited from underlying passage similarity match | Arithmetic mean, maximum score, or sum normalized by document length |
Search Index Capacity and Shard Sizing Calculator
Estimates the raw text storage, inverted index size (accounting for stop-word filtering/compression reduction), total cluster storage capacity across primary and replica shards, and recommended shard count based on target Lucene shard capacity guidelines (e.g., 30-50 GB per shard).
Raw Corpus Volume:
Inverted Index Storage:
Total Primary Storage (_source + index):
Total Cluster Storage (Primary + Replicas):
Recommended Primary Shards:
Frequently Asked Questions
How do text preprocessing techniques impact inverted index size?
Stemming and case folding each reduce distinct dictionary terms by 17%, cutting nonpositional postings by 4% and 3%, respectively. Removing the 150 most common stop words reduces nonpositional postings by 25% to 30%.
How can in-memory inverted index performance be optimized?
Dynamic list chunking almost halves linked list memory requirements and dramatically cuts cache-line reads. Adding in-chunk postings compression further halves memory footprint, while virtual memory large pages accelerate index building by reducing page table walks.
Distributed search system design: How does shard routing work in SolrCloud?
SolrCloud’s compositeId router hashes an ID prefix before an exclamation mark (e.g., IBM!12345) to co-locate documents on a specific shard. Updates route to the active shard leader, which propagates changes to all replicas.
Document search system design interview questions: How does BM25 differ from TF-IDF?
Standard TF-IDF allows repeated terms to increase scores without bound. BM25 uses a term frequency saturation curve to cap repeated term impacts, and normalizes length by comparing document length to the collection average.
How do you merge keyword and vector search results?
Use reciprocal rank fusion. Each document scores the sum of 1/(k + rank) across the result lists, with k defaulting to 60 in Elasticsearch, so no score scaling or tuning is needed.
How do you merge keyword and vector search results?
Use reciprocal rank fusion. Each document scores the sum of 1/(k + rank) across the result lists, with k defaulting to 60 in Elasticsearch, so no score scaling or tuning is needed.
Sources
- Github - BC Government (GitHub) (accessed 2026)
- Building an Accessible, Usable, Scalable, and - Old Dominion University (2021-10-28)
- Efficient In-Memory, List-Based Text Inversion - ACM (2017-12-07)
- Introduction to Information Retrieval - Stanford NLP Group (Introduction to Information Retrieval) (accessed 2026)
- Indexing - Northeastern University (accessed 2026)
- Efficient scoring and ranking - Stanford NLP Group (Introduction to Information Retrieval) (accessed 2026)
- SolrCloud Shards and Indexing :: Apache Solr Reference Guide - Apache Software Foundation (accessed 2026)
- ScaleText: The Design of a Scalable, Adaptable and User-Friendly Document System for Similarity Searches - Masaryk University (RASLAN 2016) (2016-12-01)
- Comparing full text search algorithms: BM25, TF-IDF, and Postgres - Evan Schwartz - Evan Schwartz (2024-11-19)
- Apache Tika - Apache Software Foundation (accessed 2026)
- Elasticsearch Reference: rrf - elastic.co (accessed 2026)
- Elasticsearch Reference: index-modules-translog - elastic.co (accessed 2026)
- Elasticsearch Reference: index-modules-merge - elastic.co (accessed 2026)
- Elasticsearch Reference: search-shard-routing - elastic.co (accessed 2026)
- Elasticsearch Reference: search-search - elastic.co (accessed 2026)
- Elasticsearch Reference: query-dsl-fuzzy-query - elastic.co (accessed 2026)
- Elasticsearch Reference: analysis-synonym-graph-tokenfilter - elastic.co (accessed 2026)
- Elasticsearch Reference: document-level-security - elastic.co (accessed 2026)
- Elasticsearch Reference: aliases - elastic.co (accessed 2026)
- Elasticsearch Reference: knn-search - elastic.co (accessed 2026)
- Apache Tika - Apache Software Foundation (accessed 2026)
- Elasticsearch Reference: rrf - elastic.co (accessed 2026)
- Elasticsearch Reference: index-modules-translog - elastic.co (accessed 2026)
- Elasticsearch Reference: index-modules-merge - elastic.co (accessed 2026)
- Elasticsearch Reference: search-shard-routing - elastic.co (accessed 2026)
- Elasticsearch Reference: search-search - elastic.co (accessed 2026)
- Elasticsearch Reference: query-dsl-fuzzy-query - elastic.co (accessed 2026)
- Elasticsearch Reference: analysis-synonym-graph-tokenfilter - elastic.co (accessed 2026)
- Elasticsearch Reference: document-level-security - elastic.co (accessed 2026)
- Elasticsearch Reference: aliases - elastic.co (accessed 2026)
- Elasticsearch Reference: knn-search - elastic.co (accessed 2026)