Search functionality is an important part of modern applications. E-commerce platforms use it to find products, support portals use it to locate troubleshooting guides, and AI applications use it to retrieve relevant information before generating an answer.
However, retrieving documents that contain matching keywords does not always mean retrieving the most useful documents. A user searching for "how to protect customer information when an application is compromised" may receive documents containing the words "customer" and "application" even when those documents do not explain security practices or incident response.
Traditional keyword search and vector search solve different parts of this problem. Keyword search finds documents based on matching terms, while vector search identifies documents with similar semantic meaning. Both approaches can return useful candidates, but their initial ranking may not always reflect the user's complete intent.
Azure Cosmos DB semantic reranking addresses this problem by adding an AI-powered ranking step after retrieval. It evaluates candidate documents against the user's query or context and reorders them according to semantic relevance.
This capability is useful for search applications, conversational experiences, and retrieval-augmented generation (RAG) systems. It allows developers to improve the quality of the results presented to users without replacing their existing retrieval strategy.
This article explains how semantic reranking works in Azure Cosmos DB, how to configure it, how to implement it using C# and the Azure SDKs, and how to evaluate it in production applications.
Understanding Semantic Reranking
Semantic reranking is a process in which an AI model evaluates an existing set of search results and assigns each document a relevance score based on a query or context.
Unlike a normal search operation, reranking does not retrieve additional documents from the database. It works with the candidate documents returned by an earlier retrieval operation.
Consider an online learning platform with thousands of technical articles. A user searches for:
How can I improve API security in an ASP.NET Core application?
An initial search operation might return these documents:
Document | Initial relevance |
|---|
Building REST APIs with ASP.NET Core | High |
Securing JWT Authentication in Web APIs | Medium |
Improving SQL Query Performance | Medium |
Implementing Rate Limiting in ASP.NET Core | Medium |
Introduction to ASP.NET Core Middleware | Medium |
The first result may contain many matching terms, but the JWT and rate-limiting articles may provide more useful information for the user's actual question.
A semantic reranker evaluates the candidate documents using the complete query context. It can move the authentication and rate-limiting articles higher when their content better matches the user's intent.
The process can be represented as follows:
The application receives a search query.
Azure Cosmos DB retrieves candidate documents using full-text search, vector search, hybrid search, or another query.
The application prepares the candidate documents for reranking.
The semantic reranker evaluates the documents against the user's query or context.
The reranker returns relevance scores and document indexes.
The application uses those indexes to reconstruct the final ordered results.
The important distinction is that retrieval determines which documents are considered, while reranking determines their final order.
Why Use Semantic Reranking in Azure Cosmos DB?
Azure Cosmos DB supports different retrieval approaches for applications that store structured and unstructured information. Depending on the workload, developers can use full-text search, vector search, hybrid search, or regular database queries.
Each retrieval method has different strengths.
Retrieval approach | How it works | Common limitation |
|---|
Keyword search | Finds documents containing matching terms | May miss relevant documents that use different words |
Full-text search | Uses text processing and relevance scoring | Initial ranking may not fully understand the user's intent |
Vector search | Compares vector representations of content | Similarity does not always mean the document answers the query |
Hybrid search | Combines multiple retrieval signals | The combined ranking may still need additional refinement |
Semantic reranking | Evaluates retrieved candidates against the query context | Adds inference latency and a separate processing step |
Semantic reranking is particularly useful when the order of the first few results matters.
For example, a RAG application may retrieve 30 documents but send only the top five to a language model. If the most relevant document appears at position 15, the application may exclude important information from the final response.
Reranking can improve the quality of the selected documents by moving more relevant candidates toward the top.
Azure Cosmos DB semantic reranking uses the Microsoft AI Semantic Ranker model, which is also used by Azure AI Search's Semantic Ranker.
The capability became generally available in November 2026. It is available for Azure Cosmos DB for NoSQL and works with candidate results retrieved from supported query approaches.
Understanding the Semantic Reranking Architecture
Semantic reranking introduces an inference step into the existing search architecture.
The application uses the Azure Cosmos DB SDK to retrieve documents. It then sends the selected candidate content and the query context to the semantic reranker inference endpoint using the Azure Data AI SDK.
The architecture contains three main components.
Azure Cosmos DB retrieval layer
This layer retrieves the initial candidate documents. The application can use full-text search, vector search, hybrid search, or another supported query.
For example, a full-text query can retrieve articles containing terms related to API security. The application can limit the candidate set to a manageable number before sending the documents for reranking.
Semantic reranker inference endpoint
The inference endpoint receives the query context and serialized candidate documents. The AI model evaluates the relationship between the query and each candidate.
The service returns relevance scores, document indexes, and optional diagnostic information.
The inference endpoint is a separate resource. It is not the same as the Azure Cosmos DB document endpoint.
Application result-processing layer
The application uses the returned document indexes to identify the original database records. It then constructs the final search response in the new order.
Keeping the original documents in application memory is useful because the reranker can return indexes and scores without returning the complete document content.
This architecture also makes it possible to integrate reranking into an existing search service without redesigning the database.
Prerequisites and Configuration
Before implementing semantic reranking, prepare the required Azure resources and application dependencies.
You need:
An Azure Cosmos DB for NoSQL account.
An existing database and container containing searchable documents.
A retrieval strategy such as full-text search, vector search, or hybrid search.
A semantic reranker inference endpoint.
Microsoft Entra ID authentication.
Appropriate permissions for both database retrieval and inference.
A supported Azure Cosmos DB SDK and Azure Data AI SDK.
For a full-text search example, the documents can contain fields such as id, title, and text. Configure the full-text policy and index for the text field before executing the search query.
Enable semantic reranking
You can enable semantic reranking through the Azure portal.
Open the Azure Cosmos DB account in the Azure portal.
Find Semantic Reranker in the account's resource menu.
Enable the feature.
Review the companion inference resource and wait until its endpoint becomes available.
Review the identities listed under Reranker Permissions.
Grant the required permissions to the application identity.
The integration creates or uses a companion inference account. The endpoint provided by that resource is used for reranking.
For automated environments, the resource can also be configured through Azure management tools and deployment scripts.
Configure Microsoft Entra ID permissions
Semantic reranking requires two independent permissions.
The application needs permission to read the documents from Azure Cosmos DB. It also needs permission to call the semantic reranker inference endpoint.
These permissions are separate. Access to the database does not automatically grant access to the inference service.
For local development, you can use DefaultAzureCredential to authenticate through an available Microsoft Entra identity.
For production applications, assign the required permissions to the application's managed identity rather than storing account keys or credentials in source code.
Use the least-privilege principle. Grant database read access at the required container scope and inference access at the inference resource scope.
Implementing Semantic Reranking With C#
The Azure Cosmos DB SDK retrieves the candidate documents, while the Azure Data AI SDK performs the reranking operation.
The following example uses .NET and C# to retrieve movie records through full-text search and then reorder them using semantic reranking.
Install the required packages
Create a console application:
dotnet new console --name SemanticRerankerSample --framework net8.0
cd SemanticRerankerSample
Install the required packages:
dotnet add package Microsoft.Azure.Cosmos
dotnet add package Azure.Data.AI
Use compatible package versions for your target framework. The current Microsoft implementation examples use the Azure Cosmos DB .NET SDK and the Azure Data AI SDK.
Configure application settings
Keep the database and inference endpoints outside the application source code.
For local development, configure the following environment variables:
COSMOS_DB_ENDPOINT=https://your-account.documents.azure.com:443/
COSMOS_DB_DATABASE=MoviesDatabase
COSMOS_DB_CONTAINER=Movies
INFERENCE_ENDPOINT=https://your-inference-endpoint
RERANKER_MODEL=aisearch-reranker
The values are examples. Use the actual endpoint and model identifier provided by your Azure environment.
Retrieve candidate documents
The first step is to execute a normal search query against Azure Cosmos DB.
The following query uses full-text search to retrieve movie records related to space or adventure:
const string sql = """
SELECT TOP 10 c.id, c.title, c.text
FROM c
WHERE FullTextContainsAny(
c.text,
"space",
"adventure"
)
ORDER BY RANK FullTextScore(
c.text,
"space",
"adventure"
)
""";
The query retrieves up to ten candidate documents and initially orders them using the full-text relevance score.
The candidate limit is an application decision. It should be large enough to provide useful alternatives but small enough to keep inference requests manageable.
Send candidates to the semantic reranker
The next step is to serialize the fields that should be evaluated and send them to the inference endpoint.
using Azure.Data.AI;
using Azure.Identity;
using System.Text.Json;
string context =
"Space adventures about friendship and teamwork.";
var documents = candidates.Select(movie =>
JsonSerializer.Serialize(new
{
title = movie.Title,
text = movie.Text
}));
var inference = new InferenceClient(
new Uri(inferenceEndpoint),
new DefaultAzureCredential());
var request = new SemanticRerankingOptions(
context,
documents)
{
Model = "aisearch-reranker",
DocumentType = SemanticRerankingDocumentType.Json,
TargetPaths = { "title", "text" },
ReturnDocuments = false,
TopK = 3,
Sort = true,
ReturnSentenceScore = true
};
Azure.Response<SemanticRerankingResult> response =
await inference.SemanticRerankAsync(request);
The context value describes the user's intent. The documents collection contains the candidate content to evaluate.
The DocumentType property identifies the candidate format as JSON. The TargetPaths collection specifies which JSON fields the model should consider.
The TopK property limits the number of ranked results returned. In this example, the application requests the top three documents.
The ReturnDocuments property is set to false because the application already has the original candidate documents. This avoids returning duplicate document content when indexes are sufficient to reconstruct the results.
Reconstruct the final search results
The reranker returns scores containing the index of each document in the submitted candidate collection.
The index is zero-based. Therefore, the application must use it to retrieve the corresponding original document.
var finalResults = new List<RankedMovie>();
foreach (var score in response.Value.Scores)
{
int index = score.Index!.Value;
var originalDocument = candidates[index];
finalResults.Add(new RankedMovie
{
Id = originalDocument.Id,
Title = originalDocument.Title,
Text = originalDocument.Text,
RelevanceScore = score.Score!.Value
});
}
A simple result model can look like this:
public class RankedMovie
{
public string Id { get; set; } = "";
public string Title { get; set; } = "";
public string Text { get; set; } = "";
public float RelevanceScore { get; set; }
}
The application can now return the reranked documents to the user or pass them to a language model as context for a RAG workflow.
For production code, validate every returned index before accessing the candidate collection. Also check for missing or invalid scores and handle cases where fewer results are returned than requested.
The example demonstrates the main API interaction. A complete application should also include the database retrieval, environment configuration, authentication setup, retry policy, and validation shown in the current Azure documentation.
Using Semantic Reranking With Python
Python applications can use the Azure Cosmos DB Python SDK for retrieval and the Azure Data AI SDK for reranking.
Install the required packages:
pip install azure-cosmos azure-identity azure-data-ai
The following example shows the main reranking operation:
import json
from azure.data.ai import InferenceClient
from azure.identity import DefaultAzureCredential
context = (
"Space adventures about friendship and teamwork."
)
documents = [
json.dumps({
"title": item["title"],
"text": item["text"]
})
for item in candidates
]
request = {
"query": context,
"documents": documents,
"model": "aisearch-reranker",
"documentType": "json",
"targetPaths": "title,text",
"returnDocuments": False,
"topK": 3,
"sort": True,
"returnSentenceScore": True
}
with InferenceClient(
inference_endpoint,
credential=DefaultAzureCredential()
) as inference:
response = inference.semantic_rerank(request)
results = []
for score in response["scores"]:
index = score["index"]
results.append({
"id": candidates[index]["id"],
"title": candidates[index]["title"],
"text": candidates[index]["text"],
"score": score["score"]
})
print(json.dumps(results, indent=2))
The example assumes that candidates already contains documents retrieved from Azure Cosmos DB and that inference_endpoint is configured.
Python dictionaries use the JSON-style parameter names shown in the request. When using typed Python models, use the corresponding snake_case property names instead.
Understanding Reranker Parameters and Scores
The semantic reranker provides several parameters that control how candidate documents are evaluated and returned.
Parameter | Purpose |
|---|
query or rerankContext
| Describes the user's search intent or task context |
documents
| Contains the candidate documents to evaluate |
model
| Identifies the configured reranking model |
documentType
| Identifies the candidate format, such as JSON or text |
targetPaths
| Specifies JSON fields that should be considered |
topK
| Limits the number of ranked results returned |
sort
| Controls whether results are ordered by relevance score |
returnDocuments
| Controls whether original documents are included in the response |
returnSentenceScore
| Requests optional sentence-level relevance information |
Relevance scores
The reranker returns a relevance score between 0 and 1. A higher score indicates that the document is more relevant to the supplied context.
For example:
Document | Reranker score |
|---|
Securing ASP.NET Core Web APIs | 0.94 |
Implementing JWT Authentication | 0.89 |
API Rate Limiting Techniques | 0.84 |
Introduction to ASP.NET Core | 0.52 |
These values are illustrative. Actual scores depend on the query, candidate content, and model response.
Do not treat a score as a guaranteed probability that a document is correct. It is a relevance signal that can help order results and support application-level filtering.
Document indexes
Each returned score includes a document index. This index refers to the position of the original document in the submitted candidate list.
For example, if the reranker returns index 4, the application should retrieve the fifth document from the original list.
This is why candidate documents and their identifiers should be retained until the reranking operation is complete.
Sentence-level scores
The service can also return optional sentence-level scores. These identify up to two of the highest-scoring sentences within each returned document.
Sentence scores can help developers understand which parts of a document contributed to its relevance. They are not scores for every sentence, and their indexes should not be treated as character positions or JSON field identifiers.
Integrating Semantic Reranking Into a RAG Pipeline
Retrieval-augmented generation combines database retrieval with language model generation. Instead of asking a language model to answer only from its training knowledge, the application retrieves relevant documents and supplies them as context.
Semantic reranking can improve the retrieval stage of this process.
Consider a customer-support assistant that answers questions about an organization's technical documentation.
A user asks:
What should I do when an API request repeatedly returns 401 errors?
The application can retrieve documents using a combination of keyword and vector search. The initial results might include authentication guides, API troubleshooting articles, and general HTTP documentation.
The reranker then evaluates these candidates against the complete question and moves the most useful authentication and troubleshooting documents toward the top.
The language model receives the final selected documents and generates an answer using that context.
A practical RAG pipeline looks like this:
User question
|
v
Query processing
|
v
Azure Cosmos DB retrieval
(Vector / Full-text / Hybrid)
|
v
Candidate documents
|
v
Semantic reranking
|
v
Top relevant documents
|
v
Language model
|
v
Generated response
The reranker improves candidate ordering, but it does not generate the final answer. It also does not verify whether a document is factually correct. The application still needs appropriate source validation, access controls, and answer-grounding practices.
Performance, Latency, and Cost Considerations
Semantic reranking introduces an additional network call and model inference time. This means the final search response may take longer than a retrieval-only query.
For applications that need very fast responses, this additional latency should be measured carefully.
The following practices can help control performance and cost:
Limit the candidate set
Do not send every document from the database to the reranker. Retrieve a relevant candidate set first and rerank only those documents.
The current service supports up to 50 documents per rerank call. A single context-document pair supports up to 2,048 tokens.
These limits make candidate selection and document preparation important parts of the implementation.
Send only useful document fields
A database item may contain many fields that do not help determine relevance. Sending identifiers, internal metadata, timestamps, and unrelated values can increase the amount of information processed without improving ranking.
For JSON documents, use targetPaths to identify the fields that should be considered. Also serialize only the fields needed by the reranker.
Avoid unnecessary reranking
Not every search requires semantic reranking. A query for an exact product ID or transaction number may already produce a clear result through a normal database query.
Use reranking when understanding the meaning and context of a query can improve the result order.
Monitor inference diagnostics
The response can include information about preprocessing latency, inference latency, postprocessing latency, token usage, and model identity.
These values help developers understand the inference service's behavior. They should not be confused with the complete end-to-end request time or Azure Cosmos DB request-unit consumption.
The service also provides pricing information for rerank calls. At the documented rate of $1 per 1,000 calls, application teams should estimate expected request volume and verify the applicable regional pricing before production deployment.
Error Handling and Troubleshooting
A production implementation should handle errors from both Azure Cosmos DB and the inference endpoint.
These are separate services with separate authentication and retry behavior.
Problem | Possible reason | Recommended action |
|---|
HTTP 401 or 403 | Missing or incorrect identity permissions | Verify Microsoft Entra authentication and role assignments |
Inference endpoint unavailable | Resource provisioning is incomplete | Check the inference resource provisioning state |
HTTP 429 | Service throttling or request limits | Respect the service-provided retry delay |
Invalid JSON target paths | Target fields do not match serialized documents | Verify the JSON structure and field paths |
Missing document index | Unexpected or incomplete response | Validate the response before mapping documents |
Higher search latency | Additional inference processing | Reduce unnecessary candidates and measure each stage |
No relevance improvement | Poor candidate retrieval or unsuitable context | Review retrieval quality and query wording |
Handle retries correctly
The inference client has its own retry policy, separate from the Azure Cosmos DB client used for retrieval.
Use the SDK's retry behavior and respect server-provided retry information such as Retry-After, retry-after-ms, or x-ms-retry-after-ms when available.
Avoid creating multiple nested retry loops around the same request. They can increase total response time and create unnecessary traffic.
For authorization failures, investigate the endpoint, identity, and role assignments instead of repeatedly retrying the request.
Preserve original candidate documents
The reranker returns indexes that map to the original candidate collection. If the application changes the order of that collection between submission and response processing, it can associate a score with the wrong document.
Keep the candidate collection unchanged until the response has been processed. Validate that every returned index is within the original collection's range and that the same index is not returned unexpectedly more than once.
Common Mistakes to Avoid
Expecting reranking to retrieve missing documents
Reranking only evaluates the documents supplied to it. If the initial search does not retrieve a relevant document, the reranker cannot move that document to the top.
Improve the retrieval stage before increasing the candidate count.
Sending too many candidate documents
A large candidate set increases inference work and may add unnecessary latency. Retrieve a focused set of candidates based on the application's search requirements.
Sending complete database records
Do not send every field from a database item. Select meaningful content and metadata that help the model understand the document.
Treating relevance scores as probabilities
A score of 0.90 does not mean there is a 90% probability that the document is correct. Use scores for ranking and evaluation, not as a guarantee of factual accuracy.
Ignoring identity permissions
Database access and inference access are separate. A working Cosmos DB query does not prove that the application can call the reranker.
Ignoring latency
A better result order is useful only when the improvement justifies the additional processing time. Measure the complete user request, not only the model's inference duration.
Using reranking for every query
Exact lookups and simple filters may not benefit from semantic processing. Apply reranking selectively based on the query type and expected value.
Best Practices for Production Applications
A reliable semantic search implementation requires attention to retrieval quality, document preparation, security, and monitoring.
Use full-text, vector, or hybrid retrieval to generate an initial candidate set.
Evaluate retrieval quality before introducing reranking.
Keep candidate document counts within the supported service limit.
Send only relevant fields to the inference endpoint.
Use meaningful query context rather than short or ambiguous search terms.
Use targetPaths when sending JSON documents.
Preserve the original candidate collection for reliable index mapping.
Validate indexes and scores before constructing final results.
Use Microsoft Entra ID and managed identities for production authentication.
Grant database and inference permissions separately.
Use the SDK retry policy and respect server-provided retry delays.
Monitor inference latency, token usage, request failures, and end-to-end search latency.
Compare relevance before and after reranking using representative test queries.
Avoid reranking exact-match queries that do not need semantic interpretation.
Review document content before sending it to an external inference endpoint, especially when it contains confidential or personal information.
Advantages and Disadvantages of Semantic Reranking
Advantages | Disadvantages |
|---|
Improves the ordering of retrieved documents based on query meaning | Adds network and inference latency |
Works with candidates from different retrieval approaches | Cannot recover documents missing from the candidate set |
Useful for RAG and conversational search applications | Requires an additional inference resource |
Provides relevance scores for result evaluation | Scores require careful interpretation |
Supports structured JSON and plain-text candidate documents | Requires correct document preparation and field selection |
Integrates with supported Azure SDKs | Introduces additional permissions and operational monitoring |
Summary
Azure Cosmos DB semantic reranking adds an AI-powered ranking step to existing search and retrieval workflows. It evaluates candidate documents against a user's query or context and reorders them according to semantic relevance.
The feature can work with results retrieved through full-text search, vector search, hybrid search, or other queries. This makes it useful for applications that need better search results without replacing their existing database or retrieval architecture.
For .NET and Python applications, the implementation involves retrieving candidates through the Azure Cosmos DB SDK and sending them to the semantic reranker through the Azure Data AI SDK. The application then uses the returned document indexes and relevance scores to construct the final result set.
The most important production considerations are candidate quality, document size, inference latency, identity permissions, and retry handling. Semantic reranking should complement a good retrieval strategy rather than replace it. When these pieces are designed together, it can improve search experiences and provide more relevant context to AI-powered applications.
Join the conversation! Your thoughts help the community grow.