Search functionality is an important part of modern applications. E-commerce platforms use it to find products, content platforms search articles, and customer support applications retrieve relevant answers from knowledge bases. However, returning documents that contain matching keywords is not enough. Users expect the most relevant results to appear at the top.
Consider a user searching for "best ways to improve database query performance." A basic keyword search may return every document containing the words "database" or "performance." Some documents may mention these terms only once, while others may explain query optimization, indexing, execution plans, and database performance in detail.
How can a search engine decide which document is more relevant?
Azure Cosmos DB for NoSQL addresses this problem through full-text search and the BM25 relevance-scoring algorithm. BM25 evaluates how well a document matches a search query by considering term frequency, inverse document frequency, and document length.
Azure Cosmos DB uses BM25 through the FullTextScore system function. Developers can use it to rank search results and, with the recently introduced score projection capability, inspect the actual relevance score returned for each document.
This article explains how BM25 works, how Azure Cosmos DB uses it, how to configure full-text indexing, and how to implement relevance-based queries using practical examples.
What Is BM25?
BM25 stands for Best Matching 25. It is a ranking algorithm used in information retrieval systems to estimate how relevant a document is to a search query.
It belongs to the family of probabilistic information retrieval algorithms. Instead of simply counting matching words, BM25 considers several factors that help distinguish useful documents from documents with weak keyword matches.
The three main factors are:
- Term Frequency (TF): How often a search term appears in a document.
- Inverse Document Frequency (IDF): How rare or informative the search term is across the document collection.
- Document Length: How long the document is compared with the average document length.
These factors work together to produce a relevance score. Documents with higher scores are generally considered more relevant to the query.
For example, imagine an application that stores 10,000 technical articles. A user searches for "Azure Cosmos DB indexing."
The word "Azure" may appear in thousands of articles, while "indexing" may appear in a smaller number of documents. BM25 considers the frequency of these terms across the collection and their occurrences within individual documents.
An article that explains Cosmos DB indexing in detail may receive a higher score than a general Azure article that only mentions indexing once.
Understanding the Three Factors of BM25
To understand BM25 scoring, it is useful to examine how each factor contributes to the final relevance score.
Term Frequency
Term frequency measures how often a search term appears in a document.
Suppose a user searches for:
Azure Cosmos DB indexing
Consider these two documents:
Document A:
Azure Cosmos DB supports indexing policies.
Indexing policies help control which properties
are included in the index.
Document B:
Azure Cosmos DB is a distributed database service.
It supports multiple database capabilities.
Document A contains more direct references to indexing and provides information related to the search. It is therefore likely to receive a stronger contribution from the matching terms.
However, BM25 does not increase a document's score indefinitely just because a word appears many times. Its term-frequency component uses saturation. This means that the benefit of additional occurrences becomes smaller as the frequency increases.
This behavior prevents a document from dominating search results simply by repeating the same keyword.
Inverse Document Frequency
Inverse Document Frequency measures how informative a term is across the entire document collection.
A common word that appears in nearly every document provides little help in distinguishing one document from another. A rare term can provide a stronger relevance signal.
For example, consider a collection of technical articles containing these terms:
| Search term | Occurrence across documents | General importance |
|---|
| Database | Very common | Lower distinguishing value |
| Azure | Common | Moderate distinguishing value |
| Cosmos DB | Less common | Higher distinguishing value |
| Change Feed | Relatively rare | Potentially high distinguishing value |
The exact contribution depends on the collection's statistics and the algorithm's implementation.
In simple terms, IDF helps the search engine understand that some matching words are more useful than others.
Document Length
Document length is another important factor.
Consider two documents:
- Document A contains 150 words and mentions the search term 5 times.
- Document B contains 5,000 words and mentions the same term 5 times.
A basic frequency-based search might treat both documents similarly because they contain the same number of occurrences.
BM25 considers the document length relative to the average length of documents in the collection. This helps prevent long documents from receiving an unfair advantage simply because they contain more text.
A shorter document with focused information may therefore rank higher than a much longer document with only occasional references to the search terms.
How the BM25 Formula Works
The BM25 algorithm combines the three factors into a mathematical relevance score.
A commonly used form of the BM25 formula is:
[
BM25(q,d)=
\sum_{t \in q}
IDF(t)
\cdot
\frac{TF(t,d)(k_1+1)}
{TF(t,d)+k_1\left(1-b+b\frac{|d|}{avgdl}\right)}
]
Where:
| Symbol | Meaning | | |
|---|
| (q) | Search query | | |
| (d) | Document being evaluated | | |
| (t) | A search term | | |
| (TF(t,d)) | Frequency of term (t) in document (d) | | |
| (IDF(t)) | Inverse document frequency of term (t) | | |
| ( | d | ) | Length of the document |
| (avgdl) | Average document length in the collection | | |
| (k_1) | Controls term-frequency saturation | | |
| (b) | Controls document-length normalization | | |
The formula calculates a contribution for each query term and combines those contributions into a document score.
The parameters (k_1) and (b) are commonly configurable in some BM25-based search engines. They are useful for understanding how the algorithm behaves.
However, developers should not assume that these parameters are configurable in Azure Cosmos DB full-text search. The current Cosmos DB full-text search interface exposes BM25 scoring through FullTextScore; it does not provide the same per-index BM25 parameter configuration available in Azure AI Search.
This distinction matters when developers move search workloads between different Azure services.
How Azure Cosmos DB Uses BM25
Azure Cosmos DB for NoSQL provides full-text search capabilities that allow applications to search text properties stored inside JSON documents.
The full-text search implementation uses several text-processing techniques, including:
- Tokenization to divide text into searchable terms.
- Stemming to identify related word forms.
- Stop-word removal to reduce the influence of common words.
- BM25 scoring to calculate document relevance.
For example, an application may store product descriptions in a container. When a user searches for "wireless headphones," Cosmos DB can identify matching documents and rank them using BM25.
The main query functions are:
| Function | Purpose |
|---|
FullTextContains | Checks whether a text property contains a specified term or phrase |
FullTextContainsAll | Checks whether all supplied terms are present |
FullTextContainsAny | Checks whether at least one supplied term is present |
FullTextScore | Calculates the BM25 relevance score for ranking and supported score projection |
These functions allow developers to build search functionality directly into applications using Azure Cosmos DB for NoSQL.
Configuring Full-Text Search in Azure Cosmos DB
Before executing BM25-based search queries, configure a full-text policy and full-text index on the container.
A full-text policy identifies the document properties that should support full-text search. A full-text index enables efficient text searching on those properties.
Without the required policies and indexes, full-text queries can still execute in supported scenarios, but they may consume more request units and take longer.
Define the full-text policy
Suppose an application stores technical articles using the following JSON structure:
{
"id": "article-101",
"title": "Azure Cosmos DB Indexing Guide",
"category": "Database",
"content": "Learn how indexing policies improve query performance."
}
To search the content property, configure the container's full-text policy:
{
"defaultLanguage": "en-US",
"fullTextPaths": [
{
"path": "/content",
"language": "en-US"
}
]
}
The path identifies the document property, while language specifies the language used for text processing.
You can add multiple paths when an application needs to search titles, descriptions, and content separately.
For example:
{
"defaultLanguage": "en-US",
"fullTextPaths": [
{
"path": "/title",
"language": "en-US"
},
{
"path": "/content",
"language": "en-US"
},
{
"path": "/description",
"language": "en-US"
}
]
}
Choose the indexed paths carefully. Indexing every text property is not always necessary. Focus on fields that are part of actual search operations.
Configure the full-text index
The next step is to add the full-text index to the container's indexing policy.
{
"indexingMode": "consistent",
"automatic": true,
"includedPaths": [
{
"path": "/*"
}
],
"excludedPaths": [
{
"path": "/\"_etag\"/?"
}
],
"fullTextIndexes": [
{
"path": "/title"
},
{
"path": "/content"
},
{
"path": "/description"
}
]
}
The full-text index paths should match the properties declared in the full-text policy.
When configuring a new container, include these settings during container creation. For an existing container, update the container's indexing and full-text policies through the supported Azure management interface or SDK.
Implementing BM25 Search Queries
Once full-text search is configured, you can use the Cosmos DB query language to retrieve and rank documents.
Search for a specific term
The FullTextContains function checks whether a text property contains a specified term or phrase.
SELECT TOP 10 *
FROM c
WHERE FullTextContains(c.content, "indexing")
This query returns up to ten documents whose content property matches the search term.
Use this approach when the application needs to filter documents based on a particular keyword or phrase.
Search for all terms
The FullTextContainsAll function checks whether all supplied search terms are present in the specified property.
SELECT TOP 10 *
FROM c
WHERE FullTextContainsAll(
c.content,
"Azure",
"Cosmos",
"indexing"
)
The terms do not need to appear next to each other. This function is useful when an application requires documents containing all important search terms.
Search for any matching term
Sometimes an application should return documents containing at least one of several related terms.
Use FullTextContainsAny for this purpose:
SELECT TOP 10 *
FROM c
WHERE FullTextContainsAny(
c.content,
"indexing",
"partitioning",
"query"
)
This query returns documents that contain at least one of the supplied terms.
It is useful for broader searches where users may use different words to describe a similar topic.
Rank documents using BM25
The FullTextScore function calculates the BM25 relevance score.
To return documents in relevance order, use it with ORDER BY RANK.
SELECT TOP 10
c.id,
c.title,
c.content
FROM c
ORDER BY RANK FullTextScore(
c.content,
"Azure",
"Cosmos",
"indexing"
)
The query orders documents from higher relevance to lower relevance.
This is one of the most important differences between basic keyword filtering and relevance-based search. Instead of returning matching documents in an arbitrary order, the application can prioritize documents that provide stronger matches.
Understanding BM25 Score Projection
Previously, developers could use FullTextScore to rank results but could not directly retrieve the score as a projected field in the query output.
Azure Cosmos DB introduced BM25 score projection as a generally available capability in November 2026. It allows applications to inspect the relevance score directly.
This is useful when building search interfaces, debugging unexpected rankings, or applying application-level relevance thresholds.
For example:
SELECT TOP 10
c.id,
c.title,
c.content,
FullTextScore(
c.content,
"Azure",
"Cosmos",
"indexing"
) AS score
FROM c
WHERE FullTextScore(
c.content,
"Azure",
"Cosmos",
"indexing"
) > 0
ORDER BY RANK FullTextScore(
c.content,
"Azure",
"Cosmos",
"indexing"
)
This query performs three operations:
- Calculates the BM25 score for each matching document.
- Filters out documents whose score is not greater than zero.
- Returns the score as the
score property while ranking documents by relevance.
There is an important query requirement: the scoring expression used in the projection must also appear in the corresponding ORDER BY RANK expression.
The score is not a probability or a universal relevance percentage. It is a ranking value generated for the query and indexed document collection.
Use score projection in application interfaces
A search application can use the projected score for internal ranking diagnostics or application-level filtering.
For example, an application may return the title, identifier, and score to its search service:
{
"id": "article-101",
"title": "Azure Cosmos DB Indexing Guide",
"score": 4.82
}
The score shown here is illustrative.
Developers can use the value to compare results from the same search operation, identify documents with weak relevance, and investigate changes in search behavior.
Avoid presenting raw BM25 scores to end users as percentages. A score of 4.82 does not mean that a document is 4.82 times more relevant than another document.
Using BM25 With .NET and the Azure Cosmos DB SDK
.NET applications can execute full-text search queries using the Azure Cosmos DB SDK.
The following example demonstrates how to retrieve documents ordered by BM25 relevance and read the projected score.
Assume the container has already been configured with the required full-text policy and index.
using Microsoft.Azure.Cosmos;
public record ArticleSearchResult(
string Id,
string Title,
string Content,
double Score);
public class ArticleSearchService
{
private readonly Container _container;
public ArticleSearchService(CosmosClient client)
{
_container = client.GetContainer(
"ContentDatabase",
"Articles");
}
public async Task<List<ArticleSearchResult>> SearchAsync(
string keyword)
{
string queryText = """
SELECT TOP 10
c.id AS Id,
c.title AS Title,
c.content AS Content,
FullTextScore(
c.content,
@keyword
) AS Score
FROM c
WHERE FullTextScore(
c.content,
@keyword
) > 0
ORDER BY RANK FullTextScore(
c.content,
@keyword
)
""";
var queryDefinition = new QueryDefinition(queryText)
.WithParameter("@keyword", keyword);
using FeedIterator<ArticleSearchResult> iterator =
_container.GetItemQueryIterator<ArticleSearchResult>(
queryDefinition);
var results = new List<ArticleSearchResult>();
while (iterator.HasMoreResults)
{
FeedResponse<ArticleSearchResult> response =
await iterator.ReadNextAsync();
results.AddRange(response);
}
return results;
}
}
The example uses a parameterized query instead of inserting user input directly into the SQL string. This is important when search terms come from users.
The service returns a collection of articles with their relevance scores. The application can use these values to inspect ranking behavior or apply additional business rules.
For production applications, also consider cancellation tokens, pagination, request-unit tracking, and partition-aware query design.
Combining BM25 With Vector Search
Keyword search works well when users know the terms they are looking for. However, users do not always use the same words as the documents they want to find.
For example, a user may search for:
How do I make my database queries faster?
A document may explain query optimization, indexing strategies, and execution plans without using the exact phrase "make queries faster."
Vector search can identify semantic similarity even when the wording is different.
Azure Cosmos DB supports hybrid search, which combines full-text search and vector search using Reciprocal Rank Fusion (RRF).
The basic process is:
- Run full-text search using BM25.
- Run vector search using an embedding of the user's query.
- Combine the rankings using RRF.
- Return a unified result set.
A simplified query structure looks like this:
SELECT TOP 10 *
FROM c
ORDER BY RANK RRF(
FullTextScore(c.content, "database", "performance"),
VectorDistance(
c.embedding,
@queryVector
)
)
This example illustrates the ranking structure. The vector field, embedding dimensions, distance configuration, and vector index must be configured appropriately for the actual container.
BM25 contributes keyword relevance, while vector search contributes semantic similarity. RRF combines their rankings rather than requiring developers to compare the raw scores directly.
This is useful for documentation search, product discovery, support systems, and RAG applications.
BM25 vs. Vector Search vs. Semantic Reranking
These technologies solve related but different problems.
| Feature | BM25 | Vector Search | Semantic Reranking |
|---|
| Main purpose | Rank documents by keyword relevance | Find semantically similar content | Improve the ordering of retrieved candidates |
| Input | Search terms and document text | Query and document embeddings | Query context and candidate documents |
| Understands exact keywords | Yes | Not directly | Can consider document meaning |
| Requires embeddings | No | Yes | No embedding generation is required by the application for the rerank call |
| Additional inference call | No | Not necessarily, when using database vector search | Yes |
| Common use | Traditional full-text search | Semantic retrieval | Improving top search results |
BM25 is a strong choice when exact terminology matters. Vector search is useful when meaning matters more than exact word overlap. Semantic reranking can improve the final ordering when the initial retrieval stage has already identified relevant candidates.
These approaches can be combined rather than treated as competing technologies.
Performance and Request Unit Considerations
Search performance depends on the number of indexed documents, the size of text properties, query complexity, indexing configuration, and partition distribution.
BM25 does not remove the need for good database design. A query can still consume significant request units if it scans unnecessary data or operates without the required full-text index.
Consider the following practices:
Configure full-text indexes
Define both the full-text policy and full-text index for the properties used in search queries. Microsoft recommends this configuration because queries without the required index can consume more RUs and take longer.
Search only relevant properties
Do not configure full-text search on every text property without a clear requirement. Focus on fields such as title, description, content, or product details that are part of actual search operations.
Limit the number of returned documents
Use TOP to limit the number of results returned by the query.
For example:
SELECT TOP 20
c.id,
c.title
FROM c
ORDER BY RANK FullTextScore(
c.content,
"Azure",
"indexing"
)
The application should retrieve only the number of results required by the current page or search experience.
Monitor request units
Track request-unit consumption for representative search queries. Compare results before and after introducing full-text indexing, and test with realistic document sizes and query patterns.
Avoid unnecessary score calculations
Use the same scoring expression consistently when projecting and ranking results. Avoid adding multiple full-text scoring expressions when the application does not need them.
Common Mistakes to Avoid
Assuming BM25 only counts matching words
BM25 considers term frequency, inverse document frequency, and document length. Relevance is not determined by keyword count alone.
Forgetting the full-text index
A query may execute without the expected full-text index configuration, but performance and RU consumption can be affected. Configure the policy and index before relying on full-text search in production.
Treating scores as percentages
A BM25 score is a ranking signal, not a probability. Do not display it as a confidence percentage or compare unrelated queries using a fixed threshold without validation.
Assuming BM25 parameters are configurable in Cosmos DB
Some search services expose parameters such as k1 and b. Do not copy configuration examples from those services and assume they apply to Azure Cosmos DB.
Using vector search when exact keywords are essential
Vector search can identify semantic similarity, but it may not prioritize exact product codes, error identifiers, or technical terms in the way a keyword-based search does. Consider hybrid search when both signals matter.
Expecting BM25 to understand complete user intent
BM25 is a lexical ranking algorithm. It does not perform the same natural-language interpretation as an AI semantic reranker. For complex natural-language queries, combine retrieval with semantic reranking when the additional latency and cost are justified.
Ignoring language and tokenization behavior
Tokenization, stemming, and stop-word handling affect which terms are indexed and matched. Test queries using the actual language and terminology found in your documents.
Best Practices for Production Applications
A production search system should focus on result quality, predictable performance, and maintainable query behavior.
- Define a full-text policy for the properties that users actually search.
- Configure a matching full-text index.
- Use
FullTextContainsAll when every supplied term must match. - Use
FullTextContainsAny when any supplied term is sufficient. - Use
FullTextScore with ORDER BY RANK for relevance-based ordering. - Use score projection when the application needs to inspect or filter relevance values.
- Keep user search terms parameterized.
- Evaluate BM25 results using representative queries and documents.
- Monitor request-unit consumption and query latency.
- Use hybrid search when both keyword and semantic matching are important.
- Consider semantic reranking when the top results need deeper contextual evaluation.
- Do not assume BM25 scores are comparable across different queries or changing document collections.
- Test language-specific behavior before using full-text search with multilingual content.
Advantages and Disadvantages of BM25 in Azure Cosmos DB
| Advantages | Disadvantages |
|---|
| Provides relevance-based ranking for text searches | Does not understand full natural-language intent |
| Considers term frequency, document rarity, and document length | Does not guarantee that the highest-ranked document is factually correct |
| Works directly with Azure Cosmos DB for NoSQL | Requires appropriate full-text policies and indexes |
| Does not require an external search engine for supported full-text scenarios | Language processing behavior may vary by language |
Supports filtering and ranking through FullTextScore | BM25 tuning parameters are not exposed in the same way as Azure AI Search |
| Score projection makes ranking easier to inspect | Scores need careful interpretation and should not be treated as probabilities |
Summary
BM25 is an important part of Azure Cosmos DB full-text search because it provides a relevance-based way to rank documents. Instead of relying only on the presence of matching keywords, it considers term frequency, inverse document frequency, and document length.
Azure Cosmos DB exposes this functionality through FullTextScore, which can be used with ORDER BY RANK to return the most relevant documents first. The generally available BM25 score projection capability also allows applications to inspect and use the relevance score directly in query results.
For production applications, configure the full-text policy and index carefully, use the appropriate search functions, and monitor request-unit consumption. When exact keyword matching is not enough, combine BM25 with vector search or semantic reranking.
Understanding how BM25 works helps developers build more useful search experiences, improve result ordering, and make better decisions when designing search and retrieval systems with Azure Cosmos DB.
Join the conversation! Your thoughts help the community grow.