Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 12 of 28
❮Prev Next❯

Vector Search in Cosmos DB for NoSQL

Module 2: Data for AI ⏱ 12 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    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.

    Simulate it » No Azure account needed

    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.

    Azure portal: Add a vector policy and index, then run VectorDistance Add a vector policy and index, then run VectorDistance.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading the portal…

    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
    1. Open Data Explorer and select New Container. The vector setup lives on the container, not the account.
    2. Add a vector embedding policy (path, data type, dimensions, distance function) and a vector index. Both are fixed once the container exists.
    3. Your app embeds the question, then asks for the three closest items. Filtering on the partition key keeps it cheap.
    4. With cosine, a higher score is closer. These three chunks go into the prompt for grounding.
    5. 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.

    😟 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
    🛠️ Solved with: Cosmos DB vector search

    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",
            }
        ]
    }
    SettingAllowed values
    pathThe property that holds the vector. No wildcards, and not nested inside an array.
    dataTypefloat32 (default), float16, int8, uint8. float16 halves storage with a small accuracy cost.
    dimensionsLength of every vector at that path. Default 1536.
    distanceFunctioncosine (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 typeHow it searchesMax dimensionsGood for
    flatExact, brute force, 100% recall505Small vectors where exact results matter
    quantizedFlatBrute force over compressed vectors4,096Up to about 50,000 vectors in scope, or searches narrowed by filters
    diskANNApproximate nearest neighbour graph4,096Large 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. 1 Embed

      Turn the question into 1,536 floats with the same model.

    2. 2 Filter

      WHERE c.tenantId = @tenant narrows the search to one partition.

    3. 3 Rank

      The diskANN index finds the nearest vectors.

    4. 4 Return

      TOP 3 items with their similarity score.

    A vector query in Cosmos DB
    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

    B2B wholesale

    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.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    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.

    Question 1

    Question 1 of 5

    You are creating a container in Azure Cosmos DB for NoSQL to store product descriptions with embeddings that have 1,536 dimensions. The container will hold about 3 million items, and searches must have the lowest possible latency and RU cost.

    Which vector index type should you configure?

    Question 2

    Question 2 of 5 · Select 3

    You are defining the vector embedding policy for a container that stores embeddings from text-embedding-3-small. Which THREE properties must you specify for each vector path in the policy?

    Question 3

    Question 3 of 5

    You need to return the five FAQ items whose embedding property is most similar to a query vector passed as the parameter @q. Which query should you use?

    Question 4

    Question 4 of 5

    A container has a vector index on the /embedding path. Inserts have high RU charges and latency. The indexing policy includes the path /* and excludes only /_etag/?. What should you change?

    Question 5

    Question 5 of 5

    A multitenant retrieval application stores document chunks for many customers in one container that is partitioned by /tenantId. Vector searches must return chunks only from the current customer's documents. What should you do?

    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. 1.What's the maximum dimension count for a flat vector index?Show

      505.

    2. 2.Which function ranks items by similarity in a Cosmos DB query?Show

      VectorDistance.

    3. 3.What's the default distance function in the vector policy?Show

      Cosine.

    4. 4.Which index type is approximate?Show

      diskANN.

    5. 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

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.