Vector Search in Cosmos DB for NoSQL
30-second answer
To search vectors in Azure Cosmos DB for NoSQL, you create the container with a vector embedding policy (the vector path, dataType such as float32, dimensions such as 1536, and distanceFunction such as cosine) and add a vector index (flat, quantizedFlat or diskANN) to its indexing policy, excluding the vector path from the range index. You store each embedding inside the item, then run SELECT TOP k ... ORDER BY VectorDistance(c.embedding, @q) to get the most similar items first.
Exam objective: 2.1.3 Store and retrieve embeddings and execute vector similarity search for semantic retrieval. (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
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: diskANN or quantizedFlat for large sets, or flat for exact search on small vectors (up to 505 dimensions). Then ORDER BY VectorDistance(c.embedding, @q) returns the closest items.
🤔 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
Your chat app’s memory and your vector store live in two systems.
😊 THE SOLUTION
Store embeddings in Cosmos DB and search them with VectorDistance.
- Two databases to sync✓ Vectors next to the data
- Slow full scans✓ diskANN vector index
- Wrong distance function✓ Cosine in the vector policy
Start with a question
Your product catalogue already lives in Cosmos DB. Do you need a separate vector database for semantic search?
Imagine a shop that keeps its stock in one storeroom and its “items customers liked together” list in a different building across town. Every time stock changes, someone has to drive over and update the list. Sooner or later they get out of sync.
Azure Cosmos DB for NoSQL lets you keep the vector in the same item as the product. You tell the container where the vector is with a vector embedding policy, give it a vector index, and ask for the closest items with VectorDistance. No second database, no sync job.
Explain it like I’m 10
The technical explanation
You don’t need to enable a feature on the account. You define two things when you create the container: a vector embedding policy and the vector indexes.
1. The vector embedding policy
vector_embedding_policy = {
"vectorEmbeddings": [
{
"path": "/embedding",
"dataType": "float32",
"dimensions": 1536, # text-embedding-3-small
"distanceFunction": "cosine",
}
]
}
| Setting | Allowed values |
|---|---|
path | The property that holds the vector. No wildcards, and not nested inside an array. |
dataType | float32 (default), float16, int8, uint8. float16 halves storage with a small accuracy cost. |
dimensions | Length of every vector at that path. Default 1536. |
distanceFunction | cosine (default, -1 to 1, higher is closer), dotproduct, euclidean (lower is closer). |
You can have several vector paths, for example one for text and one for images, each with its own entry.
2. The vector index
indexing_policy = {
"indexingMode": "consistent",
"includedPaths": [{"path": "/*"}],
"excludedPaths": [
{"path": "/\"_etag\"/?"},
{"path": "/embedding/*"}, # keep the range index off the vector
],
"vectorIndexes": [
{"path": "/embedding", "type": "diskANN"}
],
}
| Index type | How it searches | Max dimensions | Good for |
|---|---|---|---|
flat | Exact, brute force, 100% recall | 505 | Small vectors where exact results matter |
quantizedFlat | Brute force over compressed vectors | 4,096 | Up to about 50,000 vectors in scope, or searches narrowed by filters |
diskANN | Approximate nearest neighbour graph | 4,096 | Large sets, lowest latency and RU cost |
quantizedFlat and diskANN need at least 1,000 vectors before they’re used. With fewer, Cosmos DB does a full scan, which works but costs more RUs.
3. Create the container and store items
from azure.cosmos import PartitionKey
container = database.create_container_if_not_exists(
id="faq",
partition_key=PartitionKey(path="/tenantId"),
indexing_policy=indexing_policy,
vector_embedding_policy=vector_embedding_policy,
)
question = "How do I get my money back?"
container.upsert_item({
"id": "faq-17",
"tenantId": "contoso",
"question": question,
"answer": "Refunds go back to the original card within 5 to 7 working days.",
"embedding": embed(question), # 1,536 floats from text-embedding-3-small
})
embed() is the helper that calls your embedding deployment (see the embeddings lesson). Use the same model and dimensions for stored items and for questions.
4. Search with VectorDistance
query_vector = embed("I want a refund")
results = container.query_items(
query="""
SELECT TOP 3 c.id, c.question, c.answer,
VectorDistance(c.embedding, @q) AS score
FROM c
WHERE c.tenantId = @tenant
ORDER BY VectorDistance(c.embedding, @q)
""",
parameters=[
{"name": "@q", "value": query_vector},
{"name": "@tenant", "value": "contoso"},
],
partition_key="contoso",
)
for r in results:
print(round(r["score"], 3), r["question"])
ORDER BY VectorDistance(...) already sorts the most similar items first, whatever the distance function, so you don’t add DESC. Always include TOP N: without it the query tries to return far more results than you need and costs more RUs.
VectorDistance also takes optional arguments: a third, boolean argument forces a brute-force search, and a fourth, JSON options argument can override the distanceFunction or dataType and set searchListSizeMultiplier, which raises diskANN’s recall for more RUs.
-
1 Embed
Turn the question into 1,536 floats with the same model.
-
2 Filter
WHERE c.tenantId = @tenant narrows the search to one partition.
-
3 Rank
The diskANN index finds the nearest vectors.
-
4 Return
TOP 3 items with their similarity score.
Architect level Limits and design choices worth knowing
- Plan the policy up front. You can add or remove vector paths, but you can’t change an existing path’s dimensions or distance function in place. You’d drop the vector index and policy and add them back. Changing embedding models usually means re-embedding into a new path or container.
- No turning back. Once vector indexing and search are on for a container, you can’t disable them.
- Shared throughput databases don’t support vector indexing and search; give the container its own throughput.
- Approximate means approximate. diskANN results can vary slightly between runs, because each replica builds its own index. Use
flat(where dimensions allow) when you need exact results. - Hybrid search. With a full-text policy and index you can rank by both meaning and keywords:
ORDER BY RANK RRF(VectorDistance(c.embedding, @q), FullTextScore(c.answer, "refund")). Reciprocal rank fusion merges the two rankings. - Keep vectors fresh. When an item’s text changes, its vector is stale. A change feed consumer can re-embed changed items automatically (next lesson).
Real-world business scenario
Wide World Importers (fictional)
- The problem
- Buyers searched 800,000 product listings with keywords and missed items described in other words. The team had planned a separate vector database plus a nightly sync job.
- What they used
- They added a vector embedding policy (/embedding, float32, 1536, cosine) and a diskANN index to a new products container in the Cosmos DB account they already used, partitioned by /supplierRegion, and query with TOP 10 ORDER BY VectorDistance plus filters on region and stock.
- Why that choice
- Vectors live in the same items as price and stock, so search results are never out of date, and diskANN keeps latency and RUs low at this size.
- The result
- Buyers get relevant products from plain-language searches, and there's no second database or sync job to run.
When to use it and when not to
✓ Use it when…
- Your operational data already lives in Cosmos DB and you want semantic search on it.
- You need vector search combined with normal filters, such as tenant, region or stock.
- You want vectors and data updated together, with no sync job.
✕ Think twice when…
- Your container sits in a shared-throughput database. Vector search isn't supported there.
- You need joins across tables before ranking. PostgreSQL with pgvector suits relational data better.
- You need a dedicated search service with indexers, enrichment skills and semantic ranking over many sources. That's Azure AI Search.
↔ Alternatives to consider
- PostgreSQL with pgvector for relational data and SQL filters.
- Azure Managed Redis for in-memory vector search and semantic caching.
- Azure AI Search for search across many data sources.
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 two things must you set on a Cosmos DB container before vector search works well?
Model answer
A vector embedding policy, which tells Cosmos DB where the vector is, how many dimensions it has, its data type and the distance function. And a vector index in the indexing policy, so searches don't have to compare against every item.
Intermediate Your embeddings have 1,536 dimensions. Can you use a flat index?
Model answer
No. The flat index is capped at 505 dimensions. For 1,536 I'd use quantizedFlat if the search scope is small, say under about 50,000 vectors after filters, or diskANN for anything larger.
Experienced developer Why does Microsoft recommend putting the vector path in excludedPaths?
Model answer
Without it, the normal range index also indexes every element of the array, which makes inserts cost more RUs and take longer. The vector index is a separate index, so excluding the path from the range index loses nothing for vector search.
Interviewer follows up
And why always use TOP N?
You
Without TOP the query tries to return many more results than you need, so it costs more RUs and takes longer.
Scenario Your vector query returns slightly different results each run on an unchanged container. Is something broken?
Model answer
Not necessarily. diskANN is approximate, and each replica builds its own index, so small differences in the order or the tail of the results are expected. If I need exact results I'd use a flat index where the dimensions allow, or raise searchListSizeMultiplier to trade RUs for recall.
Architecture & design How do you keep a multi-tenant RAG app from returning another customer's documents?
Model answer
I add a WHERE filter on tenantId to every vector query, and ideally make tenantId the partition key so the search stays in that tenant's partition. Vector search combines with normal filters, so the filter and the ORDER BY VectorDistance live in the same query.
Quick revision
Key points
- Vector embedding policy: path, dataType (float32, float16, int8, uint8), dimensions (default 1536), distanceFunction (cosine default, dotproduct, euclidean).
- Vector index types: flat (exact, max 505 dims), quantizedFlat (max 4,096), diskANN (approximate, max 4,096).
- quantizedFlat and diskANN need at least 1,000 vectors before the index is used; below that it's a full scan.
- Put the vector path in excludedPaths and in vectorIndexes.
- Query with SELECT TOP k ... ORDER BY VectorDistance(c.embedding, @q); most similar comes first.
- Vector search can't be turned off on a container once enabled, and isn't supported in shared-throughput databases.
Important terminology
- Vector embedding policy
- The container setting that lists each vector path with its data type, dimensions and distance function.
- VectorDistance
- The Cosmos DB query function that returns the similarity score between a stored vector and a query vector.
- flat index
- An exact (brute-force) vector index with 100% recall, limited to 505 dimensions.
- quantizedFlat index
- A brute-force index over compressed vectors, up to 4,096 dimensions, a good fit for about 50,000 vectors or fewer in the search scope.
- diskANN index
- An approximate nearest neighbour index from Microsoft Research for fast, low-RU search over large vector sets, up to 4,096 dimensions.
- TOP N
- The clause that limits how many results a vector query returns. Always include it in vector searches.
Common mistakes
- Using a flat index for 1,536-dimension vectors.
- Leaving out TOP N, which raises RU cost and latency.
- Embedding the query with a different model or dimension count from the stored vectors.
Exam tips
- "Exact results, small vectors (≤ 505 dimensions)" = flat.
- "Millions of vectors, lowest latency and RU cost" = diskANN.
- "Rank items by similarity" = ORDER BY VectorDistance(...) with TOP N.
Five quick revision questions
-
1.What's the maximum dimension count for a flat vector index?Show
505.
-
2.Which function ranks items by similarity in a Cosmos DB query?Show
VectorDistance.
-
3.What's the default distance function in the vector policy?Show
Cosine.
-
4.Which index type is approximate?Show
diskANN.
-
5.Where does the vector path go in the indexing policy besides vectorIndexes?Show
excludedPaths.
Official references
Finished this lesson? Tick it off. Your progress is saved in this browser.
Next up: Cosmos DB Change Feed Processor
Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges.