Sub topic 3
Scaling Semantic Search
Assume you know basic Python, arrays, dot products, and keyword search. Approximate nearest-neighbor (ANN) search trades a small amount of recall for much lower query latency as collections grow.
ANN indexes: IVF and HNSW
An exact index compares a query with every stored vector. An ANN index examines only likely candidates.
- IVF (inverted file) clusters vectors into regions. At query time, it searches only the nearest
nprobeclusters. Highernprobeimproves recall but costs more time. - HNSW (Hierarchical Navigable Small World) builds layered graphs. Search follows links toward nearby vectors.
efSearchcontrols how many candidates it explores. Higher values usually improve recall and latency.
| Index | Main trade-off |
|---|---|
| IVF | Requires training; query cost depends on clusters searched |
| HNSW | Fast and accurate; uses more memory |
import faiss
import numpy as np
vectors = np.random.default_rng(0).random((10000, 384)).astype("float32")
faiss.normalize_L2(vectors)
index = faiss.IndexHNSWFlat(384, 32)
index.hnsw.efSearch = 64
index.add(vectors)
scores, ids = index.search(vectors[:1], 5)
print(ids[0])Stores, hybrid search, and reranking
A vector store adds persistence, metadata filters, updates, access control, and operational APIs around an index. It does not automatically make poor embeddings or chunks effective.
Hybrid search combines BM25, a keyword-ranking method, with vector search. BM25 handles exact names and identifiers; vectors handle paraphrases. Reciprocal rank fusion (RRF) combines result positions without comparing incompatible score scales.
A cross-encoder reranker reads the query and each candidate together, then predicts relevance. Retrieve perhaps 50 candidates cheaply, rerank them, and return the best 5. This improves precision but requires one model call per candidate pair.
Evaluation and common pitfalls
Use labeled queries containing relevant document IDs.
- Recall@k: fraction of relevant documents found in the first
k. - MRR (mean reciprocal rank): average of
1 / rankfor the first relevant result. - nDCG: rewards highly relevant results appearing near the top and supports graded relevance labels.
Normalize vectors when using cosine similarity or inner product. Follow the embedding model’s required query and document prefixes. Keep the model and preprocessing version with the index; changing either requires re-embedding. Test domain-specific language, because a general model may miss specialist meaning.
Applications
Retrieval supports retrieval-augmented generation (RAG), where retrieved passages provide evidence to a language model. The same vectors can group related items for clustering, find near-duplicates, or recommend content by semantic proximity.
Exercise
Which setting should you raise first when HNSW misses relevant results?
Show answer
Raise efSearch, then measure recall and latency again.