Lesson 1 of 3 Vector Search and Change Feed in Azure Cosmos DB

Running Vector Search in Cosmos DB for NoSQL

This lesson explains vector embedding policies, vector index types, VectorDistance queries, hybrid search and the limits that shape a design.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the fields of a vector embedding policy.
  • Choose a vector index type for a collection.
  • Explain why vector queries need TOP N.
  • Describe how hybrid search combines rankings.

Vectors next to the data

A separate vector database must be kept synchronized with the operational database, and every synchronization delay or failure makes search results disagree with the data. Cosmos DB for NoSQL avoids this by storing embeddings as ordinary properties of the items they describe: a product item can carry its name, price, stock level and a 1,536-element embedding array. A vector query can then filter on price or stock in the same request and return current values, and there is no second copy to manage.

Vector search is enabled per account with the EnableNoSQLVectorSearch capability, from the portal's Features page or with az cosmosdb update --capabilities EnableNoSQLVectorSearch. The registration can take up to about 15 minutes to apply. Once vector indexing and search are enabled on a container, they cannot be disabled.

Vector embedding policies

Each container that stores vectors needs a container vector policy, which tells the engine where vectors are and how to compare them. It is defined when the container is created and holds one entry per vector path.

  • path: the property that holds the vector, such as /embedding. Paths inside arrays and wildcards are not supported.
  • dataType: float32 (the default for most models), float16, which halves storage with a small accuracy loss, int8 or uint8.
  • dimensions: the vector length, which must match the embedding model, such as 1536 (the default).
  • distanceFunction: cosine (the default), dotproduct or euclidean.
{
  "vectorEmbeddings": [
    { "path": "/embedding", "dataType": "float32", "distanceFunction": "cosine", "dimensions": 1536 }
  ]
}

A container can hold several vector paths, for example a text embedding and an image embedding, each with its own policy entry. Policy settings cannot be edited in place; changing a path's dimensions or distance function means removing the entry and its index and adding them again, which in practice usually means a new container.

Match the pairs

Vector policy fields

Exam skills 2.1.3

Match each field of a container vector policy with what it sets.

Log in to try this activity Interactive activities are free with an account.

Vector index types

Without a vector index, a vector query scans every item, which costs many RUs on a large container. The container's indexing policy can add a vector index for each vector path, in its vectorIndexes section. The vector path should also be listed in excludedPaths, so that the ordinary range index does not index every number in the array, which would make writes expensive.

flat
Search typeExact (brute force) over full vectors
Maximum dimensions505
Recall100%
Minimum dataNone
Choose when Small vectors where exact results are required
quantizedFlat
Search typeBrute force over compressed vectors
Maximum dimensions4,096
RecallSlightly below 100%
Minimum data1,000 vectors, else full scan
Choose when Up to about 50,000 vectors in a query's scope
diskANN
Search typeApproximate nearest neighbour
Maximum dimensions4,096
RecallHigh, tunable per query
Minimum data1,000 vectors, else full scan
Choose when Large collections above about 50,000 vectors in scope

The 505-dimension limit of flat rules it out for most text embedding models, whose vectors have 1,536 or 3,072 dimensions; those models use quantizedFlat or diskANN (3,072-dimension vectors fit within the 4,096 limit). Quantized indexes accept an optional quantizerType of product (the default) or spherical. Because diskANN is approximate and each replica builds its own index, the same query can return slightly different results between runs, which is expected behaviour.

{
  "indexingMode": "consistent",
  "automatic": true,
  "includedPaths": [ { "path": "/*" } ],
  "excludedPaths": [ { "path": "/\"_etag\"/?" }, { "path": "/embedding/*" } ],
  "vectorIndexes": [ { "path": "/embedding", "type": "diskANN" } ]
}

The following diagram shows the container policy and the query.

The product search container's policy and query. The vector policy declares /embedding as float32 with 1,536 dimensions and cosine distance, with a diskANN index because 1,536 dimensions exceeds the flat index limit; the embedding path is excluded from the range index, and a full-text index covers the description. The query uses TOP, filters on category and stock, and ranks with hybrid search so that model codes match exactly.
Policy fragments are abbreviated; GTX-500 stands for a model code a shopper types.
Scenario questions

Choosing a vector index

Exam skills 2.1.3

Choose the Cosmos DB vector index type for each container.

Log in to try this activity Interactive activities are free with an account.

Querying with VectorDistance

A vector search uses the VectorDistance system function, which takes the vector property and the query vector and returns a similarity score under the container's distance function. The query must sort by that function and must limit results with TOP N; without TOP, the engine tries to score and return far more items than needed, which costs more RUs and time.

query_vector = client_openai.embeddings.create(
    model="text-embedding-3-small", input=["waterproof hiking boots"]).data[0].embedding

results = container.query_items(
    query=("SELECT TOP 5 c.id, c.name, c.price, VectorDistance(c.embedding, @q) AS score "
           "FROM c WHERE c.category = @cat AND c.inStock = true "
           "ORDER BY VectorDistance(c.embedding, @q)"),
    parameters=[{"name": "@q", "value": query_vector}, {"name": "@cat", "value": "footwear"}],
    enable_cross_partition_query=True)
for item in results:
    print(item["name"], round(item["score"], 3))

ORDER BY VectorDistance(...) returns the most similar items first, whichever metric is used. The projection should exclude the embedding itself, because returning 1,536 numbers per item wastes bandwidth and RUs. The WHERE clause filters candidates on ordinary indexed properties, and supplying a partition key (for example, a tenant ID) scopes the search to one partition, which improves both cost and isolation. Optional arguments to VectorDistance can force a brute-force search or, for diskANN, raise searchListSizeMultiplier to increase recall at the cost of latency and RUs.

Spot the bug

A costly vector query

Exam skills 2.1.3

Find the lines that make this vector search slower and more expensive than necessary.

Log in to try this activity Interactive activities are free with an account.

Full-text and hybrid search

Embeddings capture meaning but handle exact tokens such as model numbers, error codes and names less reliably. Cosmos DB for NoSQL also supports full-text search: a full-text policy and full-text index on text paths enable functions such as FullTextContains and the relevance score FullTextScore, which ranks by BM25-style term relevance. Hybrid search combines the two rankings with the RRF (Reciprocal Rank Fusion) function in an ORDER BY RANK clause.

SELECT TOP 10 c.id, c.name
FROM c
ORDER BY RANK RRF(VectorDistance(c.embedding, @q), FullTextScore(c.description, "GTX-500"))

Hybrid search suits catalog and support scenarios in which users type both descriptions and identifiers, and it often improves RAG retrieval quality over vector search alone.

Sort into groups

Vector, full-text or hybrid?

Exam skills 2.1.3

Decide which kind of search fits each query.

Log in to try this activity Interactive activities are free with an account.

Design limits and costs

Several limits shape a vector design in Cosmos DB, and exam distractors often break one of them.

Limit or behaviourConsequence
Vector search is not supported on accounts with shared (database-level) throughputUse dedicated container throughput or serverless
quantizedFlat and diskANN need at least 1,000 vectorsSmall test containers fall back to a full scan with higher RU charges
Very large bursts of inserts (millions of vectors quickly) lengthen index build timeThrottle bulk loads and allow time before measuring query cost
Policies and vector indexes cannot be modified in placePlan dimensions and distance function before creating the container
Indexes are optimized for real model embeddingsRandom test vectors give misleading recall results
True or false

Design limits

Exam skills 2.1.3

Decide whether each statement about Cosmos DB vector limits is true.

Log in to try this activity Interactive activities are free with an account.
Worked example

Designing a product search container

A retailer stores 800,000 products in Cosmos DB and embeds each description with text-embedding-3-small (1,536 dimensions). Shoppers search by description, often typing exact model codes, and results must show only in-stock items from the selected category. The team wants low RU cost per search.

The container needs a vector policy on /embedding with float32, 1,536 dimensions and cosine, and a diskANN vector index, because the collection is far above 50,000 vectors and 1,536 dimensions exceeds the flat limit. The embedding path is excluded from the range index. Queries use TOP N, filter on category and stock in the WHERE clause, and use hybrid search with a full-text index on the description so that model codes match exactly.

A flat index would be rejected for 1,536 dimensions. Leaving the embedding in the range index would make every product update expensive. A query without TOP would score far more items than needed.

Check yourself

Why can a container that stores 1,536-dimension embeddings not use a flat vector index?

Show answer

The flat index supports at most 505 dimensions. Embeddings of 1,536 dimensions need quantizedFlat or diskANN, which support up to 4,096.

Exam Tips

Remember for the exam

  • Enable EnableNoSQLVectorSearch, define a vector policy, and add a vector index.
  • flat: exact, up to 505 dimensions; quantizedFlat and diskANN: up to 4,096 and need 1,000 vectors.
  • Always use TOP N with ORDER BY VectorDistance, and exclude the vector path from the range index.
  • Hybrid search combines VectorDistance and FullTextScore with RRF.