Sub topic 1
When Database Queries Are Not Enough
Prerequisites
Assume you know basic SQL, REST APIs, service-to-service communication, message queues, caching, and horizontal scaling.
When Database Queries Are Not Enough
Database queries work well for exact lookups and structured filters such as category = 'book'. A dedicated search service becomes useful when users expect relevance ranking, typo tolerance, stemming, autocomplete, faceting, or fast searches across large text fields.
A search service usually adds operational cost and eventual consistency. Use database full-text search when the data set, query load, and ranking needs are modest. Choose a separate engine when search is a major product feature or must scale independently.
How an Inverted Index Works
An inverted index maps each searchable term to the documents containing it. For example, the term running might point to documents 1 and 2. A query can find matching document sets without scanning every document.
index = {
"red": {1, 3},
"running": {1, 2},
"jacket": {2, 3},
}
matches = index["red"] & index["jacket"]
print(matches) # {3}The index is fast for term lookups, but it depends on how text is processed before indexing.
Text Analysis: From Raw Text to Searchable Terms
Text analysis converts raw text into terms. Tokenizing splits text into words. Normalizing can lowercase words and remove punctuation. Stemming reduces related forms, such as running and runs, to a shared representation.
The same analysis should usually apply to indexed text and user queries. Otherwise, a query may search for terms that the index never stored.
Ranking Results with TF-IDF and BM25
Ranking assigns a relevance score to each matching document. TF-IDF rewards terms that appear often in a document but rarely across the whole collection. BM25 improves this approach by limiting the benefit of repeated terms and adjusting for document length.
A common BM25 score combines term frequency, inverse document frequency, and length normalization. Its parameters control how strongly repetition and document length affect ranking. Test these choices against real user queries rather than assuming the default ranking is correct.
Choosing a Search Engine
| Option | Best fit | Main trade-off |
|---|---|---|
| Database full-text search | Small or moderate systems | Fewer search features and less independent scaling |
| Dedicated search engine | Rich search and high query load | More infrastructure and synchronization work |
Choose based on query features, scale, latency, team experience, and failure behavior.
Exercise
When is a database full-text feature usually preferable to a dedicated search engine?
Show answer
Prefer it when search needs are modest, the data set and query load fit the database, and avoiding synchronization infrastructure matters more than advanced search features.