DatabasesVol. 4 · Part IV
0 / 0

Shelves / Databases

DB·63

Search Engines and Hybrid Search

How search engines find and rank text. Covers the inverted index, analysis (character filters, tokenisation, token filters), stemming and lemmatisation, relevance scoring from TF-IDF to BM25, filters versus queries, faceting, autocomplete, fuzzy matching, synonyms, engine architecture (segments, refresh, shards), then semantic search with embeddings and approximate nearest-neighbour indexes, and hybrid search with reciprocal rank fusion and reranking. Ends with evaluating relevance. Examples use Elasticsearch/OpenSearch, PostgreSQL with pgvector, Lucene, Tantivy and Meilisearch.

28 topics · ~25 min read · 31-question quiz
Updated Suggest a correction

Start here: finding what people mean

Search isn't a WHERE clause

A database answers precise questions: rows where name = 'Idli'. People searching type dosas, biriyani, or something light for breakfast, and expect the best matches first. Search differs from querying in three ways: matching is fuzzy (plurals, typos, synonyms, meaning), results are ranked by relevance, and it must be fast across millions of documents. Search engines are built around a different index.

The inverted index

Python
idx = defaultdict(set)
for name, desc, … in DISHES:
    for w in re.findall(r"[a-z]+", (name + " " + desc).lower()): idx[w].add(name)
Text
inverted index entries: 'coconut' → ['Appam with stew', 'Fish curry', 'Masala dosa', 'Sundal'] … | 229 distinct terms over 40 dishes
'coconut' AND 'chutney' → ['Masala dosa', 'Vada']

An inverted index maps each term to the list of documents containing it (its postings), like the index at the back of a cookbook. A multi-word query intersects or unions postings lists instead of scanning text, which is why search engines answer in milliseconds over billions of documents. Turning text into terms is analysis: splitting into tokens, lowercasing, removing accents and very common words, and stemming (reducing "dosas" and "dosa's" to "dosa").

Ranking with BM25

Text
BM25 'dosa':                  [('Plain dosa', 2.41), ('Rava dosa', 2.41), ('Masala dosa', 2.41)]
'dosas' (stemmed to dosa):    [('Plain dosa', 2.41), ('Rava dosa', 2.41), ('Masala dosa', 2.41)]
'biriyani' (typo), exact:     [] | fuzzy, edit distance 2: [('Mutton biryani', 2.0), ('Chicken biryani', 1.0), ('Vegetable biryani', 1.0)]
'something light for breakfast': [('Pesarattu', 5.51), ('Sundal', 2.74)]

BM25, the standard lexical ranking formula, scores a document higher when the query's terms appear in it more often (with diminishing returns), when those terms are rare across the collection (matching "pesarattu" means more than matching "with"), and when the document is short. Stemming made dosas find the dosas; fuzzy matching (terms within a couple of character edits) rescued the misspelling biriyani. But the last query exposes lexical search's limit: it found Pesarattu only because its description happens to contain both "light" and "breakfast". Idli, Upma and Pongal are light breakfasts too, and their descriptions use other words ("steamed", "porridge", "comforting").

Searching by meaning: embeddings

An embedding model maps text to a vector (here 384 numbers) such that texts with similar meanings get nearby vectors. Search becomes "find the dish vectors nearest the query vector":

Text
semantic 'something light for breakfast': [('Pesarattu', 0.42), ('Egg curry', 0.41), ('Poori masala', 0.4), ('Pongal', 0.37)]
semantic 'cold drink for a hot day':      [('Buttermilk', 0.5), ('Tender coconut water', 0.48), ('Fresh lime soda', 0.43), ('Filter coffee', 0.42)]
semantic 'dosa':                          [('Masala dosa', 0.46), ('Plain dosa', 0.45), ('Rava dosa', 0.33), ('Sundal', 0.27)]

"Cold drink for a hot day" found buttermilk, coconut water and lime soda, none of which contains the words "cold" or "hot" (buttermilk says "cooling in summer"). Semantic search understands paraphrase, but it's imprecise in its own way: Egg curry ranked second for a light breakfast, and Pesarattu (a dosa-like crepe) was missed for "dosa". The two approaches fail differently, which is why modern search runs both and merges the results (hybrid search); the lab measures each on ten queries.

Where search runs

Option Use when
PostgreSQL full-text (tsvector, GIN) and pg_trgm Search over data already in PostgreSQL, moderate scale, simple ranking
Elasticsearch / OpenSearch Large-scale search and analytics, rich relevance tuning, aggregations and facets
Meilisearch, Typesense Instant, typo-tolerant site and product search with little tuning
Vector databases (pgvector, Qdrant, Milvus, Weaviate) Semantic and hybrid search, retrieval for AI assistants (Volume 14b)

A search index is almost always a copy of data whose source of truth is elsewhere, kept in sync by indexing jobs or change-data capture, and it's allowed to lag slightly.

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain inverted indexes, relevance ranking, fuzzy and semantic search
L2 Build search with PostgreSQL FTS or Elasticsearch/OpenSearch, with analyzers, filters and facets
L3 Explain BM25, analysis chains, segment-based engines, embeddings, ANN indexes (HNSW) and fusion
L4 Diagnose poor relevance, slow queries, sync lag and recall loss with judged query sets
L5 Design search architecture (indexing pipeline, hybrid retrieval, reranking, evaluation)
L6 Run search platforms and relevance programmes with metrics and experimentation

How lexical search works

Why databases aren't search engines

WHERE description ILIKE '%noise cancelling%' has four problems:

  • It can't use a normal index, so it scans everything.
  • It matches substrings, not words ("cancelling" won't match "cancel" or "canceled").
  • It has no notion of relevance: which of 10,000 matches is best?
  • It doesn't handle typos, synonyms, languages or phrases.

Search engines (Apache Lucene underneath Elasticsearch, OpenSearch and Solr; Tantivy in Rust, underneath Quickwit and ParadeDB; Meilisearch; Typesense; Vespa) are built around one data structure and one idea: the inverted index, and ranking by relevance.

The inverted index

A book's index maps terms → pages. An inverted index maps terms → the documents containing them (a postings list), usually with positions and frequencies:

1: Wireless noise-cancellingheadphones 2: Wired headphones, noiseisolation 3: Wireless earbuds term → postings (doc:tf@positions) wireless → 1:1@0, 3:1@0 nois → 1:1@1, 2:1@3 cancel → 1:1@2 headphon → 1:1@3, 2:1@1 wire → 2:1@0 isol → 2:1@4 earbud → 3:1@1 query "wireless headphones" AND: {1,3} ∩ {1,2} = {1} OR: {1,2,3}, ranked by BM25 Postings are sorted and compressed (delta + bit-packing), so intersections are fast merges with skip lists
An inverted index. Documents are analysed into terms; each term maps to a sorted postings list of document IDs with term frequencies and positions. A query intersects or unions postings lists and scores the matches.
  • Postings lists are sorted by document ID and heavily compressed (delta encoding plus bit-packing or variable-byte), so intersecting them is a fast merge with skip pointers.
  • Positions enable phrase queries ("noise cancelling" as adjacent terms) and proximity.
  • Term dictionaries (an FST, finite-state transducer, in Lucene) map terms to postings compactly and support prefix and fuzzy lookups.
  • Doc values (a columnar per-field store) back sorting, aggregations and facets, while the inverted index answers "which documents match?".

PostgreSQL's GIN index over tsvector is the same idea inside a database (chapter 56).

Analysis: tokenisation, normalisation, stemming

Text is processed by an analyser at index time and at query time. Both sides must produce compatible terms, or nothing matches:

Text
"The Wireless Noise-Cancelling Headphones' battery lasts 30h!"
 │ character filters   strip HTML, map characters (ß → ss), normalise Unicode (NFKC)
 ▼
 │ tokenizer           split into tokens: [The] [Wireless] [Noise] [Cancelling] [Headphones'] [battery] [lasts] [30h]
 ▼                      (standard tokenizer: Unicode word boundaries, UAX #29)
 │ token filters       lowercase → remove stop words (the) → possessive strip → ASCII folding (é → e)
 ▼                      → stemming (cancelling → cancel, headphones → headphon, lasts → last) → synonyms
 [wireless] [nois] [cancel] [headphon] [batteri] [last] [30h]

Key choices:

  • Tokenisation is language-dependent. Whitespace and punctuation rules work for English. Chinese, Japanese and Thai have no spaces and need dictionary-based segmenters (ICU, kuromoji, smartcn) or n-grams. Product codes and emails need custom tokenisers, so that "SKU-1234-XL" stays searchable as a whole and as parts.
  • Stemming chops words to a stem with rules (the Porter and Snowball stemmers): "running", "runs" → "run", but also "university" and "universe" → "univers" (over-stemming). It's fast and language-specific, and doesn't need real words.
  • Lemmatisation maps to the dictionary form using vocabulary and morphology ("better" → "good", "went" → "go"). It's more accurate and costlier.
  • Stop words (the, a, of) shrink the index but break phrase queries like "to be or not to be". Modern engines often keep them and rely on BM25 to down-weight common terms.
  • ASCII folding and Unicode normalisation: "café" versus "cafe", full-width versus half-width characters.
  • Use multi-field mappings: index the same text several ways (title stemmed, title.exact keyword, title.ngram for partial matching) and query whichever fits.
JSON
PUT /products
{
  "settings": {
    "analysis": {
      "filter": {
        "en_stem": { "type": "stemmer", "language": "english" },
        "product_synonyms": { "type": "synonym_graph", "synonyms": ["tv, television", "earbuds, earphones, in-ear headphones"], "updateable": true }
      },
      "analyzer": {
        "en_index":  { "tokenizer": "standard", "filter": ["lowercase", "asciifolding", "en_stem"] },
        "en_search": { "tokenizer": "standard", "filter": ["lowercase", "asciifolding", "product_synonyms", "en_stem"] }
      }
    }
  },
  "mappings": {
    "properties": {
      "name":        { "type": "text", "analyzer": "en_index", "search_analyzer": "en_search",
                       "fields": { "exact": { "type": "keyword" } } },
      "description": { "type": "text", "analyzer": "en_index", "search_analyzer": "en_search" },
      "brand":       { "type": "keyword" },
      "price":       { "type": "scaled_float", "scaling_factor": 100 },
      "in_stock":    { "type": "boolean" },
      "embedding":   { "type": "dense_vector", "dims": 768, "index": true, "similarity": "cosine" }
    }
  }
}

Relevance: from TF-IDF to BM25

Matching documents must be ranked. The classic intuitions:

  • Term frequency (TF): a document mentioning "headphones" five times is probably more about headphones than one mentioning it once, with diminishing returns.
  • Inverse document frequency (IDF): rare terms carry more information. "cancelling" matters more than "the".
  • Length normalisation: a match in a short title means more than the same match in a 5,000-word description.

BM25 (Okapi Best Matching 25, Robertson and others, 1990s) is the default in Lucene since version 6. It combines the three with saturating TF:

Text
score(D, Q) = Σ over query terms t:   IDF(t) · tf(t,D) · (k1 + 1)
                                       ───────────────────────────────────────────────
                                       tf(t,D) + k1 · (1 − b + b · |D| / avgdl)

IDF(t) = ln(1 + (N − n(t) + 0.5) / (n(t) + 0.5))      N = docs, n(t) = docs containing t
k1 ≈ 1.2  controls TF saturation (higher = more weight for repeated terms)
b  ≈ 0.75 controls length normalisation (0 = none, 1 = full)
term frequencyscore contribution linear TF BM25 (k1 = 1.2) ceiling (k1 + 1) · IDF 1 2 3 4 5 …
BM25 term-frequency saturation. Under TF-IDF, score grows linearly with term frequency; under BM25 it rises quickly then flattens toward a ceiling set by k1, so keyword stuffing gains little.

Beyond BM25, real relevance combines business signals:

  • Field boosts: a title match outranks a description match ("title^3").
  • Phrase and proximity boosts.
  • Freshness, popularity, conversion rate, rating and margin: function_score/script_score with decay functions.
  • Personalisation.
  • Learning to rank (LTR): train a model (LambdaMART, gradient-boosted trees) on click and judgement data to re-rank the top results.
JSON
GET /products/_search
{
  "query": {
    "function_score": {
      "query": {
        "bool": {
          "must": [{ "multi_match": { "query": "wireless headphones", "fields": ["name^3", "description"], "type": "best_fields" } }],
          "should": [{ "match_phrase": { "name": { "query": "wireless headphones", "boost": 2 } } }],
          "filter": [
            { "term": { "in_stock": true } },
            { "range": { "price": { "lte": 200 } } },
            { "terms": { "brand": ["Sony", "Bose"] } }
          ]
        }
      },
      "functions": [
        { "field_value_factor": { "field": "popularity", "modifier": "log1p", "factor": 0.5 } },
        { "gauss": { "release_date": { "origin": "now", "scale": "180d", "decay": 0.5 } } }
      ],
      "boost_mode": "multiply"
    }
  },
  "aggs": {
    "brands": { "terms": { "field": "brand", "size": 20 } },
    "price_ranges": { "range": { "field": "price", "ranges": [{ "to": 50 }, { "from": 50, "to": 150 }, { "from": 150 }] } }
  },
  "highlight": { "fields": { "description": {} } },
  "size": 20
}

Search features

Filters versus queries

  • Query context (must, should): does it match, and how well? Contributes to the score.
  • Filter context (filter, must_not): does it match: yes or no? No scoring. Results are cacheable as bitsets and cheap.

Put structured constraints (in stock, price range, category, tenant, permissions) in filters, and keep the free text in queries. That's faster, and it keeps scores meaningful.

Security filtering is a filter too: multi-tenant and permission-scoped search must filter by tenant or ACL on every query (or use separate indexes per tenant). It's the same BOLA risk as APIs (Vol. 3 ch. 50).

Faceting

Facets are the counts in a sidebar ("Brand: Sony (42), Bose (17)…"), computed over the current result set with aggregations on doc values (terms, range, histogram, date_histogram). The UX subtlety is multi-select facets: when a user selects "Sony", the brand facet should still show counts for other brands (computed without the brand filter), while other facets use it. Engines handle this with post_filter plus per-facet filtered aggregations (Elasticsearch), or tagging and excluding filters (Solr, Typesense, Algolia).

Autocomplete

Search-as-you-type needs prefix matching with very low latency (under about 50 ms):

Technique How Notes
Edge n-grams at index time "headphones" → h, he, hea, head, … indexed; the query is matched as typed Flexible (works mid-phrase with shingles), bigger index
Completion suggester / FST An in-memory finite-state transducer of suggestions with weights Extremely fast prefix lookup; suggestions only, not full search
search_as_you_type field type (Elasticsearch) Shingles + edge n-grams subfields Convenient
Query suggestions from logs Popular past queries matching the prefix Often the best UX ("did people search this?")
Postgres LIKE 'prefix%' with text_pattern_ops, or pg_trgm Fine for modest scale

Combine autocomplete with typo tolerance for short prefixes carefully: one edit on a 3-letter prefix matches almost everything.

Fuzzy search and typo tolerance

Fuzzy matching finds terms within a small edit distance (Levenshtein, or Damerau-Levenshtein, which also counts transpositions) of the query term. "headphnoes" matches "headphones":

  • Elasticsearch "fuzziness": "AUTO" allows 0 edits for terms of 1–2 characters, 1 edit for 3–5, and 2 for longer terms. Lucene implements it efficiently with Levenshtein automata intersected with the term dictionary FST.
  • Set prefix_length (the first characters must match exactly) for speed and precision, and down-weight fuzzy matches relative to exact ones.
  • Phonetic analysers (Soundex, Metaphone) handle names that sound alike.
  • Did-you-mean suggestions use term suggesters or query logs.
  • PostgreSQL offers pg_trgm similarity (%, similarity(), word_similarity()) with GIN/GiST indexes, and fuzzystrmatch (levenshtein()).

Meilisearch and Typesense are built around typo tolerance and prefix search by default, with simple relevance rules. That's a good fit for site and product search with less tuning effort.

Synonyms

Users say "TV" and catalogues say "television". Synonyms expand or normalise terms:

  • Equivalent synonyms: tv, television.
  • One-way synonyms: ipod => ipod, mp3 player (searching "ipod" also finds MP3 players, but not vice versa).
  • Multi-word synonyms ("new york", nyc) need graph-aware token filters (synonym_graph) to keep phrase positions correct.
  • Query-time synonyms (preferred) can be updated without reindexing (Elasticsearch's updateable synonym sets and the synonyms API). Index-time synonyms bloat the index and need reindexing to change.
  • Synonym lists come from domain knowledge, query logs (users who search A and click results for B), and are now often supplemented by semantic search, which learns many synonyms implicitly.

Engine architecture

How Lucene-based engines index and serve:

  • Segments: new documents are buffered in memory, then written as small immutable segments (each a mini inverted index). A search queries all segments and merges results. Background merges combine small segments into bigger ones (like LSM compaction, chapter 58). Deletes are marked in bitsets and purged at merge.
  • Refresh (every 1 s by default) makes new segments searchable: near-real-time search. A flush/commit fsyncs segments, and the translog (a WAL) makes acknowledged writes durable in between.
  • Shards: an index is split into primary shards (each a Lucene index), with replicas for availability and read throughput. A query fans out to one copy of every shard, and the coordinating node merges the top-k (scatter-gather). Too many small shards waste resources; a common guideline is shards of about 10–50 GB.
  • Mappings are mostly fixed once data is indexed. Changing an analyser or field type means reindexing into a new index and switching an alias atomically. Design for zero-downtime reindexing from day one.
  • Keeping the index in sync: index from the system of record via CDC or events (Debezium → Kafka → indexer), with idempotent upserts by document ID and versioning (version_type: external) so out-of-order updates don't overwrite newer data. Periodic reconciliation catches drift.

Semantic search with embeddings

Lexical search matches words. It fails on vocabulary mismatch: a query for "laptop for video editing" doesn't match a product described as "notebook with high-performance GPU and colour-accurate display". Semantic search matches meaning:

  1. An embedding model (a neural text encoder) maps text to a dense vector, typically 384–3,072 dimensions, such that semantically similar texts are close (by cosine similarity or dot product).
  2. Embed every document (or chunk) at index time, and embed the query at search time.
  3. Return the nearest neighbours of the query vector.

Exact nearest-neighbour search compares the query with every vector, which is O(N·d). At millions of vectors, engines use approximate nearest neighbour (ANN) indexes:

ANN index Idea Trade-offs
HNSW (hierarchical navigable small world) A multi-layer proximity graph; greedy search descends from sparse upper layers to a dense bottom layer Excellent recall and latency; memory-hungry; slower builds. Default in most engines (Lucene, pgvector, Qdrant, Weaviate, Milvus)
IVF (inverted file) Cluster vectors (k-means); search only the nearest clusters (nprobe) Smaller and faster to build; recall depends on probes
Product quantisation (PQ), scalar or binary quantisation Compress vectors (for example float32 → int8, or 1-bit binary), rescoring the top candidates with full precision Large memory savings with a small recall loss
DiskANN / Vamana A graph index designed for SSDs Billion-scale on modest RAM
SQL
-- PostgreSQL + pgvector: semantic search next to your relational data (and transactional consistency)
CREATE EXTENSION IF NOT EXISTS vector;
ALTER TABLE products ADD COLUMN embedding vector(768);
CREATE INDEX products_embedding_hnsw ON products USING hnsw (embedding vector_cosine_ops)
  WITH (m = 16, ef_construction = 64);

SET hnsw.ef_search = 100;                                   -- recall/latency knob at query time
SELECT id, name, 1 - (embedding <=> $1) AS cosine_similarity  -- <=> is cosine distance
FROM products
WHERE in_stock                                              -- filtering + ANN: watch recall (iterative scans help, pgvector 0.8+)
ORDER BY embedding <=> $1
LIMIT 20;

Considerations:

  • Chunking long documents (paragraph or section chunks with overlap) for RAG and passage retrieval.
  • Model choice and versioning: changing models means re-embedding everything, so store the model name with the vector.
  • Multilingual models for multilingual search.
  • Filters combined with ANN (pre-filtering versus post-filtering affects recall).
  • Cost of embedding at index and query time.

Semantic search is weaker than lexical search at exact terms: product codes, names, rare jargon and negation ("headphones without noise cancelling").

Hybrid search: lexical + semantic → fusion and reranking

Since lexical and semantic retrieval fail differently, hybrid search runs both and fuses the results, then optionally reranks the top candidates with a stronger model:

query lexical (BM25)top 100 semantic (ANN)embed → top 100 fusionRRF → top 50 rerankcross-encoder RRF(d) = Σ 1 / (60 + rank_i(d)) then filters and boosts → top 10
Hybrid search pipeline. The query runs through lexical BM25 retrieval and vector ANN retrieval in parallel; the two ranked lists are fused (for example with reciprocal rank fusion); the top candidates are reranked by a cross-encoder; business rules and filters produce the final page.

Fusion: the two retrievers' scores aren't comparable (BM25 is unbounded, cosine similarity lies in [−1, 1]), so combine by rank or by normalised score:

  • Reciprocal Rank Fusion (RRF): score(d) = Σ_i 1 / (k + rank_i(d)) with k ≈ 60. It's simple, robust, needs no tuning, and is built into Elasticsearch (rrf retriever), OpenSearch (hybrid query + normalisation processor), Azure AI Search, MongoDB Atlas and Weaviate.
  • Convex combination: α · norm(bm25) + (1 − α) · norm(cosine). It can beat RRF when tuned on judged data.

Reranking: retrieval models (bi-encoders) embed query and document separately, which is fast but loses interaction. A cross-encoder reranker reads the query and each candidate together and outputs a relevance score. It's much more accurate and too slow for millions of documents, so apply it to the top 50–200 fused candidates. Rerankers include open models (BGE reranker, mixedbread), API services, and LLM-based rerankers for high-value queries.

SQL
-- Hybrid search with RRF entirely in PostgreSQL (full-text + pgvector)
WITH lexical AS (
    SELECT id, row_number() OVER (ORDER BY ts_rank_cd(search, q) DESC) AS r
    FROM products, websearch_to_tsquery('english', $1) q
    WHERE search @@ q
    ORDER BY ts_rank_cd(search, q) DESC LIMIT 100
),
semantic AS (
    SELECT id, row_number() OVER (ORDER BY embedding <=> $2) AS r
    FROM products ORDER BY embedding <=> $2 LIMIT 100
)
SELECT p.id, p.name,
       coalesce(1.0 / (60 + l.r), 0) + coalesce(1.0 / (60 + s.r), 0) AS rrf
FROM lexical l
FULL JOIN semantic s USING (id)
JOIN products p ON p.id = coalesce(l.id, s.id)
ORDER BY rrf DESC
LIMIT 20;

Hybrid retrieval plus reranking is also the retrieval stage of RAG (retrieval-augmented generation): fetch the best passages, then give them to an LLM as context (Vol. 13 covers AI systems). Good retrieval quality is the largest determinant of answer quality.

Evaluating relevance

You can't tune what you don't measure. Build a judgement set: queries with graded relevant documents, from expert labelling, click logs (with position-bias corrections) or LLM-assisted judging validated by humans. Then measure:

Metric Measures
Precision@k The fraction of the top k results that are relevant
Recall@k The fraction of all relevant documents found in the top k (critical for retrieval before reranking)
MRR (mean reciprocal rank) How high the first relevant result appears (navigational queries)
NDCG@k (normalised discounted cumulative gain) Graded relevance with a position discount: the standard ranking metric
Online metrics Click-through rate, zero-result rate, query reformulation rate, conversion, time to first click; A/B tests and interleaving

Workflow: change one thing (analyser, synonyms, boosts, embedding model, fusion weights), run the offline evaluation (Elasticsearch's Ranking Evaluation API, Quepid, custom scripts), then confirm online with an A/B test. Also monitor zero-result queries (a list of missing synonyms and content gaps) and slow queries.

Search engines across the ecosystem

Engine Language Notes
Elasticsearch Java (Lucene) Full-featured: lexical, vector (HNSW with quantisation), hybrid (RRF retrievers), aggregations, LTR; also observability. Licensing changed in 2021 and AGPL was added as an option in 2024
OpenSearch Java (Lucene) Apache-2.0 fork; neural and hybrid search plugins, k-NN with several engines
Apache Solr Java (Lucene) Mature and highly configurable; dense vector support
Vespa Java/C++ Large-scale serving with ML ranking, tensors, hybrid (Yahoo's engine)
Meilisearch, Typesense Rust, C++ Developer-friendly, typo-tolerant instant search with simple relevance and vector/hybrid support
Tantivy (library), Quickwit, ParadeDB (pg_search: BM25 inside PostgreSQL) Rust A Lucene-like library in Rust; ParadeDB brings Tantivy-based BM25 into Postgres
PostgreSQL FTS + pg_trgm + pgvector C Good enough for many apps; transactional consistency with your data; no extra system
Vector databases: Qdrant (Rust), Milvus (Go/C++), Weaviate (Go), Pinecone (managed), Chroma — Vector-first, with filtering, quantisation and hybrid features
Algolia, Azure AI Search, Vertex AI Search, Amazon OpenSearch Service, Elastic Cloud Managed Hosted search services
Java
// Lucene from Java: the engine under Elasticsearch, OpenSearch and Solr, usable directly as a library
try (var dir = FSDirectory.open(Path.of("idx")); var w = new IndexWriter(dir, new IndexWriterConfig(new EnglishAnalyzer()))) {
    var doc = new Document();
    doc.add(new StringField("id", "p-1", Field.Store.YES));
    doc.add(new TextField("name", "Wireless noise-cancelling headphones", Field.Store.YES));
    doc.add(new KnnFloatVectorField("vec", embed("Wireless noise-cancelling headphones"), VectorSimilarityFunction.COSINE));
    w.addDocument(doc);
}
// Query: BooleanQuery of term/phrase queries scored by BM25, or KnnFloatVectorQuery for ANN
Rust
// Tantivy (Rust): build a schema, index documents, query with BM25
let mut sb = Schema::builder();
let name = sb.add_text_field("name", TEXT | STORED);
let index = Index::create_in_ram(sb.build());
let mut writer = index.writer(50_000_000)?;
writer.add_document(doc!(name => "Wireless noise-cancelling headphones"))?;
writer.commit()?;
let searcher = index.reader()?.searcher();
let query = QueryParser::for_index(&index, vec![name]).parse_query("wireless headphones")?;
let top = searcher.search(&query, &TopDocs::with_limit(10))?;

Tantivy (a Lucene-style engine) from Python, PostgreSQL 16 full-text search, the all-MiniLM-L6-v2 embedding model (implemented in NumPy from its published weights; its similarities match the reference values), and hnswlib for approximate nearest-neighbour search, on a 2-core machine.

Experiment 1: lexical, semantic and hybrid relevance

Ten queries over the 40-dish menu, each with a hand-made list of relevant dishes. nDCG@5 scores the top five results: 1.0 is a perfect ranking, and relevant dishes ranked lower count less. Lexical search used BM25 with stemming and one-edit fuzzy matching; hybrid merged both rankings with reciprocal rank fusion (RRF: each result scores 1/(60 + rank) per list).

Text
query                            lexical  semantic  hybrid(RRF)
dosa                               0.83      0.83        0.83
dosas                              0.83      0.83        0.83
biriyani                           1.00      1.00        1.00
something light for breakfast      0.47      0.49        0.55
cold drink for a hot day           0.39      0.83        0.64
spicy chicken                      1.00      0.61        1.00
rice dishes                        0.72      0.17        0.70
sweet                              0.49      0.38        0.51
vegetarian protein                 0.39      0.64        0.64
coconut                            1.00      0.85        1.00
mean                               0.71      0.66        0.77

Neither approach dominates. Semantic search won clearly on paraphrased needs ("cold drink for a hot day", "vegetarian protein"), and lost badly where the right answer is a literal attribute ("rice dishes": the embedding of "rice dishes" sits nearer to generic food than to biryani). Lexical search was perfect on words that appear in the text ("coconut", "spicy chicken"). Hybrid was never the worst and had the best mean, which is why production systems (Elasticsearch, OpenSearch, Vespa, most RAG pipelines) default to it, often followed by a reranker (a cross-encoder model that scores each query-document pair) on the top 50. The general lesson is the method: build a judged query set from real searches and measure every change against it, because relevance changes that look obviously better often aren't.

Experiment 2: full-text search at scale

500,000 short reviews made of menu words; query: reviews mentioning both "cashews" and "saffron":

Text
ILIKE scan:                                      438 ms (5234 matches)
PostgreSQL tsvector, no index:                    70 ms
PostgreSQL tsvector + GIN index:                 6.8 ms
PostgreSQL GIN + ts_rank, top 10:               10.2 ms
tantivy, BM25 top 10 + count:                    0.7 ms (index built in 3.1 s)

ILIKE compares raw strings row by row; a stored tsvector (pre-analysed terms) was 6× faster even without an index, and a GIN inverted index made it 64× faster. PostgreSQL full-text search is a good choice up to millions of documents when the data already lives there and ranking needs are simple. A dedicated engine was another 10× faster here and, more importantly, offers BM25, field boosts, typo tolerance, facets, highlighting and distributed indexes. The price is a second system to run and keep in sync.

Experiment 3: approximate nearest neighbours

Semantic search compares the query vector with every document vector, which is fine for 40 dishes and too slow for millions. 200,000 vectors of 384 dimensions (clustered around 2,000 topics, like real embeddings), 500 queries, top 10:

Text
exact (brute force): 22.59 ms/query | HNSW index built in 76 s
HNSW ef_search= 10: 0.046 ms/query, recall@10 0.841
HNSW ef_search= 40: 0.096 ms/query, recall@10 0.994
HNSW ef_search=100: 0.169 ms/query, recall@10 1.000
HNSW ef_search=400: 0.795 ms/query, recall@10 1.000

HNSW (hierarchical navigable small world graphs) links each vector to nearby vectors in a layered graph and searches greedily from coarse to fine layers. With ef_search=40 it found 99.4% of the true top 10 at 235× the speed of brute force; raising ef_search buys recall with time. The costs are build time (76 s here, mostly CPU), memory (the graph plus the vectors, usually held in RAM) and the fact that results are approximate. pgvector (HNSW and IVFFlat indexes in PostgreSQL), Qdrant, Milvus, Weaviate, OpenSearch and Elasticsearch all expose these knobs. One warning from building this experiment: on structureless data, where every query is about equally far from everything, recall collapses (an early version with very noisy queries got 0.11 at ef_search=200); measure recall on your own embeddings rather than trusting defaults.

Try it yourself

  1. Add a synonym list (biryani ↔ biriyani, curd ↔ yoghurt) to the lexical search and rerun experiment 1. Which queries improve?
  2. Add a facet: count results by category for the query "rice", using tantivy's or PostgreSQL's grouping.
  3. Weight RRF 2:1 in favour of lexical results and see how the mean nDCG moves; then add a third list (dish names only) to the fusion.
  4. Load experiment 3's vectors into pgvector (CREATE INDEX … USING hnsw (embedding vector_ip_ops)) and compare recall and latency with hnswlib.

Key ideas

  • Why separate search: fuzzy matching, relevance ranking, text analysis and speed over large text; databases are optimised for exact predicates.
  • Inverted index: terms → postings (document ids, frequencies, positions); immutable segments merged in the background (Lucene); near-real-time refresh.
  • Analysis: tokenisers, lowercasing, ASCII folding, stop words, stemming vs lemmatisation, n-grams and edge n-grams for autocomplete, language-specific analyzers.
  • Ranking: TF-IDF, BM25 (k1, b), field boosts, function scores (recency, popularity), learning to rank.
  • Features: filters (cached, unscored) vs queries (scored), facets/aggregations, autocomplete, fuzzy matching (edit distance), synonyms, highlighting.
  • Engines: Lucene-based Elasticsearch/OpenSearch/Solr, tantivy/Quickwit, Meilisearch, Typesense, Vespa; PostgreSQL tsvector/GIN and pg_trgm.
  • Semantic search: embedding models, cosine/inner-product similarity, chunking; ANN indexes (HNSW, IVF, product quantisation), recall vs latency.
  • Hybrid: lexical + semantic retrieval, fusion (RRF, weighted scores), reranking with cross-encoders.
  • Evaluation: judged query sets, precision/recall@k, nDCG, MRR; online metrics (click-through, zero-result rate).
  • Architecture: search index as a derived copy, kept in sync by indexing pipelines or CDC; reindexing with aliases.

Numbers to remember

  • Lab: mean nDCG@5 lexical 0.71, semantic 0.66, hybrid 0.77; GIN full-text 64× faster than ILIKE on 500,000 documents, tantivy another 10×; HNSW 0.994 recall@10 at 235× the speed of brute force on 200,000 vectors.

Pitfalls

  • LIKE '%term%' as a search engine; no stemming or typo tolerance.
  • Semantic-only search failing on names, codes and exact attributes.
  • Tuning relevance by anecdote instead of a judged query set.
  • Treating the search index as the source of truth; no reindex plan.
  • ANN defaults without measuring recall on your data; embedding-model changes without re-embedding everything.

Glossary

  • Postings list: the documents containing a term.
  • BM25: the standard probabilistic lexical ranking function.
  • Embedding: a vector representation of text capturing meaning.
  • ANN: approximate nearest-neighbour search.
  • RRF: reciprocal rank fusion, combining rankings by summed 1/(k + rank).
  • nDCG: normalised discounted cumulative gain, a ranking quality metric.