My account

Vector search

Vector search finds the stored vectors closest to a question vector. Comparing with every vector is exact but slow at millions of rows, so real systems use an approximate index like HNSW. It is very fast but can miss a few true neighbors, so you measure recall and tune it. Filters (like category or customer) need care, because the index may find too few rows that pass the filter. In .NET, PostgreSQL with pgvector is a simple first choice.

Not reviewedWritten with AI helpReading time: 15 minShop help assistant exampleC# and .NET 10 codePostgreSQL

Author: bezzad

Contents

The problem: one question, two million comparisons

The help assistant now searches more than help articles. It also searches the manuals of 40,000 products. After cutting them into pieces, we have about 2 million chunks, each with a vector of 1,536 numbers.

The first version loaded all vectors into memory and compared the question with each one in a loop. It worked with 3,000 chunks. With 2 million:

  1. Memory: 2,000,000 × 1,536 numbers × 4 bytes ≈ 12 GB in every app instance.
  2. Speed: about a second of CPU for each question, and all CPUs busy at lunch time.

We need an index, like a B-tree for normal columns, but for “closest vector”.

Exact or approximate?

  1. Exact search (also called flat or brute force) compares with every vector. It always finds the true closest ones. The cost grows in a straight line with the number of rows. It is fine up to some tens of thousands of rows.
  2. Approximate nearest neighbor (ANN) search uses an index to check only a small part of the vectors. It is often hundreds of times faster, but it can miss some of the true closest ones.

How much does it miss? We measure it with recall: out of the true top 10, how many did the index return? Recall 0.95 means 9 or 10 of the right 10 on average. For RAG this is usually fine, because the model reads several chunks anyway.

How HNSW works

HNSW (Hierarchical Navigable Small World) is the most common ANN index today. It is in pgvector, Qdrant, Elasticsearch, Azure AI Search and many others.

Top layerfew pointsMiddle layermore pointsBottom layerall pointsstartclosest to the question
The top layer has few points and long jumps. The search starts there, walks to the point closest to the question, and drops one layer down. The bottom layer has all points, so the last steps are short and careful.
  1. A graph. Each vector is a node, linked to some of its close neighbors.
  2. Layers. Every node is in the bottom layer. Fewer and fewer nodes are also in higher layers, like express stations on a train line.
  3. Greedy walk. Start at the top. Move to the neighbor that is closer to the question, while you can. Then go down one layer and repeat.
  4. A candidate list. On the bottom layer, the search keeps a list of the best candidates it has seen. A longer list checks more nodes: better recall, slower search.

The three knobs

Knob (pgvector name) What it does Bigger value means
m Links per node Better recall, more memory, slower build
ef_construction Candidate list size while building Better graph, slower build
ef_search Candidate list size while searching Better recall, slower search

In pgvector the defaults are 16, 64 and 40. Start with the defaults. Change ef_search first, because you can change it per query without building the index again.

pgvector from .NET

If you already run PostgreSQL, the pgvector extension is the simplest start: vectors live next to the rest of your data, in the same backup and the same transactions.

// Packages: Npgsql.EntityFrameworkCore.PostgreSQL and Pgvector.EntityFrameworkCore
builder.Services.AddDbContext<HelpDb>(o =>
    o.UseNpgsql(connectionString, npgsql => npgsql.UseVector()));

public sealed class ArticleChunk
{
    public int Id { get; set; }
    public string Category { get; set; } = "";
    public string Text { get; set; } = "";
    [Column(TypeName = "vector(1536)")]
    public Vector Embedding { get; set; } = null!;
}
protected override void OnModelCreating(ModelBuilder b)
{
    b.HasPostgresExtension("vector");
    b.Entity<ArticleChunk>()
        .HasIndex(c => c.Embedding)
        .HasMethod("hnsw")
        .HasOperators("vector_cosine_ops");
}

The search is a normal LINQ query:

var question = new Vector(await embedder.GenerateVectorAsync(text, cancellationToken: ct));

List<ArticleChunk> top = await db.Chunks
    .OrderBy(c => c.Embedding.CosineDistance(question))
    .Take(5)
    .ToListAsync(ct);

The operator class in the index (here, cosine) must match the distance in the query. If the index uses cosine and the query sorts by another distance, PostgreSQL cannot use the index and reads every row.

Measure recall, do not guess it

  1. Take 200 real questions.
  2. Run each one with exact search. In PostgreSQL you can turn the index off for one transaction, so it scans every row. These are the true answers.
  3. Run each one with the index and count how many of the true top 10 came back.
  4. Try ef_search values like 40, 100 and 200. Write down recall and the 95th percentile time for each.
  5. Pick the smallest value that gives the recall you need.

Do this again when the data grows a lot, or when you change the embedding model.

Filters: the hidden trap

A customer asks a question on the page of a garden product. We want only chunks from the garden category:

SELECT id, text FROM chunks
WHERE category = 'garden'
ORDER BY embedding <=> @question
LIMIT 5;
1. Index: 40 nearestef_search = 40green = garden chunk2. WHERE filtercategory = garden3. Result2 rowsasked for 5
The index returns its best 40 candidates first. Only 2 of them are garden chunks, so the WHERE filter leaves 2 rows, not 5. Small categories get poor results.

With a normal HNSW scan, the index finds about ef_search candidates (40 by default), and then PostgreSQL removes the rows that do not pass the filter. If garden is 1% of the data, maybe none of the 40 is a garden chunk. Ways to fix it:

  1. Iterative index scans (pgvector 0.8 and later): the index keeps searching until it finds enough rows that pass the filter.
  2. A bigger ef_search for filtered queries. Simple, but slower.
  3. A partial index for a few big and common filters, or a partition per tenant when every query filters by tenant.
  4. A vector database with filter-aware search, when filters are the main use case.

The same trap hits security filters, like “only documents this user may see”. The RAG lesson comes back to this.

Memory and size

  1. Raw size = rows × dimensions × 4 bytes. One million 1,536-number vectors ≈ 6 GB.
  2. The HNSW index adds the graph links on top, and it is fast only when it fits in memory.
  3. Ways to shrink it: ask the embedding model for fewer dimensions (if it supports it), use half-precision vectors (pgvector has a halfvec type), or use quantization in engines that support it. Measure recall again after each change.
  4. The pgvector HNSW index has a dimension limit (2,000 for the normal vector type at the time of writing). Very large models need halfvec or fewer dimensions.

pgvector or a vector database?

Pick When
pgvector You already run PostgreSQL; up to a few million vectors; you want joins, transactions and one backup.
A search engine you already have (Elasticsearch, OpenSearch, Azure AI Search) You need keyword and vector search together, and you already run it.
A dedicated vector database (for example Qdrant or Milvus) Very large scale, heavy filtering, many collections, or you need features pgvector does not have.

In an interview, “it depends” is not an answer. Say what it depends on: data size, filters, the team’s skills, and what you already run.

Common mistakes

Mistake Result Right way
Loading all vectors into app memory Huge memory, slow answers. A vector index in the database.
Index operator does not match the query distance Full table scan, no error. Same distance in the index and the query.
Filtering after a small candidate list Few or zero results for small groups. Iterative scans, bigger ef_search, partial index or partition.
Never measuring recall Quality drops silently as data grows. Compare with exact search on real questions.
Picking a vector database first One more system to run, for no reason. Start with what you run; move when numbers say so.

Summary in five lines

  1. Exact search is correct but slow at scale; ANN indexes like HNSW are fast and slightly approximate.
  2. HNSW walks a layered graph; m, ef_construction and ef_search trade recall for speed and memory.
  3. Measure recall against exact search on real questions, and tune ef_search first.
  4. Filters can leave too few rows; use iterative scans, partial indexes or partitions.
  5. pgvector is a simple start in .NET; move to another engine when size or filters need it.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.