# Vector Database

**Also known as:** Vector index · Semantic search  
**Category:** Data & Storage (Where the data lives)  
**Complexity:** 3/5  
**Guide:** https://layra4.dev/architectures/data-storage/vector-database

*Find items by meaning: store embeddings and search for the nearest ones.*

An embedding model turns a piece of text, an image or a product into a vector: a list of a few hundred to a few thousand numbers. Items with similar meaning land close together, so "low-cost airfare" sits near "cheap flights" although they share no word. A vector database stores these vectors and answers one question fast: which stored vectors are nearest to this one? That is what "semantic search" means.

Comparing a query with every stored vector is exact, but too slow past a few million rows. So vector stores build an approximate nearest-neighbour (ANN) index, such as HNSW or IVF, that checks only a small part of the data. Dedicated products such as Qdrant, Milvus or Pinecone do this, and so do pgvector in Postgres and the vector fields in Elasticsearch and OpenSearch.

> **In one sentence.** A vector database finds the stored embeddings closest to a query embedding, using an approximate index that gives up a little recall for a lot of speed. Measure that recall, and pair it with keyword search.

## Origin (2016)

Nearest-neighbour search is decades old. Two ideas shaped today's stores: product quantization (Jégou, Douze and Schmid, 2011), which compresses vectors, and the HNSW graph (Malkov and Yashunin, 2016), now the default index in most of them.

## Key concepts

### Embedding

A fixed-length vector produced by a model. The distance between two vectors stands for how different their meanings are. Vectors are only comparable when the same model made them.

- Typical sizes run from 384 to 3,072 dimensions
- Long documents are split into chunks, one vector per chunk
- A new model means re-embedding every row

### Distance metric (Cosine · Dot product · L2)

How closeness is measured. Use the metric the model was trained for. When vectors are normalized to length 1, cosine, dot product and Euclidean distance all rank results in the same order.

> cosine(a, b) = (a · b) / (|a| × |b|)   1 = same direction, 0 = unrelated

### HNSW (Hierarchical Navigable Small World)

A layered graph in which each vector links to its near neighbours. A search enters at the sparse top layer and walks greedily toward the query, layer by layer. It gives high recall at low latency, but the graph needs memory and is slow to build.

- m: links per node. More links, better recall, more memory
- ef_search: candidates kept while searching. Higher is more accurate and slower
- Takes inserts well; deletes are often only marked and cleaned up later

### IVF (Inverted file index)

Group the vectors into clusters with k-means. A query compares itself with the cluster centres and searches only the closest few lists (nprobe). It builds faster and uses less memory than HNSW. Product quantization (IVF-PQ) shrinks it further at some cost in accuracy.

### Recall

The share of the true nearest neighbours that an approximate search returns. A recall@10 of 0.95 means it finds, on average, 9.5 of the real top 10. You measure it by running an exact search on a sample of queries and comparing.

### Metadata filtering

Restricting results by ordinary fields, such as tenant, language or date. Post-filtering takes the top k and then drops rows that fail the filter, so a selective filter can leave almost nothing. Filtering during the search needs support from the index.

### Hybrid search

Run a keyword search (BM25) and a vector search, then merge the two ranked lists. Reciprocal rank fusion is the usual merge: each result scores 1 / (k + rank) in each list it appears in, with k around 60, and the scores add up.

## Design rules

### Store the model with every vector

Keep the model name and version beside each embedding. When you change models, build a new index next to the old one, re-embed everything into it, and switch reads over when it is full.

### Measure recall before you tune

Take a few hundred real queries, find their true neighbours with an exact scan, and compare. Raise ef_search or nprobe until recall meets your target, then check that latency still does.

### Use hybrid search for anything people type

Vectors match meaning and miss exact tokens: product codes, names, error numbers. A keyword search catches those. Merging both lists beats either alone on most real queries.

### Keep it derived from the database

The source text lives in the database of record. The vectors are a derived copy you can rebuild, fed by the same outbox or change feed as any other index.

## Examples

### Hybrid search in Postgres with pgvector

```sql
create extension if not exists vector;

-- One row per chunk. The dimension must match the embedding model.
create table doc_chunks (
  id        bigint generated always as identity primary key,
  doc_id    bigint not null,
  tenant_id bigint not null,
  body      text   not null,
  model     text   not null,                -- which model made this vector
  embedding vector(1024) not null,
  tsv       tsvector generated always as (to_tsvector('english', body)) stored
);

-- Vector side: HNSW over cosine distance. Bigger m means better recall and more memory.
create index on doc_chunks using hnsw (embedding vector_cosine_ops)
  with (m = 16, ef_construction = 64);

-- Keyword side: an inverted index over the generated tsvector.
create index on doc_chunks using gin (tsv);

-- More candidates per search: better recall, slower query.
set hnsw.ef_search = 100;

-- $1 = query embedding, $2 = tenant, $3 = the words the user typed.
with semantic as (
  select id, row_number() over (order by embedding <=> $1) as rank
  from doc_chunks
  where tenant_id = $2
  order by embedding <=> $1
  limit 50
),
keyword as (
  select id, row_number() over (order by ts_rank_cd(tsv, q) desc) as rank
  from doc_chunks, websearch_to_tsquery('english', $3) as q
  where tenant_id = $2 and tsv @@ q
  order by ts_rank_cd(tsv, q) desc
  limit 50
)
select c.id, c.doc_id, c.body,
       coalesce(1.0 / (60 + s.rank), 0) + coalesce(1.0 / (60 + k.rank), 0) as score
from semantic s
full outer join keyword k on k.id = s.id
join doc_chunks c on c.id = coalesce(s.id, k.id)
order by score desc
limit 10;
```

One table holds the text, its vector and a keyword index. The query takes the top 50 by meaning and the top 50 by keywords, then merges them with reciprocal rank fusion. If the tenant filter is very selective, the HNSW scan can return fewer than 50 rows: raise ef_search, or turn on iterative index scans where your version has them.

## When to use

- Users describe what they want in their own words, not in your exact terms
- Retrieval for RAG: finding the passages a language model should read
- Similar items: related products, duplicate tickets, near-identical images

## When not to use

- Exact lookups by id, SKU, email or error code. A normal index does that
- A few thousand vectors: an exact scan answers in milliseconds with no ANN index
- Search that must be complete, such as legal discovery, where a missed match is a failure

## Benefits

- Finds matches by meaning, across synonyms, paraphrases and even languages
- Millisecond queries over millions of vectors
- One mechanism for text, images and anything else a model can embed

## Costs

- Approximate: some true matches are missed, and you must measure how many
- Memory: a million 1,024-dimension float32 vectors take about 4 GB before the index
- A model call per write, and a full re-embed whenever the model changes

## Pitfalls

- Mixing vectors from two embedding models in one index, so distances mean nothing and results look random.
- A selective filter applied after the ANN search, so a small tenant's query returns two results instead of ten.
- Relying on vectors alone, so a search for an exact product code returns similar-looking wrong codes.
- Building an IVF index on an almost empty table. Its clusters come from the rows present at build time, so recall drops as data arrives.

## Related patterns

- [Retrieval-Augmented Generation](https://layra4.dev/architectures/ai/rag) — the most common reason a team adds a vector store
- [Search Index](https://layra4.dev/architectures/data-storage/search-index) — the keyword side of hybrid search
- [Database Indexes](https://layra4.dev/architectures/data-storage/database-indexing) — exact-match indexes, which vectors do not replace
- [Agent Memory](https://layra4.dev/architectures/ai/agent-memory) — long-term memory is often a vector search over past notes

## Further reading

- *Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs* — Yu. A. Malkov, D. A. Yashunin (2016) — The HNSW paper: the layered graph most vector stores use.
- *Product Quantization for Nearest Neighbor Search* — Hervé Jégou, Matthijs Douze, Cordelia Schmid (2011) — How to compress vectors so billions fit in memory.
- *Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods* — Gordon V. Cormack, Charles L. A. Clarke, Stefan Büttcher (2009) — The simple merge behind most hybrid search.
