Embeddings and Vector Search for Developers
30-second answer
An embedding is a list of numbers (a vector) that an embedding model such as text-embedding-3-small (1,536 dimensions) produces from text, so that texts with similar meaning get vectors that sit close together. Vector search embeds the user's question with the same model, then asks the database for the stored vectors with the smallest distance (usually cosine), and an index such as DiskANN or HNSW makes that fast. On Azure you can store and search vectors in Cosmos DB for NoSQL, PostgreSQL with pgvector and Azure Managed Redis.
Simulate it » No Azure account neededExam objective: 2.1.3 Store and retrieve embeddings and execute vector similarity search for semantic retrieval. 2.2.5 Run vector similarity search, including storing embeddings, semantic retrieval, and implementing retrieval-augmented generation (RAG) patterns by using metadata filter. 2.3.2 Implement vector indexing to enable similarity search. (Skills measured as of October 7, 2026)
Simulations
Feel it before you read it. No account needed, nothing leaves this page.
Open <strong>Data Explorer</strong> and select <strong>New Container</strong>. The vector setup lives on the container, not the account.
👆 Click the glowing item in the portal to continue
Read the steps as text
- Open Data Explorer and select New Container. The vector setup lives on the container, not the account.
- Add a vector embedding policy (path, data type, dimensions, distance function) and a vector index. Both are fixed once the container exists.
- Your app embeds the question, then asks for the three closest items. Filtering on the partition key keeps it cheap.
- With cosine, a higher score is closer. These three chunks go into the prompt for grounding.
- Pick the store your data already lives in: Cosmos DB for JSON at scale, pgvector for relational data, Redis for speed and caching.
🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.
🖱️ Drag to rotate · scroll or pinch to zoom
Text becomes a vector
An embedding model turns text into a list of numbers, a vector (1,536 numbers for text-embedding-3-small). Texts that mean similar things get vectors that sit close together, so "refund" lands near "money back".
🤔 What happens if…
Read this tour as text
- Text becomes a vector. An embedding model turns text into a list of numbers, a vector (1,536 numbers for
text-embedding-3-small). Texts that mean similar things get vectors that sit close together, so "refund" lands near "money back". - Cosmos DB: items, partitions, RUs. In Azure Cosmos DB for NoSQL, JSON items live in containers, spread across logical partitions by the partition key. Every operation costs Request Units (RUs). A point read by id and partition key costs about 1 RU. A query that scans every partition costs far more.
- Indexing and consistency. By default Cosmos DB indexes every property, so writes cost more RUs. An indexing policy can exclude paths you never filter on, such as the big
embeddingarray. Consistency levels trade freshness for speed and cost: Strong, Bounded staleness, Session (default), Consistent prefix, Eventual. - Vector search in Cosmos DB. A vector embedding policy tells Cosmos DB where the vectors are, their dimensions and distance function. A vector index makes search fast:
diskANNorquantizedFlatfor large sets, orflatfor exact search on small vectors (up to 505 dimensions). ThenORDER BY VectorDistance(c.embedding, @q)returns the closest items. - Change feed. The change feed is an ordered log of inserts and updates in a container (deletes only show up in the *all versions and deletes* mode). A change feed processor reads it with a lease container that remembers how far each worker got, so a new product can be embedded the moment it’s saved.
- PostgreSQL with pgvector. In Azure Database for PostgreSQL, the pgvector extension adds a
vector(1536)column type. Without an index, every search compares against every row (a sequential scan). An HNSW or IVFFlat index finds near neighbours fast, trading a little recall for a lot of speed. - RAG with a metadata filter. Retrieval-augmented generation (RAG): embed the question, fetch the closest chunks (
ORDER BY embedding <=> $1 LIMIT 5), filter by metadata such astenant_idorlang, then send those chunks to the model as context. The answer is grounded in your own data. - Azure Managed Redis. Azure Managed Redis keeps hot data in memory. Cache-aside: check Redis, and on a miss read the database and store the result with a TTL. When data changes, invalidate the key. Redis can also hold a vector index for fast similarity search, for example a semantic cache of answers.
Products arrive without embeddings. Let the change feed notice each new or edited product, write its embedding, and then answer shopper questions with VectorDistance over a DiskANN index.
🎓 Education-only simulation. Your lab is saved in this browser, so you can leave and continue later.
😟 THE PROBLEM
Search finds “refund” but misses “money back”.
😊 THE SOLUTION
Store embeddings and search by meaning, not by keyword.
- Keyword-only search✓ Embeddings capture meaning
- Comparing every vector✓ Approximate nearest neighbour indexes
- LLM guesses✓ RAG with retrieved chunks
Start with a question
A customer types "How do I get my money back?" but your help page only ever says "refund". How does search still find it?
A keyword search looks for the words “money” and “back”. Your refund policy doesn’t contain either, so it comes back empty, and the customer opens a support ticket.
A good shop assistant wouldn’t miss this. They hear the question, understand it’s about refunds, and walk you to the right shelf. Embeddings give your app the same trick: they turn text into numbers that capture meaning, and vector search finds the stored text whose numbers sit closest to the question.
Explain it like I’m 10
Visual: vector search in motion
Watch one question become 1,536 numbers, land on a map of meaning and pull back the closest help articles.
Read the video script
- A question in everyday wordsA customer types, how do I get my money back? Your help page never says money back. It says refund. So a keyword search comes back empty.
- Text becomes a vectorAn embedding model, here text embedding three small, reads that text and returns a vector. It's a list of 1,536 numbers. You'll only ever look at a few of them.
- Similar meaning, nearby pointsEvery help article was embedded the same way. Picture each vector as a pin on a map of meaning. Refunds and returns sit together, delivery questions sit somewhere else.
- The question finds its neighboursNow embed the question with the same model, and drop it on the map. It lands right next to refund policy. The database scores the closest pins with cosine similarity.
- Exact search checks every vectorWith no index, that's an exact k nearest neighbours search. It compares the question with every single vector. Recall is a hundred percent, but the work grows with every row you add.
- An ANN index jumps aheadAn approximate nearest neighbour index, like DiskANN or HNSW, jumps straight to the right neighbourhood and checks only a small slice. It's far faster, and now and then it misses one true match.
- Top results feed RAGTake the top results, say the best three chunks, and put them in the prompt. Now the chat model answers from your own refund policy instead of guessing. That's RAG.
The technical explanation
An embedding model reads text and returns a fixed-length array of floating-point numbers. With text-embedding-3-small you get 1,536 numbers by default; text-embedding-3-large gives 3,072. Both let you ask for fewer dimensions with the dimensions parameter, which saves storage at a small cost in quality. Whatever you choose, every vector in one index must have the same length.
Create an embedding in Python
You call the embedding deployment in your Foundry project the same way you’d call a chat model, just with embeddings.create:
import os
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
project = AIProjectClient(
endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
def embed(text: str) -> list[float]:
result = openai.embeddings.create(
model="text-embedding-3-small", # your DEPLOYMENT name
input=text,
)
return result.data[0].embedding # a list of 1,536 floats
vector = embed("How do I get my money back?")
print(len(vector)) # 1536
input can also be a list of strings, which embeds a batch in one call. That’s much cheaper on round trips when you’re loading thousands of documents.
How “close” is measured
The database compares the query vector with stored vectors using a distance function:
| Function | Range | Closest means | Notes |
|---|---|---|---|
| Cosine | -1 to 1 | Highest value | The usual default for text. Looks at direction, not length. |
| Dot product | -inf to +inf | Highest value | Same ranking as cosine when vectors are normalised (OpenAI embeddings are). |
| Euclidean | 0 to +inf | Lowest value | Straight-line distance. |
Pick the function your embedding model was trained for. For OpenAI text embeddings, cosine is the safe choice.
Exact versus approximate search
With no index, the database compares the question with every stored vector. That’s exact k-nearest neighbours (kNN): 100% recall, but the cost grows with every row you add. With a million vectors of 1,536 dimensions, that’s a lot of maths per question.
An approximate nearest neighbour (ANN) index builds a structure, usually a graph, that lets the search jump towards the right neighbourhood and check only a small slice of the data. You lose a little recall (you might miss one of the true top 10) and gain a big drop in latency and cost.
| Store on Azure | Exact option | ANN index options |
|---|---|---|
| Cosmos DB for NoSQL | flat (up to 505 dimensions), quantizedFlat (compressed) | diskANN |
| PostgreSQL + pgvector | No index (sequential scan) | hnsw, ivfflat, and DiskANN through the pg_diskann extension |
| Azure Managed Redis | FLAT | HNSW |
-
1 Ingest
Split documents into chunks and embed each chunk once.
-
2 Store
Save the text, its metadata and its vector together.
-
3 Embed the question
Use the same model and dimensions as the documents.
-
4 Search
Ask the database for the k closest vectors, with any filters.
-
5 Use the results
Show them, or pass them to a chat model as grounding (RAG).
Chunking matters more than people expect
If you embed a 40-page manual as one vector, the numbers become an average of everything in it, and nothing matches well. Split it into passages of a few hundred tokens, often with a small overlap so sentences aren’t cut in half, and store each chunk with metadata such as docId, page and tenantId. Then a search returns the exact paragraph, and filters keep one customer’s data away from another’s.
Architect level Where RAG fits
Retrieval-augmented generation is vector search plus a chat model. You embed the user’s question, fetch the top few chunks (with filters such as tenant or language), and put those chunks in the prompt as context. The model answers from your data instead of guessing. The quality of a RAG app depends mostly on the retrieval step: good chunks, the right filters and a sensible k. A bigger chat model won’t fix chunks that are wrong.
Many apps also add hybrid search, which combines a vector score with a keyword (full-text) score. That helps with exact terms the embedding model may blur, like product codes or error numbers.
Real-world business scenario
Northwind Appliances (fictional)
- The problem
- The help centre search matched keywords only. Customers who typed "washer smells" never found the article titled "Cleaning the drum seal", and support tickets kept growing.
- What they used
- Help articles split into chunks, embedded with text-embedding-3-small and stored with their vectors in Azure Cosmos DB for NoSQL, which already held the article catalogue. Questions are embedded with the same deployment and searched with a diskANN vector index.
- Why that choice
- The vectors sit in the same items as the articles, so there was no second database to keep in sync, and meaning-based search finds articles that share no words with the question.
- The result
- Customers find the right article from everyday wording, and the same retrieval step later fed a chat assistant that answers from those articles.
When to use it and when not to
✓ Use it when…
- Users describe things in their own words and you need results by meaning, not exact keywords.
- You're building RAG, recommendations (similar products) or duplicate detection.
- You need to search across languages or across text and images with a multimodal model.
✕ Think twice when…
- You need exact matches, such as an order number or an email address. A normal index or filter is cheaper and exact.
- Your data is tiny and fixed. A simple list or keyword search may be all you need.
- You can't keep the embedding model stable. Every model change means re-embedding everything.
↔ Alternatives to consider
- Full-text search for keywords, phrases and exact terms.
- Hybrid search to combine keyword and vector scores in one ranking.
- Azure AI Search when you want a dedicated search service with indexers, skills and semantic ranking.
Test yourself with exercises
5 original practice questions in the AI-200 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.
Interview preparation
Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.
Beginner What is an embedding, in plain words?
Model answer
It's a list of numbers that captures what a piece of text means. An embedding model reads "How do I get my money back?" and returns, say, 1,536 numbers. A sentence about refunds gets numbers close to it, even if it shares no words, so I can search by meaning instead of by keyword.
Interviewer follows up
Why can't you just use keyword search?
You
Keyword search misses synonyms. A customer types "money back" and the policy says "refund". Vector search finds it because the meanings are close.
Intermediate You embedded your documents with text-embedding-3-small. Which model do you use for the user's question?
Model answer
The same one, with the same dimensions. Vectors from different models live in different spaces, so comparing them gives meaningless distances. If I change the model, I re-embed every document.
Experienced developer What's the difference between exact and approximate vector search, and when would you pick each?
Model answer
Exact kNN compares the query with every vector, so recall is 100% but cost grows with the data. Approximate search uses an index like DiskANN or HNSW and checks only a small part of the graph, so it's far faster and cheaper with a small loss in recall. For a few thousand vectors, or when a filter narrows the set a lot, exact is fine. For hundreds of thousands or millions, I use an ANN index and tune it for the recall I need.
Scenario Search results got noticeably worse after a teammate re-ran the ingestion pipeline. What would you check first?
Model answer
Whether the pipeline used a different embedding model or a different dimensions setting from the one the query code uses. Then whether the chunking changed, for example whole PDFs embedded as one vector instead of paragraphs. Mixed models or giant chunks both blur the results.
Architecture & design How do you decide between Cosmos DB, PostgreSQL and Redis for vectors?
Model answer
I keep vectors next to the data that already lives somewhere. Product catalogue in Cosmos DB, I use its built-in vector index. Relational data with joins and SQL filters, PostgreSQL with pgvector. If I need sub-millisecond lookups or a semantic cache of answers, Azure Managed Redis. Avoiding a second copy of the data usually matters more than small speed differences.
Quick revision
Key points
- An embedding model turns text into a vector; similar meaning gives close vectors.
- text-embedding-3-small returns 1,536 dimensions by default; text-embedding-3-large returns 3,072.
- Embed documents and questions with the same model and the same dimensions.
- Cosine is the usual distance function; dot product and Euclidean are the others.
- Exact kNN gives full recall; ANN indexes (DiskANN, HNSW, IVFFlat) trade a little recall for speed.
- Chunk long documents so each vector holds one focused idea.
Important terminology
- Embedding
- A fixed-length list of numbers that represents the meaning of a piece of text, an image or other data.
- Dimensions
- The length of an embedding vector, for example 1,536 for text-embedding-3-small.
- Cosine similarity
- A measure of how closely two vectors point in the same direction, from -1 (opposite) to 1 (same meaning).
- k-nearest neighbours (kNN)
- An exact search that compares the query vector with every stored vector and returns the k closest.
- Approximate nearest neighbour (ANN)
- A search that uses an index such as DiskANN or HNSW to find most of the closest vectors much faster, trading a little recall.
- Recall
- The share of the true closest items that a search actually returns.
- Chunking
- Splitting long documents into smaller passages before embedding, so each vector represents one focused idea.
Common mistakes
- Embedding the query with a different model, or different dimensions, from the stored documents.
- Embedding whole long documents as one vector, which blurs the meaning.
- Forgetting to set the vector dimensions in the database to match the model.
Exam tips
- "Find items with similar meaning, not matching words" = vector search over embeddings.
- "Vectors from model A, queries from model B" is always wrong; re-embed with one model.
- "Lower latency on millions of vectors, small recall loss acceptable" = an ANN index (DiskANN or HNSW).
Five quick revision questions
-
1.How many dimensions does text-embedding-3-small return by default?Show
1,536.
-
2.Which distance function is the usual default for text embeddings?Show
Cosine.
-
3.What do you call search that checks every vector?Show
Exact k-nearest neighbours (kNN), or brute force.
-
4.Name two ANN index algorithms.Show
DiskANN and HNSW (IVFFlat is another).
-
5.Why split documents into chunks before embedding?Show
So each vector represents one focused passage, which makes retrieval more precise.
Official references
Finished this lesson? Tick it off. Your progress is saved in this browser.
Next up: Cosmos DB for NoSQL: Connect with the SDK and Query
Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges.