Embeddings and vector search: what an embedding vector represents, cosine similarity and dot product, exact versus approximate (HNSW) nearest-neighbour search, chunking strategies, hybrid search, IEmbeddingGenerator and Microsoft.Extensions.VectorData, and choosing a vector store.
An embedding is a fixed-length vector of floats produced by an embedding model, such that texts with similar meaning land close together. Vector search embeds the query with the same model and returns the stored vectors nearest to it, usually by cosine similarity. At scale you use an approximate index (HNSW) rather than comparing against every vector.
You chunk documents into passages of a few hundred tokens because one vector for a 40-page PDF blurs everything together. For stores: Azure AI Search gives hybrid keyword-plus-vector search and reranking; SQL Server 2025 / Azure SQL has a native VECTOR type when the data already lives there; Cosmos DB and pgvector suit apps already on those. The trade-off: vectors find meaning, but miss exact codes and names unless you add keyword search.
"An embedding model turns text into a vector, say 1,536 floats for
text-embedding-3-small. It's trained so that passages with similar meaning end up pointing in similar directions, so 'how do I reset my password' and 'forgot login credentials' are close even with no words in common. Vector search is then just geometry: embed the query with the same model and find the nearest stored vectors, normally by cosine similarity. Comparing against every vector is fine for ten thousand chunks, but at millions you use an approximate nearest-neighbour index like HNSW, which trades a percent or two of recall for orders of magnitude of speed.Chunking matters as much as the model. If I embed a whole policy document as one vector, the vector is an average of twenty topics and matches nothing well. So I split on headings into chunks of a few hundred tokens with a bit of overlap, and I store the source, section and permissions alongside each vector. In .NET I generate vectors with
IEmbeddingGeneratorfrom Microsoft.Extensions.AI and store them through Microsoft.Extensions.VectorData, which has connectors for Azure AI Search, SQL Server, Cosmos DB, Postgres and others, so the store is a swappable detail.The mistake I see is going vector-only. Embeddings are bad at exact tokens: a part number, a policy code, a person's name. Hybrid search, keyword plus vector merged with reciprocal rank fusion, then a reranker, fixes most of that. For the store, if the data already lives in Azure SQL or SQL Server 2025, the native
VECTORtype avoids a second system; if I need hybrid search, reranking and scale, Azure AI Search. Embeddings capture meaning; they don't replace keyword search, they complement it."
| Measure | What it compares | Note |
|---|---|---|
| Cosine similarity | Angle between vectors | The default for text embeddings; 1 = same direction |
| Dot product | Angle and length | Equal to cosine when vectors are normalised (OpenAI embeddings are) |
| Euclidean distance | Straight-line distance | Less common for text; same ranking as cosine on normalised vectors |
| Store | Fits when | Watch out for |
|---|---|---|
| Azure AI Search | Hybrid search, semantic reranking, filters, large corpora | Separate service and cost; index sync |
SQL Server 2025 / Azure SQL VECTOR |
Data already in SQL; transactional consistency; modest scale | Approximate vector indexes still preview; dimension limits (1,998 for float32) |
| Azure Cosmos DB (NoSQL vector search) | App already on Cosmos; per-tenant partitioning | RU cost of vector queries |
| PostgreSQL + pgvector | App on Postgres (Azure Database for PostgreSQL) | Index tuning (HNSW / IVFFlat) |
| In-memory | Prototypes, tests, a few thousand chunks | No persistence or scale |
For [an internal HR policy search over about 4,000 pages], whole-document embeddings gave a top-5 hit rate of [about 55%] on our test questions. Splitting on headings into [~500-token] chunks with [50-token] overlap raised it to [about 82%], and adding hybrid keyword search with the semantic reranker in Azure AI Search took it to [about 91%], mainly by fixing queries with policy codes.
Checks that the candidate understands embeddings and retrieval well enough to build and tune search for a RAG feature.
Green flags
Red flags
An embedding model is a neural network (usually a transformer encoder) trained with contrastive learning: pairs that should match are pulled together, non-matching pairs are pushed apart. The output is a point in a high-dimensional space. Individual dimensions don't mean anything human-readable; only relative positions do.
"reset password" โโบ [0.012, -0.044, 0.103, ...] โ close
"forgot my login" โโบ [0.015, -0.041, 0.097, ...] โ
"quarterly revenue" โโบ [-0.081, 0.066, -0.010, ...] far
cos(a, b) = (a ยท b) / (|a| |b|)
In .NET, System.Numerics.Tensors.TensorPrimitives.CosineSimilarity computes it with SIMD. With normalised vectors the dot product gives the same ranking and is cheaper.
m, efConstruction, efSearch).layer 2: A โโโโโโโโโโโโโ F
layer 1: A โโโโ C โโโโโโ F โโโโ H
layer 0: AโBโCโDโEโFโGโHโIโJ (all points)
| Strategy | How | Good for |
|---|---|---|
| Fixed size + overlap | e.g. 512 tokens, 10โ15% overlap | Unstructured text |
| Structure-aware | Split on headings, paragraphs, list items | Policies, docs, wikis |
| Semantic | Split where embedding similarity between sentences drops | Long narrative text |
Keep metadata with each chunk: document id, title, section heading, URL, last modified, and access-control fields for filtering. Prepending the document title and heading to the chunk text before embedding often improves retrieval.
Keyword search (BM25) is excellent at exact terms; vector search at paraphrase. Run both and merge with reciprocal rank fusion (score = ฮฃ 1/(k + rank)). Then a reranker (cross-encoder, such as Azure AI Search's semantic ranker) rescores the top 50 by reading query and chunk together.
VECTOR(n) type and VECTOR_DISTANCE; EF Core 10 maps it for SQL Server 2025 and Azure SQL.TensorPrimitives.CosineSimilarity.VECTOR(1536) column and query it with VECTOR_DISTANCE('cosine', ...).Embedding and exact cosine search in memory, the core idea before you add a real store.
// Packages: Microsoft.Extensions.AI.OpenAI, Azure.AI.OpenAI, Azure.Identity, System.Numerics.Tensors
using System.Numerics.Tensors;
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Extensions.AI;
var endpoint = new Uri(Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")!);
IEmbeddingGenerator<string, Embedding<float>> embedder =
new AzureOpenAIClient(endpoint, new DefaultAzureCredential())
.GetEmbeddingClient("text-embedding-3-small")
.AsIEmbeddingGenerator();
string[] chunks =
[
"To reset your password, open Settings > Security and choose Reset.",
"Invoices are emailed on the first business day of each month.",
"Leave requests need manager approval at least two weeks ahead."
];
// Batch the corpus: one request for many inputs.
var vectors = await embedder.GenerateAsync(chunks);
var query = await embedder.GenerateVectorAsync("I forgot my login");
var ranked = chunks
.Select((text, i) => (text, score: TensorPrimitives.CosineSimilarity(query.Span, vectors[i].Vector.Span)))
.OrderByDescending(x => x.score);
foreach (var (text, score) in ranked)
Console.WriteLine($"{score:F3} {text}");
The same idea in SQL Server 2025 / Azure SQL with the native vector type:
CREATE TABLE dbo.DocChunks
(
Id int IDENTITY PRIMARY KEY,
DocumentId int NOT NULL,
Heading nvarchar(200) NOT NULL,
Content nvarchar(max) NOT NULL,
Embedding vector(1536) NOT NULL
);
DECLARE @q vector(1536) = CAST(@queryJson AS vector(1536));
SELECT TOP (5) Id, Heading,
VECTOR_DISTANCE('cosine', Embedding, @q) AS Distance -- smaller = more similar
FROM dbo.DocChunks
ORDER BY Distance;
VECTOR caps at 1,998 dimensions. Instead: start with 1,536 or a shortened 512โ1,024 vector and keep the larger size only if your recall@k test shows a real gain.VECTOR type is GA, but its approximate (DiskANN) vector index is still preview and can change. Instead: use exact VECTOR_DISTANCE search at modest scale, or a GA service such as Azure AI Search for large corpora.Retrieval quality is mostly chunking, metadata and hybrid ranking, not the embedding model. Build a small labelled set of real questions with the chunk that should be found, and measure hit rate and MRR before and after each change. That turns "it feels better" into a number.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Azure AI Search | Hybrid, reranking, large corpora, many filters | Separate service, index pipeline | Small corpus already in SQL |
| SQL Server 2025 / Azure SQL vector | Data and permissions already in SQL | Uses DB resources; ANN indexes still maturing | Millions of chunks with heavy query load |
| Cosmos DB / pgvector | App already on that store | RU or compute cost | Introducing them just for vectors |
Prefer Microsoft.Extensions.VectorData in application code so moving from the in-memory connector in tests to Azure AI Search in production is configuration, not a rewrite.
Build a labelled set of 50โ200 real questions, each with the chunk ids that should come back, written with domain experts from real (de-identified) usage. Then measure:
In .NET this is a small xUnit test project: load the set from JSON, call the same IEmbeddingGenerator and vector store search the app uses, compute the metrics with LINQ, and fail the build if recall@5 drops below the baseline. Run it on every change to chunking, the embedding model, hybrid weights or the reranker. Retrieval comes before answer quality: if the right chunk isn't retrieved, no prompt fixes the answer.
Each method fails differently. Pure vector search misses exact tokens (product codes, IDs, names, error messages) and jargon the embedding model handles poorly. Pure keyword (BM25) misses paraphrases, which are common in support and help-desk questions. Hybrid runs both in parallel and merges them with reciprocal rank fusion: each document scores ฮฃ 1/(k + rank) across the lists (k is often 60). Because RRF uses ranks, not raw scores, you don't have to normalise BM25 and cosine scores that sit on incompatible scales, and documents ranked well by both rise.
A reranker (a cross-encoder, such as Azure AI Search's semantic ranker) then reads the query and each candidate document together in one model pass and reorders them. That is far more accurate but adds roughly 100โ300 ms and cost per query, so apply it only to the top ~50 candidates. Prove the gain with recall@k and MRR before and after.
Last updated 23 Nov 2026.