Tag: Vector Similarity Search

Implement vector indexing to enable similarity search (AI-200 Exam Prep)

This post is a part of the AI-200: Developing AI Cloud Solutions on Azure  Exam Prep Hub.
This topic falls under these sections:
Develop AI solutions by using Azure data management services (25–30%)
   --> Integrate Azure Managed Redis in AI solutions
      --> Implement vector indexing to enable similarity search


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Overview

Vector similarity search is a foundational capability for modern AI applications. It allows an application to retrieve data based on semantic similarity rather than requiring an exact keyword match.

For the AI-200: Developing AI Cloud Solutions on Azure exam, you should understand how Azure Managed Redis can be used as a low-latency vector database, how vectors are stored and indexed, the difference between FLAT and HNSW indexing, how distance metrics affect similarity calculations, and how vector indexes are queried.

Azure Managed Redis provides vector search through the RediSearch module. Vector data can be stored in Redis hashes or JSON documents and indexed for similarity searches.


1. What Is Vector Similarity Search?

Traditional database searches generally look for exact or textual matches.

For example:

"How do I reset my password?"

A keyword-based search might look for documents containing:

  • password
  • reset
  • credentials
  • account

Vector search takes a different approach.

The text is converted into an embedding, which is a numerical representation of the semantic meaning of the text.

For example:

"How do I reset my password?"
Embedding model
[0.021, -0.134, 0.087, ..., 0.442]

A document such as:

“Steps for recovering your account credentials”

may have an embedding that is mathematically close to the query embedding even though the document does not contain the exact phrase “reset my password.”

This allows vector search to find semantically related information.


2. What Is an Embedding?

An embedding is a high-dimensional numerical representation of data.

Embeddings can represent:

  • Text
  • Documents
  • Images
  • Products
  • Audio
  • Other types of content

The embedding model transforms the original content into a vector.

For example:

Document
Embedding model
[0.12, -0.04, 0.81, 0.23, ...]

The number of dimensions depends on the embedding model.

Important exam concept

The vectors being indexed and the query vectors must be compatible.

In particular, the vector index configuration must match the characteristics of the embedding model, including:

  • Vector dimensions
  • Distance metric
  • Vector representation/type

Using inconsistent embedding models can produce poor or invalid search results.


3. Azure Managed Redis as a Vector Database

Azure Managed Redis is primarily known for high-performance in-memory data operations, but it can also support vector workloads.

With the appropriate Redis functionality enabled, it can:

  1. Store embeddings.
  2. Create vector indexes.
  3. Search vectors.
  4. Return the nearest vectors.
  5. Combine vector searches with metadata filtering.

This makes Azure Managed Redis useful for applications such as:

  • Semantic search
  • Retrieval-augmented generation (RAG)
  • Recommendation systems
  • Semantic caching
  • Conversational memory
  • Document retrieval
  • Similarity matching

The major advantage is low-latency access, particularly when vector search is being performed alongside other Redis-based application data.


4. RediSearch and Vector Indexing

Azure Managed Redis uses the RediSearch functionality to provide vector search.

For Azure Managed Redis vector search, RediSearch must be enabled when the Redis instance is created. It cannot simply be added later to an existing instance.

Current Azure Managed Redis documentation identifies RediSearch support for:

  • Memory Optimized
  • Balanced
  • Compute Optimized

The Flash Optimized tier does not support RediSearch. Azure Managed Redis vector workloads also require the Enterprise clustering policy.

Exam tip

If a scenario says:

“An existing Azure Managed Redis instance does not have RediSearch enabled. The application now needs vector similarity search.”

The important consideration is that the required module must be enabled during provisioning. You should not assume that the module can simply be installed onto an existing Azure Managed Redis instance.


5. Storing Vectors in Redis

Azure Managed Redis supports storing vector data in Redis data structures such as:

  • Hashes
  • JSON documents

Hashes

Hashes are useful when the application has relatively straightforward fields.

Conceptually:

document:123
title = "Azure AI"
category = "AI"
embedding = [ ... ]

JSON

JSON can be useful when the application has more complex or nested document structures.

Conceptually:

{
"id": "document-123",
"title": "Azure AI",
"category": "AI",
"embedding": [ ... ],
"metadata": {
"author": "Norm",
"year": 2026
}
}

The choice between hashes and JSON depends on the application’s data model and how the data will be accessed.

Microsoft’s current guidance specifically identifies both hashes and JSON as supported approaches for vector storage.


6. Why Metadata Matters

A vector should generally not exist by itself.

Applications often store metadata alongside the vector, such as:

  • Document ID
  • Document title
  • Category
  • Source URL
  • Timestamp
  • Tenant ID
  • Author
  • Security/access-control information

For example:

Document:
id = 1001
title = "Azure Container Apps"
category = "Azure"
tenant = "Contoso"
embedding = [...]

Metadata enables filtered vector search.

For example:

Find the 5 documents most similar to this question, but only search documents belonging to the Azure category.

Or:

Find similar documents that the current user is authorized to access.

This becomes particularly important in multi-tenant and RAG applications.


7. Vector Indexing Strategies

The two important vector indexing strategies you should know for AI-200 are:

IndexDescriptionTypical use
FLATExact/brute-force searchSmaller datasets or maximum accuracy
HNSWApproximate nearest-neighbor graphLarger datasets and lower latency

Understanding the trade-off between these approaches is important for the exam.


8. FLAT Index

A FLAT index performs an exhaustive comparison.

Conceptually:

Query vector
|
+---- Compare with Vector 1
+---- Compare with Vector 2
+---- Compare with Vector 3
+---- Compare with Vector 4
+---- ...
+---- Compare with Vector N

Every candidate vector is evaluated.

Advantages

  • Exact search
  • High recall
  • Straightforward behavior
  • Useful for relatively small datasets

Disadvantages

  • More computationally expensive as the dataset grows
  • Latency can increase with the number of vectors

FLAT is therefore appropriate when exhaustive accuracy is more important than minimizing search computation.


9. HNSW Index

HNSW stands for Hierarchical Navigable Small World.

Instead of comparing the query against every vector, HNSW organizes vectors into a graph that allows the search to navigate toward likely nearest neighbors.

Conceptually:

                 Vector A
                /        \
           Vector B     Vector C
             /             \
        Vector D           Vector E
             \             /
                Vector F

The actual structure is considerably more sophisticated, but the important idea is that the index provides an efficient path toward nearby vectors.

Advantages

  • Fast similarity searches
  • Well suited to larger datasets
  • Reduces the amount of computation required
  • Supports approximate nearest-neighbor search

Disadvantages

  • Search is approximate rather than exhaustive
  • Indexing requires additional resources
  • There is a trade-off between search speed, recall, and resource consumption

Microsoft identifies HNSW as a common choice for larger datasets where lower latency is more important than exhaustive precision.


10. FLAT vs. HNSW

A useful way to remember the difference is:

FLAT = accuracy through exhaustive search

HNSW = speed through approximate search

For example:

Scenario A

You have 10,000 vectors and require exact results.

FLAT may be appropriate.

Scenario B

You have millions of vectors and require very low search latency.

HNSW is generally a better candidate.

The correct choice depends on:

  • Dataset size
  • Required latency
  • Accuracy/recall requirements
  • Available resources
  • Workload characteristics

11. Distance and Similarity Metrics

Once vectors are indexed, Redis needs a way to determine how close two vectors are.

Common metrics include:

Cosine

Cosine similarity measures the angle between vectors.

It is commonly used for text embeddings.

Conceptually:

Vector A
angle
Vector B

The smaller the angular difference, the more semantically similar the vectors generally are.

Euclidean / L2

Euclidean distance measures the straight-line distance between vectors.

A ●----------------● B
distance

A smaller distance indicates greater similarity.

Inner Product

Inner product, also called dot product in many contexts, can be used for similarity/ranking depending on how embeddings are generated and normalized.

Azure Managed Redis vector search supports metrics including:

  • L2
  • COSINE
  • IP

The appropriate metric depends on the embedding model and how its vectors are represented.


12. KNN Search

A common vector-search operation is K-nearest neighbors (KNN).

Suppose the application asks:

“Which five documents are most similar to this question?”

The application sets:

K = 5

The vector search returns the five nearest vectors according to the selected similarity/distance metric.

Conceptually:

Query
|
+-- Result 1 ← most similar
+-- Result 2
+-- Result 3
+-- Result 4
+-- Result 5

KNN is especially useful in:

  • Semantic search
  • Recommendation systems
  • RAG
  • Similarity matching

Azure Managed Redis supports KNN and vector range queries.


13. Approximate Nearest Neighbor Search

ANN, or approximate nearest neighbor search, attempts to find vectors that are very close to the query without necessarily exhaustively comparing every vector.

This can dramatically reduce search latency and computational requirements.

The trade-off is:

You may sacrifice some recall for significantly better performance.

HNSW is an example of an indexing strategy commonly used to enable efficient approximate nearest-neighbor searches.


14. Vector Index Configuration

When creating a vector index, think about the following characteristics:

1. Data structure

Will the vectors be stored in:

  • Hashes?
  • JSON documents?

2. Vector field

Which property contains the embedding?

For example:

embedding

3. Vector dimensions

The index must accommodate the dimensionality of the embeddings.

4. Distance metric

Choose the appropriate metric, such as:

COSINE
L2
IP

5. Index algorithm

Choose between:

FLAT
HNSW

6. Metadata fields

Determine which fields need to support filtering.


15. Example Conceptual Data Model

Consider a RAG application containing technical documentation.

A Redis record might conceptually look like:

document:1001
title:
"Azure Container Apps"
category:
"Containers"
source:
"https://example.com/container-apps"
tenant:
"Contoso"
embedding:
[0.012, -0.081, 0.224, ...]

The application can then:

  1. Receive a user’s question.
  2. Generate an embedding for the question.
  3. Submit the query vector to Redis.
  4. Search the vector index.
  5. Retrieve the closest documents.
  6. Apply metadata/security filtering.
  7. Send the retrieved content to the LLM.
  8. Generate a grounded response.

16. Vector Search and RAG

Vector indexing is especially important for Retrieval-Augmented Generation (RAG).

A typical RAG pipeline looks like this:

                DOCUMENT INGESTION
                       |
                       v
                 Split documents
                       |
                       v
                 Generate embeddings
                       |
                       v
             Store vectors + metadata
                       |
                       v
                Create vector index
                       |
                       |
             USER QUERY
                  |
                  v
           Generate query embedding
                  |
                  v
          Vector similarity search
                  |
                  v
          Apply metadata/security filters
                  |
                  v
             Retrieve top K
                  |
                  v
          Add retrieved context
                  |
                  v
                   LLM
                  |
                  v
              Final response

The vector database does not generate the final natural-language response.

Its role is primarily retrieval.


17. Why Metadata Filtering Is Important in RAG

Suppose a company has documents belonging to multiple departments:

HR
Finance
Engineering
Legal

A user asks:

“What is our reimbursement policy?”

A pure vector search could potentially retrieve semantically relevant documents from multiple departments.

Instead, the application can use metadata:

department = "Finance"

or, more importantly:

tenant_id = current_user.tenant_id

and possibly:

access_level <= current_user.access_level

This helps ensure that retrieval is both relevant and appropriately scoped.

For RAG, metadata can also provide information needed to identify the source of retrieved content.


18. Hybrid Search

Vector search does not necessarily need to operate alone.

Azure Managed Redis can combine vector search with other search/filter capabilities, including:

  • Numeric filters
  • Text filters
  • Geospatial filters
  • Prefix matching
  • Fuzzy matching
  • Boolean conditions

This enables hybrid retrieval.

For example:

Find products semantically similar to this product, but only return products where category = 'laptop' and price < 1500.

The vector component handles semantic similarity while the metadata/filter component constrains the candidate results.


19. Choosing FLAT or HNSW

For the exam, think about the decision this way:

Choose FLAT when:

  • The dataset is relatively small.
  • Exact similarity results are important.
  • Exhaustive comparison is acceptable.
  • Search latency is less critical.

Choose HNSW when:

  • The dataset is large.
  • Low latency is important.
  • Approximate results are acceptable.
  • High-throughput vector search is required.

Do not assume that HNSW is always better. It is a trade-off.


20. Important Exam Considerations

When answering AI-200 questions involving Azure Managed Redis vector indexing, pay attention to these details.

RediSearch must be available

Vector search depends on the RediSearch functionality.

Vector indexing is different from ordinary Redis keys

A Redis key/value operation retrieves a known key. Vector indexing enables similarity-based retrieval.

HNSW is approximate

It is designed to improve search performance and reduce computation compared with exhaustive search.

FLAT is exhaustive

It compares the query against the indexed vectors rather than navigating an approximate graph.

Metadata is valuable

Metadata enables filtering and allows applications to associate retrieved vectors with meaningful application information.

Embedding compatibility matters

The query embedding and indexed embeddings need to be compatible with the index configuration.

Vector search is not generation

Redis retrieves relevant information. An LLM can subsequently use that information to generate a response in a RAG architecture.


21. Common Exam Traps

Trap 1: “HNSW always provides exact results”

Incorrect.

HNSW is an approximate nearest-neighbor approach.


Trap 2: “FLAT is always the best option”

Incorrect.

FLAT can become computationally expensive as the number of vectors increases.


Trap 3: “Vector search replaces metadata filtering”

Incorrect.

Vector similarity determines semantic closeness. Metadata filters can constrain the search to the appropriate subset.


Trap 4: “The vector database generates the answer”

Incorrect.

The vector database retrieves relevant information. An LLM can use that retrieved information to generate the final response.


Trap 5: “Any embedding can be searched against any vector index”

Incorrect.

The embedding dimensions, representation, and similarity configuration need to be compatible.


Trap 6: “RediSearch can always be enabled later”

Incorrect for Azure Managed Redis provisioning.

Current Azure Managed Redis guidance states that required modules such as RediSearch need to be enabled when the instance is created.


22. AI-200 Exam Takeaways

Remember these concepts:

ConceptWhat to remember
EmbeddingNumerical representation of semantic meaning
VectorHigh-dimensional numerical representation
Vector indexMakes similarity searches efficient
RediSearchProvides vector search capabilities
FLATExact/exhaustive search
HNSWApproximate nearest-neighbor search
KNNRetrieves the K most similar vectors
ANNFaster approximate similarity search
COSINECommon metric for text embeddings
L2Euclidean distance
IPInner-product similarity
MetadataEnables filtering and contextual information
RAGRetrieve relevant content before LLM generation
HashRedis structure suitable for vector + fields
JSONRedis structure suitable for structured/nested vector records

Practice Exam Questions

Question 1

An AI application uses Azure Managed Redis to store 2 million document embeddings. The application requires very low-latency similarity searches and can tolerate a small reduction in recall in exchange for improved performance.

Which vector indexing strategy is most appropriate?

A. FLAT

B. HNSW

C. Hash-only retrieval

D. Key-based lookup

Answer: B

Explanation

HNSW is designed for approximate nearest-neighbor searches and is generally appropriate for larger datasets where low latency is important. It avoids exhaustive comparison with every vector and therefore can substantially reduce search work.

FLAT performs exhaustive searches and can become increasingly expensive as the number of vectors grows. A hash-only retrieval or normal key lookup cannot perform semantic vector similarity search.


Question 2

A development team has 5,000 product embeddings and requires exhaustive similarity comparisons because search accuracy is more important than minimizing computational cost.

Which indexing strategy should the team consider?

A. HNSW

B. FLAT

C. Boolean indexing

D. Prefix indexing

Answer: B

Explanation

FLAT performs an exhaustive comparison of the query vector against the indexed vectors. It is appropriate when the dataset is relatively small or when exhaustive accuracy is preferred.

HNSW is designed for approximate nearest-neighbor searches and trades some recall for performance.


Question 3

An application generates an embedding for a user’s question and wants to retrieve the five most semantically similar documents from Azure Managed Redis.

Which concept describes this operation?

A. Cache invalidation

B. Key-based lookup

C. K-nearest neighbors

D. Transaction processing

Answer: C

Explanation

K-nearest neighbors (KNN) retrieves the top K vectors that are closest to the query vector according to the configured similarity/distance metric.

With K = 5, the application requests the five nearest vectors.


Question 4

An organization stores document embeddings in Azure Managed Redis. Each document also contains a tenantId field. A RAG application must ensure that users retrieve documents only from their own tenant.

What is the primary purpose of the tenantId metadata?

A. Increasing the dimensionality of embeddings

B. Changing the embedding model

C. Replacing the vector index

D. Restricting vector retrieval to the appropriate tenant

Answer: D

Explanation

Metadata such as tenantId can be used to filter vector-search results so that retrieval is restricted to the appropriate tenant.

This is particularly important in multitenant AI and RAG applications where semantic similarity alone does not provide an authorization boundary.


Question 5

A team creates an Azure Managed Redis instance and later decides that it needs vector search. The instance was created without the required RediSearch functionality.

What should the team understand?

A. RediSearch must be enabled during instance provisioning

B. Vector search automatically becomes available when the first vector is stored

C. FLAT indexing eliminates the need for RediSearch

D. KNN automatically installs the required module

Answer: A

Explanation

Azure Managed Redis vector search requires RediSearch, and current Azure Managed Redis guidance states that the module must be enabled when the instance is created. Modules cannot simply be added to an existing instance afterward.


Question 6

An application uses text embeddings generated by an embedding model. Which consideration is most important when configuring the vector index?

A. The Redis key must contain the user’s password

B. The vector index must be compatible with the embedding dimensions and similarity configuration

C. Every embedding must be stored as plain text

D. The application must use FLAT regardless of dataset size

Answer: B

Explanation

The vector index needs to be configured consistently with the embeddings being generated. In particular, vector dimensions and the selected similarity metric need to be compatible with the embedding model and its vector representation.

Using an incompatible vector configuration can cause errors or poor search results.


Question 7

A RAG application retrieves documents from Azure Managed Redis using vector similarity search. What should happen after relevant documents are retrieved?

A. Redis automatically writes the final natural-language answer

B. The vector index generates a new embedding for every retrieved document

C. The retrieved content can be supplied to an LLM as grounding/context

D. The vectors are converted into relational database tables

Answer: C

Explanation

In a RAG architecture, vector search is the retrieval stage.

The application retrieves relevant content and supplies it as context to an LLM. The LLM then uses that context to generate the response.

The vector database does not itself generate the final natural-language answer.


Question 8

A team wants to find products semantically similar to a user’s query but only within the Laptops category.

Which approach best satisfies this requirement?

A. Perform only an exact key lookup

B. Delete all vectors outside the Laptops category

C. Use only the product title as the vector

D. Combine vector similarity search with a metadata filter

Answer: D

Explanation

Vector similarity identifies semantically similar products, while the metadata filter restricts results to the required category.

This is an example of combining vector retrieval with structured filtering.


Question 9

Which statement best describes the primary difference between FLAT and HNSW vector indexes?

A. FLAT performs exhaustive comparison, while HNSW uses an approximate graph-based approach

B. FLAT stores JSON while HNSW stores hashes

C. FLAT supports text only while HNSW supports vectors only

D. FLAT is used for metadata and HNSW is used for authentication

Answer: A

Explanation

The fundamental distinction is the search strategy.

FLAT performs exhaustive comparisons, while HNSW uses a graph-based approximate nearest-neighbor approach designed to improve search performance at scale.

The distinction is not based on whether the data is stored as hashes or JSON.


Question 10

An application uses Azure Managed Redis for vector similarity search. Which combination represents a valid vector-search design?

A. Store only Redis keys and perform exact string comparisons

B. Store embeddings, create a vector index, and query using a compatible similarity metric

C. Store embeddings only in application memory and use Redis for authentication

D. Store embeddings as passwords and use expiration to determine similarity

Answer: B

Explanation

A vector-search implementation requires embeddings to be stored, a compatible vector index to be created, and queries to use an appropriate similarity/distance configuration.

The other choices describe unrelated Redis capabilities and do not implement vector similarity search.


Final Exam Review

For “Implement vector indexing to enable similarity search”, the most important mental model is:

                 CONTENT
                    |
                    v
             Embedding model
                    |
                    v
              Vector embedding
                    |
                    v
       +-------------------------+
       |     Azure Managed       |
       |         Redis           |
       |                         |
       | Vector + metadata       |
       |         ↓               |
       |    Vector index         |
       |    /         \          |
       | FLAT          HNSW      |
       +-------------------------+
                    ^
                    |
             Query embedding
                    |
                    v
             Similarity search
                    |
                    v
              Top-K results
                    |
                    v
             RAG / Application

If you remember only a handful of things for the exam, remember these:

  1. RediSearch provides vector-search capabilities in Azure Managed Redis.
  2. FLAT = exhaustive/exact search.
  3. HNSW = approximate nearest-neighbor search optimized for performance.
  4. KNN returns the top K similar vectors.
  5. Cosine, L2, and inner product are important similarity/distance metrics.
  6. Vectors should be compatible with the embedding model and index configuration.
  7. Store metadata alongside vectors when applications need filtering or source information.
  8. Vector search retrieves information; an LLM can use that information for RAG generation.
  9. Vector search requires appropriate Redis provisioning, including RediSearch and supported configuration.
  10. The right index is determined by dataset size, latency requirements, accuracy/recall requirements, and resource considerations.

Go to the AI-200 Exam Prep Hub main page

Store and retrieve embeddings and execute vector similarity search for semantic retrieval (AI-200 Exam Prep)

This post is a part of the AI-200: Developing AI Cloud Solutions on Azure  Exam Prep Hub.
This topic falls under these sections:
Develop AI solutions by using Azure data management services (25–30%)
   --> Develop AI solutions by using Azure Cosmos DB for NoSQL
      --> Store and retrieve embeddings and execute vector similarity search for semantic retrieval


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Overview

Modern AI applications frequently need to retrieve information based on meaning, rather than simply matching exact words.

For example, suppose a user asks:

“What options are available for taking my dog on vacation?”

A traditional keyword search might look for documents containing the words dog, vacation, or travel. A semantic search system can instead identify documents discussing pet-friendly hotels, even if those documents never use the exact words in the user’s question.

This is accomplished using vector embeddings and vector similarity search.

Azure Cosmos DB for NoSQL provides integrated vector storage, indexing, and search capabilities. Applications can store embeddings directly alongside their source documents and use the VectorDistance() system function to find documents whose vectors are closest to a query vector.

For the AI-200 exam, you should understand:

  • What embeddings are
  • How embeddings are generated
  • How embeddings are stored in Cosmos DB
  • Vector embedding policies
  • Vector indexing policies
  • flat, quantizedFlat, and diskANN
  • The VectorDistance() function
  • k-nearest-neighbor (kNN) searches
  • Semantic retrieval
  • Filtering vector searches
  • Why TOP N is important
  • How vector search fits into RAG applications
  • Important vector-search limitations

1. What Is a Vector Embedding?

A vector embedding is a numerical representation of information.

An embedding model converts content such as:

  • Text
  • Documents
  • Images
  • Audio
  • Other supported data

into an array of numerical values.

For example, a simplified embedding might look like:

[0.12, -0.43, 0.87, 0.21, -0.09]

Real-world embedding models generally produce vectors with many more dimensions.

The important concept is that the position of an embedding in a high-dimensional mathematical space represents characteristics of the original content.

Content with similar meanings tends to have vectors that are close together.

For example:

"How can I travel with my dog?"

might be semantically close to:

"Hotels that allow pets"

even though the two sentences don’t contain the same words.


2. Embeddings Are Generated Outside Cosmos DB

Azure Cosmos DB stores and searches embeddings, but the embedding itself is typically generated by an embedding model.

For example, an application might use an embedding API such as an Azure OpenAI embedding model.

The general workflow is:

Source content
|
v
Embedding model
|
v
Vector embedding
|
v
Azure Cosmos DB

For a search request:

User query
|
v
Embedding model
|
v
Query embedding
|
v
Cosmos DB vector search
|
v
Most semantically similar documents

The stored document embedding and query embedding need to be compatible. In practice, applications should generate both using the same embedding model or a compatible embedding space.


3. Storing Embeddings in Cosmos DB

One of the major advantages of the integrated vector capabilities in Azure Cosmos DB for NoSQL is that the embedding can be stored alongside the original document.

For example:

{
"id": "doc001",
"category": "travel",
"title": "Pet-Friendly Hotels",
"content": "Hotels that welcome dogs and cats...",
"embedding": [
0.123,
-0.456,
0.789,
0.234
]
}

The application therefore doesn’t need to maintain a completely separate database containing the vector and another database containing the associated document.

The vector and its source data can be colocated.

This is particularly useful for AI applications because the application can retrieve both:

  1. The similarity result
  2. The original content needed to answer the user’s question

from the same Cosmos DB item.


4. What Is Semantic Retrieval?

Semantic retrieval means finding information based on its meaning rather than simply matching keywords.

Consider these two documents:

Document A

“Our resort provides accommodations for guests traveling with pets.”

Document B

“Our resort has a swimming pool and fitness center.”

A user searches:

“Where can I stay with my dog?”

Document A is likely to have a much closer semantic relationship to the query.

A vector search system identifies that relationship by comparing embeddings.

The basic process is:

  1. Generate embeddings for documents.
  2. Store the embeddings with the documents.
  3. Generate an embedding for the user’s query.
  4. Compare the query vector with document vectors.
  5. Rank documents according to similarity.
  6. Return the most relevant documents.

This is the foundation of many retrieval-augmented generation (RAG) applications.


5. Vector Search in Azure Cosmos DB

Azure Cosmos DB for NoSQL provides vector search capabilities through:

  • Vector embedding policies
  • Vector indexing policies
  • The VectorDistance() system function

Vector indexes improve vector-search efficiency by reducing latency and RU consumption compared with an unindexed/full-scan approach.

At a conceptual level:

                  Azure Cosmos DB
+---------------------+
| |
Document ---> | Original content |
| |
Embedding --> | Vector embedding |
| |
| Vector index |
| |
+----------+----------+
^
|
VectorDistance()
|
Query embedding

6. Vector Embedding Policies

A vector embedding policy describes the vector properties that Cosmos DB should treat as embeddings.

The policy can specify characteristics such as:

  • The vector property path
  • Number of dimensions
  • Distance function
  • Data type

The policy establishes how Cosmos DB should interpret the vector data.

A simplified conceptual configuration might look like:

{
"vectorEmbeddings": [
{
"path": "/embedding",
"dataType": "float32",
"dimensions": 1536,
"distanceFunction": "cosine"
}
]
}

The exact configuration supported depends on the current Cosmos DB capabilities and account configuration, but the important exam concept is:

The vector embedding policy describes the characteristics of the vector data.

Don’t confuse this with the vector indexing policy.


7. Vector Indexing Policies

The vector indexing policy determines how Cosmos DB indexes the vectors for vector search.

Azure Cosmos DB for NoSQL currently provides three primary vector index types:

IndexGeneral purpose
flatExact/brute-force vector search
quantizedFlatQuantized vector search for smaller/scoped workloads
diskANNEfficient approximate vector search for larger workloads

Choosing the appropriate index is an important architectural decision.


8. The flat Vector Index

The flat index performs a brute-force comparison of vectors.

Its major advantage is accuracy.

A flat search can provide exact nearest-neighbor results.

However, it has a maximum vector dimensionality of 505 dimensions, which makes it unsuitable for many modern high-dimensional embedding models.

It can be appropriate for relatively small vector datasets or situations where exact recall is particularly important.

Key exam concept

Flat = exact/brute-force search.


9. The quantizedFlat Vector Index

quantizedFlat compresses vectors before storing them in the vector index.

This can provide:

  • Lower latency
  • Higher throughput
  • Lower RU consumption

compared with an ordinary flat index.

The trade-off is that quantization can result in some loss of accuracy.

quantizedFlat supports vectors up to 4,096 dimensions.

Microsoft currently describes quantizedFlat as particularly appropriate for smaller or more narrowly scoped searches, with 50,000 vectors or fewer in the search scope being a useful general guideline—not an absolute limit. Actual workloads should be benchmarked.

Key exam concept

quantizedFlat = compressed/brute-force search with improved efficiency and a possible small accuracy trade-off.


10. The diskANN Vector Index

diskANN is designed for efficient approximate vector search, particularly for larger workloads.

It can provide:

  • Low latency
  • High throughput
  • Efficient RU consumption
  • High retrieval accuracy

It supports vectors up to 4,096 dimensions.

Microsoft describes DiskANN as generally the most performant option when the search scope exceeds approximately 50,000 vectors, although actual workload testing remains important.

Key exam concept

diskANN = approximate vector search optimized for larger datasets/search scopes.


11. Vector Index Comparison

For exam preparation, remember the following:

CharacteristicflatquantizedFlatdiskANN
Search typeExact/brute forceQuantized brute forceApproximate
Maximum dimensions5054,0964,096
AccuracyExactSlight possible lossHigh, configurable trade-offs
Large datasetsPoor fitBetter for smaller/scoped dataExcellent
Latency at scaleHigherModerateLower
RU efficiency at scaleLowerBetterBetter
Typical useSmall/exact searchesSmaller/scoped searchesLarge-scale vector search

12. Important Requirement: Vector Index Configuration

A vector index must be configured for the vector property that will be searched.

For example:

"vectorIndexes": [
{
"path": "/embedding",
"type": "diskANN"
}
]

The vector embedding policy and vector index work together.

A useful way to remember the distinction is:

Embedding policy = What is my vector?

Vector index = How should I search my vector?


13. Performing Vector Similarity Search

The primary Cosmos DB function used for vector similarity search is:

VectorDistance()

A basic query might look like:

SELECT TOP 10
c.title,
VectorDistance(c.embedding, @queryVector) AS SimilarityScore
FROM c
ORDER BY VectorDistance(c.embedding, @queryVector)

This query:

  1. Takes the query vector.
  2. Compares it with c.embedding.
  3. Calculates a vector distance.
  4. Sorts the results.
  5. Returns the top 10 results.

Microsoft specifically recommends using TOP N for vector searches because returning unnecessary results increases RU consumption and latency.


14. Understanding VectorDistance()

The function conceptually compares:

Document vector
|
v
VectorDistance()
^
|
Query vector

The result represents the distance between the vectors.

The exact interpretation depends on the configured distance function.

Common distance concepts include:

  • Cosine
  • Euclidean
  • Dot product

The application should use the distance function appropriate for the embedding model and workload.


15. Why Distance Matters

Suppose the query embedding is:

Q = [0.2, 0.3, 0.5]

and the database contains:

A = [0.2, 0.3, 0.5]
B = [0.8, 0.1, 0.2]
C = [-0.4, 0.7, 0.1]

The vector closest to the query is likely the most semantically similar.

The search engine can therefore rank results:

1. Document A
2. Document B
3. Document C

The application doesn’t have to know the meaning represented by every dimension.

The embedding model and vector-distance calculation handle that mathematical representation.


16. Always Use TOP N

A particularly important exam and practical-development point is:

Use TOP N with vector searches.

For example:

SELECT TOP 5
c.id,
c.title,
VectorDistance(c.embedding, @queryVector) AS score
FROM c
ORDER BY VectorDistance(c.embedding, @queryVector)

If the application only needs the five most relevant documents, there’s little reason to retrieve thousands of results.

Returning unnecessary results can increase:

  • RU consumption
  • Latency
  • Network traffic
  • Application processing

Microsoft explicitly recommends TOP N for vector searches.


17. Filtering Vector Searches

Vector search can also be combined with traditional query filtering.

For example:

SELECT TOP 10
c.title,
c.category,
VectorDistance(c.embedding, @queryVector) AS score
FROM c
WHERE c.category = "travel"
ORDER BY VectorDistance(c.embedding, @queryVector)

This means:

Find the most semantically similar documents within the travel category.

This is extremely useful in real applications.

Examples include:

  • Search products within a specific department.
  • Search documents belonging to a specific tenant.
  • Search hotel information within a particular region.
  • Search only documents that a user is authorized to access.

Azure Cosmos DB supports combining vector search with other query filtering capabilities.


18. Vector Search and Partitioning

Azure Cosmos DB applications should always consider partitioning.

For example, a multi-tenant application might have:

{
"id": "doc123",
"tenantId": "tenantA",
"title": "Company policy",
"embedding": [...]
}

A query could restrict retrieval to a particular tenant:

SELECT TOP 10
c.title,
VectorDistance(c.embedding, @queryVector) AS score
FROM c
WHERE c.tenantId = @tenantId
ORDER BY VectorDistance(c.embedding, @queryVector)

This can narrow the search scope and can be important for both performance and data isolation.


19. Semantic Search vs. Keyword Search

It is important to understand the difference.

Keyword search

A keyword search primarily asks:

Does this document contain the requested word or phrase?

For example:

"automobile"

might fail to find a document that only says:

"car"

Semantic search

Semantic search asks:

Which documents are mathematically closest in meaning to this query?

Therefore:

"automobile"

may retrieve documents discussing:

cars
vehicles
motor vehicles
transportation

depending on how the embedding model represents the concepts.


20. Hybrid Search

Vector search doesn’t have to replace traditional search.

Many AI applications use hybrid search, combining:

  • Keyword/full-text search
  • Vector similarity
  • Metadata filtering

For example:

User query
|
+--------------------+
| |
v v
Keyword search Vector search
| |
+---------+----------+
|
v
Combined ranking
|
v
Relevant results

This can provide better retrieval than relying exclusively on either keyword or vector search.

For example, vector search is good at identifying semantic similarity, while keyword search can be valuable when an exact product ID, name, or technical term matters.


21. Vector Search and RAG

One of the most important practical applications of vector search is Retrieval-Augmented Generation (RAG).

A simplified RAG architecture looks like this:

              DOCUMENT INGESTION
|
v
Generate embeddings
|
v
Azure Cosmos DB
+----------------------+
| Documents |
| Embeddings |
| Vector index |
+----------------------+

^
|
Vector retrieval
|
|
User question --> Generate embedding
|
v
Vector similarity search
|
v
Relevant documents
|
v
LLM
|
v
Generated answer

The vector database is responsible for retrieving relevant information.

The LLM is responsible for generating the final response using that retrieved information.

This distinction is important.

Vector search retrieves information; the LLM generates the response.


22. Keeping Embeddings Synchronized

Suppose the source document changes:

Original document
|
v
Embedding A

The document is updated:

Updated document
|
v
Embedding A <-- stale!

The embedding may no longer accurately represent the document.

Therefore, applications should have a mechanism to regenerate embeddings when source content changes.

Azure Cosmos DB’s change feed can be used as part of an architecture that detects changes and triggers embedding regeneration. The current AI-200 training material specifically includes change-feed processing for keeping embeddings synchronized.

A common architecture is:

Document updated
|
v
Cosmos DB change feed
|
v
Processing component
|
v
Generate new embedding
|
v
Update Cosmos DB item

23. Vector Index Limitations You Should Know

Several limitations are particularly relevant for the AI-200 exam.

Maximum dimensions

Current limits include:

  • flat: 505 dimensions
  • quantizedFlat: 4,096 dimensions
  • diskANN: 4,096 dimensions

Minimum vectors for quantizedFlat and diskANN

quantizedFlat and diskANN require at least 1,000 vectors for indexed vector searching. If fewer than 1,000 vectors are present, a full scan can be performed instead.

Shared throughput

Vector indexing and search currently aren’t supported on accounts using shared throughput.

Vector policy changes

Vector embedding and vector indexing policy settings aren’t simply modified in place. Depending on the specific configuration, the existing policy/index must be removed and recreated, or a new container may be required.

Vector search cannot simply be disabled

Once vector indexing and search are enabled on a container, it cannot simply be disabled.


24. Common Exam Traps

Trap 1: Confusing embeddings with indexes

An embedding is the numerical representation of content.

An index is the structure used to efficiently search those vectors.


Trap 2: Thinking Cosmos DB generates the embedding

Cosmos DB stores and searches embeddings.

An embedding model, such as an embedding API, generates the embedding.


Trap 3: Assuming diskANN is exact

diskANN is an approximate nearest-neighbor approach.

It is designed to provide excellent performance while maintaining high retrieval quality.


Trap 4: Assuming quantizedFlat is exact

Quantization can introduce a small loss of accuracy.


Trap 5: Forgetting TOP N

A vector search should generally use TOP N to avoid unnecessarily expensive retrieval.


Trap 6: Using flat for a 1,536-dimensional embedding

The current flat limit is 505 dimensions.

A 1,536-dimensional embedding requires a vector index type supporting that dimensionality, such as quantizedFlat or diskANN.


Trap 7: Treating vector search as keyword search

Vector search is based on semantic similarity, not exact text matching.


25. Exam-Focused Summary

For AI-200, remember this chain:

Source data
|
v
Embedding model
|
v
Vector embedding
|
v
Cosmos DB document
|
v
Vector embedding policy
|
v
Vector index
|
v
VectorDistance()
|
v
TOP N results
|
v
Semantic retrieval

The most important concepts are:

ConceptRemember
EmbeddingNumerical representation of content
Vector storeStores and retrieves embeddings
Vector embedding policyDefines characteristics of vectors
Vector indexMakes vector searches more efficient
flatExact/brute-force; max 505 dimensions
quantizedFlatQuantized; max 4,096 dimensions
diskANNApproximate, efficient large-scale search; max 4,096 dimensions
VectorDistance()Performs vector distance calculation
TOP NLimits results and helps control RU/latency
Semantic searchFinds content by meaning
Metadata filteringNarrows the search space
Hybrid searchCombines lexical and vector retrieval
RAGUses retrieved context to augment LLM generation
Change feedCan trigger embedding refresh when data changes

Practice Exam Questions

Question 1

An AI application stores product descriptions in Azure Cosmos DB for NoSQL. The application needs to find products that are semantically similar to a user’s natural-language query.

What should the application do?

A. Store the product descriptions as strings and use CONTAINS() exclusively.

B. Generate embeddings for the product descriptions and store the vectors with the documents.

C. Convert each product description to a partition key.

D. Store each word as a separate Cosmos DB item.

Answer: B

Explanation:
Semantic retrieval requires converting content into vector embeddings. The embeddings can then be stored alongside the original documents in Cosmos DB and compared with a query embedding. Keyword functions such as CONTAINS() don’t provide semantic similarity.


Question 2

An application uses a 1,536-dimensional embedding model and needs an efficient vector index for a large production dataset.

Which vector index type is the most appropriate choice?

A. flat

B. hash

C. range

D. diskANN

Answer: D

Explanation:
diskANN supports vectors up to 4,096 dimensions and is designed for efficient approximate vector search at larger scales. flat is limited to 505 dimensions and therefore cannot index a 1,536-dimensional vector.


Question 3

An application needs the five most semantically similar documents to a query vector.

Which query pattern should be used?

A.

SELECT *
FROM c
ORDER BY VectorDistance(c.embedding, @queryVector)

B.

SELECT TOP 5 *
FROM c
ORDER BY c.embedding

C.

SELECT TOP 5 *
FROM c
ORDER BY VectorDistance(c.embedding, @queryVector)

D.

SELECT *
FROM c
WHERE c.embedding = @queryVector

Answer: C

Explanation:
VectorDistance() calculates the distance between the stored embedding and query vector. TOP 5 limits the results to the five most relevant documents and helps avoid unnecessary RU consumption and latency.


Question 4

Which statement best describes the purpose of a vector embedding?

A. It is a Cosmos DB authentication token.

B. It is the partition key automatically generated by Cosmos DB.

C. It is a numerical representation of the semantic characteristics of content.

D. It is an index containing document metadata.

Answer: C

Explanation:
An embedding is a numerical representation generated by an embedding model. Semantically related content tends to produce vectors that are close together in vector space.


Question 5

A company has a relatively small vector search workload and wants to use a vector index that compresses vectors to improve efficiency while accepting a possible small loss in accuracy.

Which index should it consider?

A. flat

B. quantizedFlat

C. diskANN

D. NoSQL range indexing

Answer: B

Explanation:
quantizedFlat compresses vectors before indexing. This can improve latency, throughput, and RU efficiency compared with flat, at the potential cost of some accuracy. It is particularly suited to smaller or more narrowly scoped searches.


Question 6

An application has documents containing both an embedding and a category property. It needs to find the most semantically similar documents, but only within the "finance" category.

Which approach is appropriate?

A. Perform a vector search without filtering and discard non-finance results afterward.

B. Store each category in a separate Cosmos DB account.

C. Use VectorDistance() together with a WHERE filter for the category.

D. Replace the embeddings with category names.

Answer: C

Explanation:
Vector search can be combined with traditional Cosmos DB query filters. The application can use a WHERE clause to restrict the search to documents matching the required metadata.


Question 7

A developer changes the text of a document but continues using the embedding that was generated from the old version.

What is the primary problem?

A. The partition key automatically changes.

B. The vector index is deleted.

C. The document becomes unreadable.

D. The embedding may no longer accurately represent the document.

Answer: D

Explanation:
An embedding represents the content used to generate it. If the source content changes substantially, the old embedding can become stale. Applications can use mechanisms such as the Cosmos DB change feed to detect changes and trigger embedding regeneration.


Question 8

Which statement correctly describes the flat vector index in Azure Cosmos DB for NoSQL?

A. It performs exact/brute-force vector search and supports vectors up to 505 dimensions.

B. It performs approximate DiskANN search and supports 4,096 dimensions.

C. It compresses vectors and always produces approximate results.

D. It is used only for keyword searches.

Answer: A

Explanation:
The flat index performs brute-force vector search and can provide exact nearest-neighbor results. Its current maximum vector dimensionality is 505.


Question 9

An AI application uses vector search as part of a RAG architecture.

What is the primary purpose of the vector search portion of the architecture?

A. Generate the final natural-language response.

B. Retrieve content that is semantically relevant to the user’s query.

C. Train the large language model.

D. Replace the embedding model.

Answer: B

Explanation:
Vector search retrieves relevant information based on semantic similarity. The retrieved content can then be supplied to an LLM as context for generating the final answer. Vector retrieval and LLM generation are separate responsibilities.


Question 10

A developer creates a vector search query that returns every matching document instead of limiting the result set. The application only needs the top 10 results.

What should the developer change?

A. Remove the vector index.

B. Increase the embedding dimensionality.

C. Add a TOP 10 clause to the query.

D. Replace VectorDistance() with CONTAINS().

Answer: C

Explanation:
Vector searches should generally use TOP N to limit the number of returned results. Returning more results than the application needs can increase RU consumption and latency.


Final Exam Takeaways

If you remember only a handful of things from this topic, remember these:

  1. Embeddings represent the semantic characteristics of content numerically.
  2. An embedding model generates the embedding; Cosmos DB stores and searches it.
  3. Embeddings can be stored alongside the original Cosmos DB document.
  4. VectorDistance() is the key function for vector similarity searches.
  5. Use TOP N when performing vector retrieval.
  6. flat provides exact/brute-force search but is limited to 505 dimensions.
  7. quantizedFlat provides a more efficient quantized approach for smaller/scoped searches.
  8. diskANN is designed for efficient approximate search at larger scales and supports up to 4,096 dimensions.
  9. Vector search can be combined with metadata filters and hybrid search.
  10. Vector retrieval is a fundamental building block for RAG applications.
  11. When source content changes, embeddings may need to be regenerated.
  12. For AI-200 scenario questions, pay close attention to the dataset size, vector dimensionality, accuracy requirements, RU consumption, and latency requirements when selecting a vector index.

Go to the AI-200 Exam Prep Hub main page