Vector Databases: Indexes for Semantic Search
A vector database answers one question very fast: which stored points are closest to this one in a high-dimensional space. That sounds narrow until you realize that almost every modern AI feature â semantic search, recommendations, deduplication, retrieval-augmented generation, anomaly flags â is that question wearing a different hat. The engineering is about choosing an approximate index, deciding what to store beside the vector, and resisting the urge to benchmark with data that flatters the tool.
Responsibilities Beyond the Nearest Neighbor
Plain similarity search is the easy part. A useful store also has to hold payload data alongside vectors â titles, text, timestamps, access scopes â because an application that retrieves identifiers and then issues a second query for content pays twice and risks inconsistency. It has to filter before or during search so that a user's results never include another tenant's documents. It has to survive process restarts, support incremental inserts and deletes, and expose consistent snapshots while ingestion runs.
These requirements interact unpleasantly with indexing. Many approximate indexes were designed for a static, unfiltered set of points, and adding predicates can drop recall sharply if the engine applies the filter after the graph traversal rather than before it. Deletions similarly force tombstones that accumulate and degrade traversal. When you evaluate a store, test filters and deletes with realistic selectivity on day one, not after the corpus has grown to millions of items.
Exact Search and the Case for Approximation
With a million vectors of 1,024 dimensions, an exact scan is a billion floating-point multiply-adds per query â feasible on a fast machine, painful at a thousand queries per second, hopeless at a hundred million rows. Approximate nearest neighbor search accepts a tunable loss in recall to gain orders of magnitude in speed, and for most AI workloads the top five results being right ninety-five percent of the time is indistinguishable from perfect.
import numpy as np
import time
rng = np.random.default_rng(7)
n, dim, k = 50_000, 256, 5
data = rng.standard_normal((n, dim)).astype("float32")
data /= np.linalg.norm(data, axis=1, keepdims=True)
queries = rng.standard_normal((20, dim)).astype("float32")
queries /= np.linalg.norm(queries, axis=1, keepdims=True)
def exact_search(query, k):
sims = data @ query
top = np.argsort(-sims)[:k]
return top, sims[top]
start = time.perf_counter()
for q in queries:
exact_search(q, k)
elapsed = time.perf_counter() - start
print(f"exact: {elapsed / len(queries) * 1000:.2f} ms per query")
print("dim matters: memory for float32 is",
round(data.nbytes / 1e6, 1), "MB for", n, "vectors")
Once you have measured the exact baseline, recall of an approximate index becomes a number you can defend instead of a vendor claim you repeat.
The Three Index Families
Hierarchical navigable small-world graphs organize points into layers of proximity graphs: coarse at the top, dense at the bottom, and a greedy walk narrows the candidates at each level. They deliver high recall at low latency and are the default in most engines, at the cost of build time and memory for the graph itself. Inverted file indexes cluster points with k-means and search only the nearest centroids, which scales to very large collections and works well on a GPU, but needs enough probes to avoid missing a cluster. Product quantization compresses vectors into short codes, shrinking memory dramatically and enabling a two-stage search, though recall suffers unless the codebook is tuned carefully.
| Index | Recall profile | Memory | Build time | Best fit |
|---|---|---|---|---|
| Flat (exact) | Perfect | High, full vectors | None | Under 100k vectors, gold-standard evals |
| HNSW | Very high, tunable via graph depth | High, graph plus vectors | Slow, incremental-friendly | Latency-sensitive interactive search |
| IVF | Good, tuned by nprobe | Medium, centroids plus vectors | Medium | Large corpora, batch or GPU search |
| IVF with PQ | Moderate, needs tuning | Very low, codes only | Slow | Billion-scale, memory-constrained |
| Flat with quantized vectors | High with rescoring | Low | None | Small to medium, tight memory |
A useful operational habit is to keep a flat exact index over a sample of production data. When approximate results look wrong, compare against it and you will know immediately whether the index or the query is at fault.
Filters, Payloads, and Multi-Tenancy
Filtering is where vector stores separate themselves. The safe pattern is pre-filtering: evaluate the predicate first, then search only within the surviving set. Post-filtering â search then drop non-matching results â returns fewer than k rows or, worse, silently loses the true neighbor. Engines differ in strategy, so benchmark with both highly selective filters and per-tenant partitions, which are the two shapes applications actually produce.
import chromadb
client = chromadb.EphemeralClient()
collection = client.create_collection(
name="tickets",
metadata={"hnsw:space": "cosine"},
embedding_function=None,
)
collection.add(
ids=["t1", "t2", "t3"],
embeddings=[[1.0, 0.0, 0.0], [0.9, 0.1, 0.0], [0.0, 1.0, 0.0]],
documents=["refund rejected", "refund approved", "login broken"],
metadatas=[
{"team": "billing", "status": "closed", "lang": "en"},
{"team": "billing", "status": "open", "lang": "en"},
{"team": "auth", "status": "open", "lang": "de"},
],
)
res = collection.query(
query_embeddings=[[1.0, 0.0, 0.0]],
n_results=3,
where={"team": "billing"},
include=["documents", "metadatas", "distances"],
)
print(list(zip(res["ids"][0], res["documents"][0], res["distances"][0])))
collection.update(ids=["t3"], metadatas=[{"team": "auth", "status": "closed", "lang": "de"}])
print("count after upsert:", collection.count())
Multi-tenant systems face a spectrum of choices: one collection per tenant gives isolation but multiplies index overhead; a shared collection with a tenant filter keeps one index but demands filter-aware search; sharding by tenant scales independently at the cost of operational complexity. Start shared with strict filters, and partition only when a single customer's growth would otherwise dominate your latency.
Selecting a Store for Your Workload
Managed cloud services trade money for zero operational burden and elastic scale, self-hosted engines trade operational work for control and cost predictability, and embedded libraries remove the network hop entirely for single-process applications. Vector support now also ships inside general databases you may already run, which is often the pragmatic answer at moderate scale: one backup story, one query language, one team that understands it.
| Option shape | Examples | Choose when |
|---|---|---|
| Managed service | Pinecone, managed Qdrant or Weaviate | Small team, elastic traffic, no ops capacity |
| Self-hosted engine | Qdrant, Weaviate, Milvus, pgvector | Predictable load, strict data residency |
| Embedded or in-process | FAISS, Chroma, sqlite-vec | Prototypes, local-first, single node |
| Database extension | pgvector, Elasticsearch dense vectors | Existing SQL or search estate, moderate scale |
Quantify before deciding: vectors per tenant, dimension, update rate, required recall, and latency at peak. If those numbers are still guesses, an embedded store gets you to real measurements fastest.
Benchmarking Without Fooling Yourself
The common benchmark is three million vectors generated by one model, queried by vectors from the same model, with no filters and no deletes. It measures a case nobody runs. Real evaluation embeds your own documents, queries them the way users phrase things, applies the filters your application uses, and reports recall at k alongside p95 latency and cost per million queries.
Build a small harness: hold out a set of queries with known relevant passages from manual labeling, run each candidate configuration, and plot recall against latency so the trade-off is explicit. Include an indexing phase â some engines return queries before the index is ready and look excellent for the first hour. Include write throughput, because a store that cannot keep up with ingestion will hand you stale results no matter how fast it reads.
đĄNormalize once, at write time
Best Practices
- Keep an exact index over a sample as ground truth for recall checks
- Test filtered and delete-heavy workloads during evaluation, not after launch
- Store the fields you display with the vector so retrieval needs one round trip
- Report recall at k, p95 latency, and cost together â never a single headline number
- Re-run benchmarks after every engine upgrade; index defaults change between versions
Key Takeaways
- Vector stores pair payload, filters, and durability with fast approximate search
- HNSW favors latency and recall, IVF favors scale, product quantization favors memory
- Filter strategy decides correctness: pre-filter, do not post-filter
- Collection layout encodes your tenancy model, so choose it deliberately
- Benchmarks must use your corpus, your filters, and your query phrasing to mean anything
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- Forgetting constraints â Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions