🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Vector Databases: Indexes for Semantic Search

đŸŸĸ Free Lesson

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.

python
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.

IndexRecall profileMemoryBuild timeBest fit
Flat (exact)PerfectHigh, full vectorsNoneUnder 100k vectors, gold-standard evals
HNSWVery high, tunable via graph depthHigh, graph plus vectorsSlow, incremental-friendlyLatency-sensitive interactive search
IVFGood, tuned by nprobeMedium, centroids plus vectorsMediumLarge corpora, batch or GPU search
IVF with PQModerate, needs tuningVery low, codes onlySlowBillion-scale, memory-constrained
Flat with quantized vectorsHigh with rescoringLowNoneSmall 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.

python
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 shapeExamplesChoose when
Managed servicePinecone, managed Qdrant or WeaviateSmall team, elastic traffic, no ops capacity
Self-hosted engineQdrant, Weaviate, Milvus, pgvectorPredictable load, strict data residency
Embedded or in-processFAISS, Chroma, sqlite-vecPrototypes, local-first, single node
Database extensionpgvector, Elasticsearch dense vectorsExisting 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

Convert vectors to unit length when you store them if you intend to use cosine similarity; then cosine becomes a plain dot product and query-time normalization can never be forgotten.

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

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. 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

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. 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

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement