📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

๐Ÿ“š Interview question

What is an embedding, and how does vector search work? Explain similarity measures, why and how you chunk documents, and how you'd choose between Azure AI Search, SQL Server 2025's vector type, Cosmos DB and pgvector for a .NET app.

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.

Intermediate Theory Intermediate ai azure-ai-search embeddings microsoft-extensions-ai sql-server vector-search

๐ŸŽฏ Key points

  • An embedding is a fixed-length float vector (e.g. 1536 dimensions for text-embedding-3-small) where similar meaning gives nearby vectors
  • Similarity by cosine similarity (or dot product on normalised vectors); TensorPrimitives.CosineSimilarity in .NET
  • Exact k-NN is O(n · d); approximate indexes such as HNSW trade a little recall for big speed gains
  • Dimensions drive storage, memory and query cost; text-embedding-3 models can return shortened vectors (e.g. 512 or 1024) with a small accuracy loss
  • Chunk documents (e.g. 300–800 tokens with overlap, split on headings) because one vector per long document blurs meaning
  • The same embedding model and dimensions must be used for indexing and querying; changing either means re-embedding everything
  • Hybrid search (keyword BM25 + vector, fused with RRF) plus a semantic reranker beats vector-only for codes, names and IDs
  • Store choice: Azure AI Search for hybrid and reranking at scale; SQL Server 2025 (GA November 2025) / Azure SQL VECTOR type when data already lives there, noting its approximate vector index is still preview; Cosmos DB or pgvector next to existing data

โฑ 30-second answer

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.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"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 IEmbeddingGenerator from 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 VECTOR type 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."


Similarity measures

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

Vector store options (as of late 2026)

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

Production example

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.

๐Ÿ” What the interviewer is checking

Checks that the candidate understands embeddings and retrieval well enough to build and tune search for a RAG feature.

Green flags

  • Explains embeddings as meaning-preserving vectors and names cosine similarity
  • Knows exact vs approximate search and HNSW
  • Chunks on structure and keeps metadata
  • Mentions hybrid search and reranking for exact terms
  • Chooses a store based on where data already lives and the scale

Red flags

  • Thinks the vector stores the text or keywords
  • Mixes embedding models between indexing and querying
  • No idea why chunking matters
  • Picks a vector database without considering existing infrastructure

๐Ÿ“š Learn in depth

1. What the vector means

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

2. Cosine similarity

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.

3. Exact vs approximate search

  • Exact (flat) k-NN: compare with every vector. O(n ยท d). Fine to roughly 100k vectors.
  • HNSW: a layered graph; search starts at a sparse top layer and greedily descends. Query time is roughly logarithmic; recall depends on parameters (m, efConstruction, efSearch).
  • IVF: cluster vectors and search only the nearest clusters.
layer 2:  A โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ F
layer 1:  A โ”€โ”€โ”€โ”€ C โ”€โ”€โ”€โ”€โ”€โ”€ F โ”€โ”€โ”€โ”€ H
layer 0:  Aโ”€Bโ”€Cโ”€Dโ”€Eโ”€Fโ”€Gโ”€Hโ”€Iโ”€J   (all points)

4. Chunking

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.

5. Hybrid search and reranking

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.

6. Operational facts

  • Index and query must use the same embedding model and dimensions; changing models means re-embedding the corpus.
  • Embedding is cheap per token but large corpora add up; batch requests and embed only changed chunks.
  • SQL Server 2025 adds the VECTOR(n) type and VECTOR_DISTANCE; EF Core 10 maps it for SQL Server 2025 and Azure SQL.

Try it yourself

  1. Embed ten sentences and print the cosine similarity matrix with TensorPrimitives.CosineSimilarity.
  2. Search for a product code with vector-only search and watch it fail; add a keyword filter.
  3. Chunk one long document three ways and compare top-3 results for five questions.
  4. In SQL Server 2025, create a table with a VECTOR(1536) column and query it with VECTOR_DISTANCE('cosine', ...).
  5. Benchmark exact search over 100k random vectors with BenchmarkDotNet.

๐Ÿ’ป Code

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;

โš  Common mistakes

  • Mistake: Embedding whole documents as one vector. Why it is wrong: the vector averages many topics and matches nothing precisely. Instead: chunk on structure into a few hundred tokens with overlap.
  • Mistake: Querying with a different embedding model from the one used to index. Why it is wrong: vectors from different models live in different spaces. Instead: record the model and dimensions with the index; re-embed when you change.
  • Mistake: Picking the largest dimensions by default. Why it is wrong: storage, index memory and query time grow linearly with dimensions (3,072 floats = 12 KB per chunk before index overhead), and SQL Server's float32 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.
  • Mistake: Vector-only search for IDs, codes and names. Why it is wrong: embeddings blur exact tokens. Instead: hybrid search with keyword scoring and RRF, plus a reranker.
  • Mistake: Dropping metadata. Why it is wrong: you cannot cite sources or filter by permission or date. Instead: store document id, heading, URL and ACL fields with each chunk.
  • Mistake: Treating similarity score as a probability of correctness. Why it is wrong: scores are relative and model-specific. Instead: tune thresholds on a labelled test set.
  • Mistake: Relying on preview features for a production SLA. Why it is wrong: SQL Server 2025's 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.
  • Mistake: Adding a dedicated vector database by default. Why it is wrong: another system to secure, sync and pay for. Instead: use the vector support in the database you already run when scale allows.
  • Mistake: Re-embedding the whole corpus on every change. Why it is wrong: wasted cost and time. Instead: hash chunks and embed only new or changed ones.

๐Ÿ› Senior insight: trade-offs

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.

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions chunking or hybrid search improving results Why: Checks whether they can measure retrieval rather than guess
    How to answer

    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:

    • Hit rate / recall@k: is a correct chunk in the top k, and what share of the correct chunks did we get?
    • MRR: the average of 1 / rank of the first correct chunk.
    • nDCG@k: graded relevance, discounted by position.

    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.

  2. When: Candidate mentions keyword search or Azure AI Search Why: Checks depth on retrieval beyond basic embeddings
    How to 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.

โ†ฉ Usually asked after

More in .NET and AI

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me