Writing database queries becomes more difficult as applications grow. Developers need to understand the data model, partitioning strategy, available indexes, filtering requirements, and the application's expected result shape.
AI-assisted query generation can reduce some of that work. A developer can describe a requirement in natural language and ask an AI tool to generate a query for Azure Cosmos DB.
That can be useful, but a generated query should not be considered production-ready simply because it executes successfully.
For Azure Cosmos DB for NoSQL, a useful evaluation needs to consider at least two dimensions:
Accuracy: Does the query return the correct data?
RU efficiency: Does it perform the operation without unnecessary request-unit consumption?
Latency, partition behavior, result size, and query safety are also valuable measurements.
This makes AI query assistance a good candidate for a controlled engineering experiment rather than a simple feature demonstration.
Why Query Accuracy Is Only the First Test
Consider a requirement such as:
Find active orders for customer 1001
created during the last 30 days.
An AI assistant might generate:
SELECT c.id, c.status, c.total
FROM c
WHERE c.customerId = @customerId
AND c.status = @status
AND c.createdAt >= @startDate
The query looks reasonable.
But several questions remain:
Are all required records returned?
Are inactive orders excluded?
Is the date comparison correct?
Is the partition key being used?
How many RUs does the query consume?
Is the application retrieving more fields than necessary?
Does the query behave similarly as data volume grows?
A good evaluation therefore looks like:
Natural-Language Requirement
|
v
AI Query Assistant
|
v
Generated Query
|
+-----+-----+------+
| | |
v v v
Correctness RU Latency
| | |
+-----+-----+------+
|
v
Engineering Result
Understanding Request Units
Azure Cosmos DB uses Request Units (RUs) to represent the computational cost of database operations.
For AI-generated queries, RU consumption is particularly interesting because the assistant may produce several logically equivalent queries with different execution characteristics.
For example:
| Query | Result | RU Cost | Interpretation |
|---|---|---|---|
| A | Correct | Measured | Baseline |
| B | Correct | Measured | Compare |
| C | Incorrect | Measured | Reject |
| D | Correct | High | Investigate |
The values must come from an actual experiment. RU consumption varies according to factors such as data size, indexing, partitioning, query shape, and returned data.
Therefore, there is no single RU value that should be presented as the expected cost of a query pattern.
Build a Trusted Baseline
The first step is to create a query written or reviewed by an experienced developer.
Suppose the container uses:
/customerId
as its partition key.
A baseline query could be:
SELECT c.id, c.status, c.total
FROM c
WHERE c.customerId = @customerId
AND c.status = @status
AND c.createdAt >= @startDate
This query becomes the reference point for evaluating the AI-generated version.
The baseline should be reviewed for:
Correctness
Partition strategy
Required projection
Parameterization
Expected workload
The goal is not to prove that the human query is perfect. It is to establish a controlled reference.
Create Representative Test Data
AI query evaluation is only meaningful when the dataset represents the application's data model.
A sample document might look like:
{
"id": "order-10001",
"customerId": "customer-1001",
"status": "Active",
"total": 249.50,
"createdAt": "2026-08-20T10:30:00Z",
"items": [
{
"productId": "product-10",
"quantity": 2
}
]
}
A useful dataset should include:
Multiple customers
Different order statuses
Different dates
Multiple products
Empty and non-empty arrays
Different document sizes
Realistic distribution of records
It should also contain enough data to make partitioning and query behavior meaningful.
A query that looks efficient against 100 documents may not behave the same way against a much larger dataset.
Give the AI Assistant Schema Context
AI query generation improves when the assistant has accurate schema information.
For example:
{
"container": "orders",
"partitionKey": "/customerId",
"fields": {
"id": "string",
"customerId": "string",
"status": "string",
"total": "number",
"createdAt": "datetime"
}
}
The assistant should also understand important constraints:
Use parameterized queries.
Partition key: customerId.
Return only required fields.
Do not generate write operations.
Without this information, the model may infer field names or relationships incorrectly.
Test Query Accuracy
Accuracy should be evaluated against a known expected result.
For example:
var expectedIds = new HashSet<string>
{
"order-10001",
"order-10004",
"order-10009"
};
After executing the AI-generated query:
var actualIds = results
.Select(x => x.Id)
.ToHashSet();
Assert.Equal(expectedIds, actualIds);
For more complex queries, compare the complete expected result rather than only checking that some records exist.
This helps detect:
Missing records
Extra records
Incorrect filtering
Incorrect sorting
Incorrect projections
Measure RU Consumption in C#
The Cosmos DB SDK exposes request-charge information through the query response.
A simple measurement can be implemented like this:
var iterator = container.GetItemQueryIterator<Order>(
queryDefinition);
double totalRequestCharge = 0;
while (iterator.HasMoreResults)
{
var response = await iterator.ReadNextAsync();
totalRequestCharge += response.RequestCharge;
foreach (var order in response)
{
Console.WriteLine(order.Id);
}
}
Console.WriteLine(
$"Total request charge: {totalRequestCharge} RU");
For a multi-page query, capture the total request charge across all responses.
Comparing only the first page can produce an incomplete measurement.
Measure Latency Separately
RU cost and latency are related but not identical.
Measure query execution time separately:
var stopwatch = Stopwatch.StartNew();
var results = await ExecuteQueryAsync();
stopwatch.Stop();
Console.WriteLine(
$"Elapsed: {stopwatch.ElapsedMilliseconds} ms");
For a meaningful benchmark, execute the same workload multiple times and record appropriate statistics rather than relying on one execution.
Useful measurements include:
Average
Median
P95
P99
The exact metrics should depend on the workload being tested.
Test Partition-Aware Queries
Partitioning is one of the most important parts of Cosmos DB query design.
Suppose:
/customerId
is the partition key.
A query that supplies a specific customer ID can provide the database with useful partition information:
SELECT c.id, c.total
FROM c
WHERE c.customerId = @customerId
AND c.status = @status
An AI assistant that ignores the partition model may generate a query such as:
SELECT c.id, c.total
FROM c
WHERE c.status = @status
That may still be functionally correct, depending on the dataset.
However, it may have a very different cost profile.
This is exactly why correctness and RU efficiency need to be measured separately.
Projection Matters
AI-generated queries may retrieve entire documents when only a few fields are needed.
For example:
SELECT *
FROM c
WHERE c.status = @status
If the application only needs an ID and total:
SELECT c.id, c.total
FROM c
WHERE c.status = @status
The second query expresses a more focused data requirement.
When evaluating AI query generation, track whether the assistant consistently selects only the fields required by the task.
This is both a performance and data-minimization concern.
Test Different Natural-Language Prompts
Do not evaluate the assistant using one carefully written prompt.
Create multiple phrasings of the same requirement.
For example:
Join the conversation! Your thoughts help the community grow.