Vector databases, index types, and chunking

Retrieval quality is decided before the model ever runs. This guide explains embeddings, how vector indexes find nearest neighbours, how to choose an embedding model, and how the way you cut documents into chunks changes what you can retrieve.

Vector search in 60 seconds

  • Embeddings map text to vectors; similar meaning means nearby vectors.
  • A vector index finds nearest neighbours without checking every vector. Flat is exact; IVF, HNSW, and product quantisation trade a little accuracy for speed and memory.
  • Recall is the key quality number for an index: the share of the true nearest neighbours that it actually returns.
  • Chunking decides what can be found. A chunk is the unit of retrieval, so cut along meaning, keep context, and attach metadata.
  • Version everything. Vectors from different embedding models cannot be compared, so changing the model means re-embedding the corpus.

From text to vectors

An embedding model reads a piece of text and returns a fixed-length list of numbers, often between 384 and 3,072 of them. The model is trained so that texts about the same thing end up close together. To compare two vectors you measure the angle between them (cosine similarity) or the distance between them. When vectors are scaled to the same length, cosine similarity and the dot product give the same ranking, which is why many systems normalise vectors and use the faster dot product.

Exact nearest-neighbour search by brute force (illustrative) (python)
# Illustrative: compare the query with every stored vector.
# The vectors are assumed to be normalised to length 1, so a dot product equals cosine similarity.

def top_k(query_vector, stored, k=5):
    scored = []
    for item_id, vector in stored.items():
        score = sum(q * v for q, v in zip(query_vector, vector))
        scored.append((score, item_id))
    scored.sort(reverse=True)
    return scored[:k]

# Cost grows with the number of vectors. Fine for thousands; too slow for hundreds of millions.

Brute force is exact and simple, and it is the right answer for small collections. As the collection grows, comparing against every vector becomes too slow, and that is the problem that vector indexes solve.

What a vector database adds

A vector database is a store built around nearest-neighbour search. Beyond the index it provides the features that turn a library into a service: durable storage, updates and deletes, metadata filtering (search only documents from this tenant, after this date), hybrid search that combines keyword and vector ranking, replication, and access control. Many general-purpose databases now offer a vector index as an option, and dedicated systems offer more tuning and scale. The right choice depends on your size, your filtering needs, and what you already operate.

Index types

Almost all production vector indexes are approximate: they may miss a true nearest neighbour in exchange for much faster search. The three families below cover most systems, and they are often combined.

Flat checks everything; IVF narrows to a few clusters; HNSW hops through a layered graph.

Flat (exact) index

A flat index stores vectors as they are and compares the query with all of them. It has perfect recall, no tuning, and no build time. It is the baseline against which every approximate index is measured, and it remains a good choice up to roughly hundreds of thousands of vectors, or when you filter down to a small subset before searching.

IVF (inverted file index)

IVF groups the vectors into clusters, each with a centre point. At query time it finds the few clusters whose centres are closest to the query and searches only inside them. The number of clusters searched, often called nprobe, is the main dial: more clusters means better recall and slower search. IVF builds quickly and uses little extra memory, and it suffers when a query falls near the boundary between clusters, because its true neighbours may sit in a cluster that was skipped.

HNSW (hierarchical navigable small world)

HNSW builds a layered graph. The top layer has few points with long links, and each lower layer has more points with shorter links. A search starts in the top layer, hops toward the query, drops a layer, and repeats until it reaches the dense bottom layer. It gives high recall at low latency, which is why it is the default in many systems. The costs are memory, since the graph is stored on top of the vectors, and slower inserts and deletes. Its main dials are the number of links per node and the search breadth.

Product quantisation and compression

Memory is often the real limit. One million vectors with 768 numbers of 4 bytes each take about 3 GB, and one billion take about 3 TB. Product quantisation compresses each vector by splitting it into parts and replacing each part with the ID of its nearest entry in a small codebook, shrinking vectors by an order of magnitude at a cost in precision. Simpler options are scalar quantisation (storing 8-bit instead of 32-bit numbers) and, for some models, shorter embeddings. Compression is usually paired with a second step that reranks the top candidates using the full-precision vectors.

IndexRecallSpeedMemoryUpdatesChoose when
FlatExactSlow at scaleVectors onlyTrivialSmall collections, or after heavy filtering
IVFGood, depends on clusters searchedFastLow extraCheap; clusters drift over timeLarge collections, memory-aware, fast builds
HNSWHighVery fastHigh (graph on top)Slower inserts and deletesLow-latency search where memory allows
PQ or scalar quantisationLower, can be rerankedFastMuch lowerDepends on the index it is added toVery large collections where memory is the limit

Measuring an index: recall and latency

Choose index settings by measurement, not by default. Take a sample of real queries, compute the exact nearest neighbours with a flat search, then run the same queries through the approximate index and compute recall at k: the fraction of the true top k that appear in the approximate top k. Plot recall against latency as you change the dials, and choose the cheapest point that meets your quality bar. Remember that recall of the index is only one input: if the embedding model misses the meaning of your domain, a perfect index returns the wrong things quickly.

Recall at k for an approximate index (illustrative) (python)
# Illustrative: compare an approximate index with exact search on real queries.
# exact_search() and approx_search() are placeholders returning lists of ids.

def recall_at_k(queries, k=10):
    total = 0.0
    for q in queries:
        truth = set(exact_search(q, k))
        found = set(approx_search(q, k))
        total += len(truth & found) / k
    return total / len(queries)

# Repeat for several index settings and record recall and latency for each.

Choosing an embedding model

The embedding model decides what 'similar' means, so it matters at least as much as the index. Look at the languages it supports, the maximum input length, the vector size (larger vectors cost more to store and search), and how it performs on your domain. Public leaderboards give a starting list, but they are averages over general tasks; build a small set of real queries with known relevant documents and test the candidates on it.

  • Version your vectors. Store the model name and version with each vector, and never mix models in one index.
  • Plan the migration. Changing the model means re-embedding every document, so build the new index beside the old one and switch when it is ready.
  • Consider shorter vectors. Some models support truncating their output to fewer dimensions with a small loss in quality, which reduces memory and speeds up search. Check that your model was trained for it.

Chunking: deciding what can be retrieved

Documents are usually too long to embed as one vector, and a single vector for a long page blurs many topics together. So documents are cut into chunks, and each chunk is embedded and stored. The chunk is the unit of retrieval and of context given to the model, so how you cut decides what the system can find and what the model can read. A chunk that is too small loses the context needed to understand it. A chunk that is too large mixes topics, so the vector matches nothing well and the model receives a lot of irrelevant text.

Fixed-size chunks with overlap

The simplest method cuts every N tokens and repeats the last part of each chunk at the start of the next, so a sentence at a boundary is not lost. It is easy and predictable. It ignores structure, so it can cut a table or a sentence in half.

Recursive splitting by separators

A step up: try to split on the largest natural boundary first (sections, then paragraphs, then sentences, then words), and only split further when a piece is still too long. It keeps paragraphs together when possible and is a good default for prose.

Structure-aware chunking

For documents with real structure, such as manuals, contracts, and code, cut along that structure: a section with its heading, a table as a whole, a function with its signature. Prepending the heading path (for example, 'Refund policy > Digital goods') to each chunk gives it context that a bare paragraph lacks.

Semantic chunking

Embed each sentence, and start a new chunk where the meaning changes, detected by a drop in similarity between neighbouring sentences. It follows the content rather than the layout, at the cost of an extra embedding pass. It helps on long, loosely structured text and adds little on well-structured documents.

Parent-child (small-to-big) chunking

Match on small chunks, return big ones. Small chunks embed precisely, so they match a question well. Once a small chunk matches, the system fetches its parent, the surrounding section, so the model has enough context to answer. This removes much of the trade-off between precision and context.

Recursive chunking with overlap and a heading prefix (illustrative) (python)
# Illustrative: split on the largest boundary that keeps chunks under the limit.
# count_tokens() is a placeholder for the model's tokenizer.

SEPARATORS = ['\n\n', '\n', '. ', ' ']

def split(text, max_tokens=400, separators=SEPARATORS):
    if count_tokens(text) <= max_tokens or not separators:
        return [text]
    sep, rest = separators[0], separators[1:]
    pieces, current, chunks = text.split(sep), '', []
    for piece in pieces:
        candidate = (current + sep + piece) if current else piece
        if count_tokens(candidate) <= max_tokens:
            current = candidate
        else:
            if current:
                chunks.append(current)
            current = piece
    if current:
        chunks.append(current)
    out = []
    for c in chunks:
        out.extend(split(c, max_tokens, rest) if count_tokens(c) > max_tokens else [c])
    return out

def make_chunks(doc):
    chunks = split(doc.body)
    return [{'text': f'{doc.heading_path}\n{c}', 'source': doc.url, 'section': doc.heading_path,
             'updated': doc.updated, 'access': doc.access_groups} for c in chunks]

Metadata and filtering

Every chunk should carry metadata: its source, section, date, language, document version, and who may read it. Metadata does three jobs. It lets you filter before or during the search, so a question about the 2024 policy does not match the 2019 one. It supports access control, so a search returns only what the user may see. And it lets the answer cite its source. Decide the metadata schema before ingestion, because adding it later means re-processing every document.

The chunking strategies compared

StrategyHow it cutsStrengthWeaknessGood for
Fixed size with overlapEvery N tokens, repeating the tailSimple, predictableIgnores structureQuick prototypes, uniform text
RecursiveLargest natural boundary firstKeeps paragraphs togetherStill blind to meaningGeneral prose
Structure-awareAlong headings, tables, functionsRespects the documentNeeds a parser per formatManuals, contracts, code
SemanticWhere similarity dropsFollows the contentExtra embedding costLong, loosely structured text
Parent-childSmall to match, large to returnPrecision and contextMore storage and logicQuestion answering over long sections

How to choose and tune

  • Start simple: recursive splitting at a few hundred tokens with a small overlap, plus a heading prefix.
  • Build an evaluation set of real questions with the passages that answer them, and measure recall of the right chunk.
  • Change one thing at a time: chunk size, overlap, or strategy, and re-measure.
  • Add structure-aware or parent-child chunking where the evaluation shows missed context.
  • Pick an index by measurement: start flat, move to IVF or HNSW when latency demands, add compression when memory demands.
  • Keep both indexes during migrations: a new embedding model or a new chunking scheme is a re-ingestion, so run old and new side by side.

What this means for your role

Common mistakes

Further reading

  • Types of RAG, the pipelines that use these indexes.
  • Indexing, the database indexing ideas behind the structures on this page.
  • Bloom filters, another approximate structure that trades accuracy for speed and space.
  • Sharding, for splitting a large index across machines.

Good retrieval starts with good pieces. Cut along meaning, keep the context, label every chunk, and measure before you tune.

Search topics

↑↓ to move · Enter to open · Esc to close