Exploration Queries
-
An exploration query uses the RQL
filterclause (theFilter()method in the C# API)
to evaluate a condition on the server against the results a query retrieves. -
Processing has two main stages:
- Retrieve - the query retrieves results from a collection or an index, as defined by
fromand anywherecondition. - Filter - the server examines the retrieved results one by one and keeps those that match the
filtercondition.
No index is used or created for thefiltercondition.
The matching results are returned to the client.
- Retrieve - the query retrieves results from a collection or an index, as defined by
-
Because
filterexamines results individually, its cost grows with the number of results it scans.
Usefilter_limitto cap the number of results examined on large datasets. See Limit the number of scanned results.
For recurring queries, preferwherewhen the condition can be indexed. See When to use exploration queries. -
In this article:
- How exploration queries work
- When to use exploration queries
- Exploration queries vs disabling auto-index creation
- Exploration queries by query type
- Limit the number of scanned results
- Filter and sorting
- Filter and paging
- Filter and projections
- Filter by a related document
- Filter with a JavaScript function
- Filter and sharding
- Supported operators and limitations
- Syntax
How exploration queries work
C# queries written with LINQ or DocumentQuery are translated into RQL before being sent to the server.
The processing described below applies to these APIs as well as to queries written directly in RQL.
-
An exploration query is processed on the server in two main stages:
-
Retrieve
The query retrieves results from the specified collection or index (static or auto), applying any initial query conditions. In RQL, these are specified by thefromandwhereclauses.
The retrieved results are the candidate results for filtering.
If sorting is specified, it determines the order in which the filter examines them. -
Filter
The server examines the candidate results one by one and evaluates the filter condition using its JavaScript engine. Matching results are kept; results that fail the condition are skipped.
No index is used or created for the filter condition.
If a projection is specified, the matching results are projected before being returned to the client.
Otherwise, the matching results are returned without projection. -
-
What the filter condition is evaluated against:
- Full documents for full-collection queries and queries on a Map index (static or auto).
The filter condition can reference document fields that aren't indexed. - Aggregation results for Map-Reduce indexes and dynamic aggregation queries (
group byin RQL).
Learn more in Filter with a static Map-Reduce index and Filter with a dynamic group-by query.
- Full documents for full-collection queries and queries on a Map index (static or auto).
-
Filtering stops when any of the following occurs:
- Enough results have been collected to fill the requested page. See Filter and paging.
- No further candidates remain to be examined.
- The number of examined candidates reaches the configured scan limit (
filter_limitin RQL),
including candidates rejected by the filter. See Limit the number of scanned results.
-
RQL filter comparison semantics:
=and==use strict equality (===);!=and<>use strict inequality (!==).
Equality compares both type and value.- String comparisons are case-sensitive, unlike the default behavior of the RQL
whereclause.
This applies to equality and inequality (==,!=) and range comparisons (<,<=,>,>=).
Uppercase ASCII letters come before lowercase ASCII letters in character-code order.
For example:filter Address.Country == "usa"does not match"USA".filter Name >= "a"excludes"Apple"but includes"apple".
-
The RQL structure illustrates this processing flow:
-
filtercomes aftergroup by,where,order by, andload, and beforeselectandinclude.
limitandfilter_limitcome last:limitcontrols paging, andfilter_limitcaps the number of candidates examined. -
The outline below shows these clauses together. Optional clauses can be omitted:
declare function ... // Optional: define a function to call from 'filter'from <collection-name> // Or: from index "<index-name>"group by ... // Optional: 'filter' then evaluates the aggregation resultswhere ... // Optional: narrow the candidate resultsorder by ... // Optional: sort candidates before filteringload ... // Optional: load related documents for 'filter'filter <condition> // Evaluated per candidate, without using an indexselect ... // Optional: projectioninclude ... // Optional: send related documents to the client with the resultslimit <offset>, <pageSize> // Optional: pagingfilter_limit <number> // Optional: maximum number of candidates to examine
-
-
Query statistics on a non-sharded database:
When an exploration query is executed, the query statistics report:ScannedResultscounts the candidates actually examined by the filter.SkippedResultsincludes candidates rejected by the filter.
It can also include results skipped for other reasons, such as duplicate elimination.
-
For sharded databases, see Filter and sharding.
When to use exploration queries
Use filter when:
-
You need a one-time or occasional look at your data, for example during development, debugging, or a support investigation, without creating an index solely for that condition.
-
Use
filterwhen you need to evaluate a condition on fields that aren't indexed.
Usingwherefor the same condition has these implications:- In a static-index query,
wherecan use only the index fields.
Awherecondition on any other field throws an error. - In a dynamic query, a
wherecondition on a new field makes RavenDB create an auto-index that includes it.
Using
filteravoids these indexing requirements because it evaluates the condition directly against the retrieved results. - In a static-index query,
-
Use
filterwhen the required condition cannot be expressed as an ordinary RQLwherecomparison,
for example:- Comparing two fields of the same document, for example
filter UnitsInStock < ReorderLevel.
See Supported operators and limitations. - Checking a field of a related document. See Filter by a related document.
- Comparing two fields of the same document, for example
-
On a sharded database, use
filterwhen the condition applies to an aggregated value of a Map-Reduce orgroup byquery, such asCount.filterevaluates the combined results, whilewhereevaluates each shard's partial results and can miss matches. See Filter and sharding.
Prefer where when:
-
The query runs repeatedly and the condition can be evaluated using an index.
A dynamic query reuses a suitable auto-index or creates one when needed. Subsequent queries can use that index. -
The condition can be indexed and
filterwould otherwise need to scan a large dataset.
The cost offiltergrows with the number of results it examines.
where vs filter:
| Feature | where | filter |
|---|---|---|
| Evaluated against | An index, for ordinary field conditions | A document or aggregation result |
| Index usage | Uses the queried index. A dynamic query reuses a suitable auto-index or creates one when needed | No index is used or created for the filter condition |
| Work | Uses indexed fields to find matches | Examines results individually, until the page is full, filter_limit is reached, or results are exhausted |
| String comparison | Case-insensitive by default | Case-sensitive |
| Typical use | Recurring queries | Ad-hoc exploration or additional filtering logic |
Exploration queries vs disabling auto-index creation
Exploration queries use filter to evaluate a condition without requiring an index.
Disabling auto-index creation prevents RavenDB from automatically creating new auto-indexes.
The table below compares their purposes and effects on query execution:
| Feature | Purpose | Effect on query execution |
|---|---|---|
| Disabling auto-index creation | Prevent RavenDB from automatically creating new auto-indexes. | Blocks a query that would need a new auto-index - the query fails. The server setting also blocks queries that would use an existing auto-index. |
Exploration query (filter) | Evaluate a filter condition without requiring an index. | Scans the retrieved results and evaluates the filter condition without using or creating an index for that condition. |
Example
The table below compares queries against the Products collection.
Each product document has a UnitsInStock field containing the number of units currently in stock.
Assume auto-index creation is disabled and no existing auto-index covers the UnitsInStock field.
| Query | Result |
|---|---|
from Products where UnitsInStock > 10 | ❌ Failswhere needs an auto-index, and creating one is disabled. |
from Products filter UnitsInStock > 10 | ✅ Runsfilter scans the Products documents. No index is needed. |
Use them together
-
Disable auto-index creation to protect the database from unplanned indexes,
and usefilterto explore data that no index covers. -
filterdoesn't exempt the rest of the query:
Conditions on ordinary document fields inwhere, or sorting by document fields withorder by,
still require an auto-index in a collection query, so the settings still apply.
Where to disable auto-index creation
| Setting | Applies to | Effect |
|---|---|---|
| Studio: Disable creating new Auto-Indexes | Queries and patches run from the Studio, per database | Queries that need a new auto-index fail. Existing auto-indexes can still be used. |
| Server: Indexing.DisableQueryOptimizerGeneratedIndexes | All queries and patches, from any client including the Studio. Server-wide or per database | Queries that need an auto-index fail, even if a suitable one already exists. Database-level changes take effect after the database is reloaded. |
Patch-by-query and delete-by-query operations do not support filter.
You therefore cannot use filter to avoid the auto-index requirements of these operations.
See Query and operation restrictions.
Exploration queries by query type
-
You can use
filterwith each of the following query types:- Full-collection query -
Reads documents directly from a collection, without using a static index or an auto-index. - Dynamic query -
Queries a collection using an auto-index, for example to evaluatewhereconditions or sort by a document field.
RavenDB reuses a suitable auto-index or creates one when needed. - Static-index query -
Retrieves results using the static index explicitly specified in the query.
- Full-collection query -
-
For queries on Map-Reduce indexes and dynamic
group byqueries,
filterevaluates aggregation results rather than individual documents.
Learn more in Filter with a static Map-Reduce index and Filter with a dynamic group-by query. -
In each case,
filterapplies an additional condition to the results retrieved by the query,
without using or creating an index for that condition.
Filter with a full-collection query
-
In a full-collection query,
filterexamines documents directly from the collection.
No index is used and no auto-index is created. -
The following query returns all companies located in the USA.
Each matching result is a fullCompanydocument.
No page size orfilter_limitis set, so the filter examines the entire collection:
- Query
- Query_async
- DocumentQuery
- DocumentQuery_async
- RawQuery
- RawQuery_async
- RQL
List<Company> companies = session
.Query<Company>()
// Scan all documents in the collection and keep only companies located in the USA.
// No auto-index is created.
.Filter(c => c.Address.Country == "USA")
.ToList();
List<Company> companies = await asyncSession
.Query<Company>()
// Scan all documents in the collection and keep only companies located in the USA.
// No auto-index is created.
.Filter(c => c.Address.Country == "USA")
.ToListAsync();
List<Company> companies = session.Advanced
.DocumentQuery<Company>()
// Scan all documents in the collection and keep only companies located in the USA.
// No auto-index is created.
.Filter(f => f.Equals(c => c.Address.Country, "USA"))
.ToList();
List<Company> companies = await asyncSession.Advanced
.AsyncDocumentQuery<Company>()
// Scan all documents in the collection and keep only companies located in the USA.
// No auto-index is created.
.Filter(f => f.Equals(c => c.Address.Country, "USA"))
.ToListAsync();
List<Company> companies = session.Advanced
.RawQuery<Company>("from Companies filter Address.Country == $country")
.AddParameter("country", "USA")
.ToList();
List<Company> companies = await asyncSession.Advanced
.AsyncRawQuery<Company>("from Companies filter Address.Country == $country")
.AddParameter("country", "USA")
.ToListAsync();
from Companies
filter Address.Country == "USA"
Without a page size or filter_limit, filtering a large collection can scan every document in it,
which burdens the server and prolongs the query time.
-
Set a page size to limit the number of matching results returned.
Learn more in Filter and paging. -
Set
filter_limitto restrict the number of scanned documents.
Learn more in Limit the number of scanned results.
Filter with a dynamic query
-
A collection query targets a collection without explicitly specifying an index.
RavenDB processes a collection query as a dynamic query when it includes awherecondition on document fields other than just the document ID, anorder byclause that sorts by a document field, or both.
It reuses a suitable auto-index or creates one when needed.
Learn more in Query a collection - with filtering.Dynamic
group byqueries use an auto Map-Reduce index.
See Filter with a dynamic group-by query. -
Narrow the results with
wherefirst: only results matching thatwherecondition are examined byfilter.
The fields referenced infilterare not added to the auto-index. -
The following query returns full
Companydocuments that match both conditions:where:Contact.Titleequals "Sales Representative" (case-insensitive).filter:Address.Countryequals "Germany" (case-sensitive).
- Query
- Query_async
- DocumentQuery
- DocumentQuery_async
- RawQuery
- RawQuery_async
- RQL
List<Company> companies = session
.Query<Company>()
// 'Where' is evaluated against an auto-index that indexes 'Contact.Title'
.Where(c => c.Contact.Title == "Sales Representative")
// 'Filter' scans only the results that matched the 'Where' condition.
// 'Address.Country' is NOT added to the auto-index.
.Filter(c => c.Address.Country == "Germany")
.ToList();
List<Company> companies = await asyncSession
.Query<Company>()
// 'Where' is evaluated against an auto-index that indexes 'Contact.Title'
.Where(c => c.Contact.Title == "Sales Representative")
// 'Filter' scans only the results that matched the 'Where' condition.
// 'Address.Country' is NOT added to the auto-index.
.Filter(c => c.Address.Country == "Germany")
.ToListAsync();
List<Company> companies = session.Advanced
.DocumentQuery<Company>()
// 'WhereEquals' is evaluated against an auto-index that indexes 'Contact.Title'
.WhereEquals(c => c.Contact.Title, "Sales Representative")
// 'Filter' scans only the results that matched the 'WhereEquals' condition.
// 'Address.Country' is NOT added to the auto-index.
.Filter(f => f.Equals(c => c.Address.Country, "Germany"))
.ToList();
List<Company> companies = await asyncSession.Advanced
.AsyncDocumentQuery<Company>()
// 'WhereEquals' is evaluated against an auto-index that indexes 'Contact.Title'
.WhereEquals(c => c.Contact.Title, "Sales Representative")
// 'Filter' scans only the results that matched the 'WhereEquals' condition.
// 'Address.Country' is NOT added to the auto-index.
.Filter(f => f.Equals(c => c.Address.Country, "Germany"))
.ToListAsync();
List<Company> companies = session.Advanced
.RawQuery<Company>(@"
from Companies
where Contact.Title == $title
filter Address.Country == $country")
.AddParameter("title", "Sales Representative")
.AddParameter("country", "Germany")
.ToList();
List<Company> companies = await asyncSession.Advanced
.AsyncRawQuery<Company>(@"
from Companies
where Contact.Title == $title
filter Address.Country == $country")
.AddParameter("title", "Sales Representative")
.AddParameter("country", "Germany")
.ToListAsync();
from Companies
where Contact.Title == "Sales Representative"
filter Address.Country == "Germany"
Auto-index used:
The where condition uses an auto-index on Contact.Title, such as Auto/Companies/ByContact.Title.
The Address.Country field used by filter does not need to be indexed.
Filter with a static index query
-
For a static Map index,
whereevaluates its condition against the index-fields,
whilefilterevaluates its condition against the original documents.
The filter condition can therefore reference document fields that aren't included in the index. -
filtercannot see fields that exist only in the index, even if they are stored.
For example, if an index computesStockValue = UnitsInStock * PricePerUnitand the documents have noStockValuefield,filter StockValue > 1000returns no matches without reporting an error. -
For example, create and deploy the following index, which indexes only the product's
Categoryfield:public class Products_ByCategory : AbstractIndexCreationTask<Product>{public class IndexEntry{// The index fieldpublic string Category { get; set; }}public Products_ByCategory(){Map = products => from product in productsselect new IndexEntry{Category = product.Category};}}
-
Query the index for beverages (categories/1-A), then
filterthe retrieved documents to those whosePricePerUnitis greater than 20.
PricePerUnitis not indexed by this index, so awherecondition on it would fail.Each matching result is a full
Productdocument.
The query uses the specified static index. No auto-index is created:
- Query
- Query_async
- DocumentQuery
- DocumentQuery_async
- RawQuery
- RawQuery_async
- RQL
List<Product> products = session
.Query<Products_ByCategory.IndexEntry, Products_ByCategory>()
// 'Where' is evaluated against the index-field 'Category'
.Where(x => x.Category == "categories/1-A")
// Switch the query type to 'Product', so 'Filter' can reference document fields
.OfType<Product>()
// 'Filter' is evaluated against each retrieved Product document
.Filter(p => p.PricePerUnit > 20)
.ToList();
List<Product> products = await asyncSession
.Query<Products_ByCategory.IndexEntry, Products_ByCategory>()
// 'Where' is evaluated against the index-field 'Category'
.Where(x => x.Category == "categories/1-A")
// Switch the query type to 'Product', so 'Filter' can reference document fields
.OfType<Product>()
// 'Filter' is evaluated against each retrieved Product document
.Filter(p => p.PricePerUnit > 20)
.ToListAsync();
List<Product> products = session.Advanced
.DocumentQuery<Products_ByCategory.IndexEntry, Products_ByCategory>()
// 'WhereEquals' is evaluated against the index-field 'Category'
.WhereEquals(x => x.Category, "categories/1-A")
// Switch the query type to 'Product', so 'Filter' can reference document fields
.OfType<Product>()
// 'Filter' is evaluated against each retrieved Product document
.Filter(f => f.GreaterThan(p => p.PricePerUnit, 20))
.ToList();
List<Product> products = await asyncSession.Advanced
.AsyncDocumentQuery<Products_ByCategory.IndexEntry, Products_ByCategory>()
// 'WhereEquals' is evaluated against the index-field 'Category'
.WhereEquals(x => x.Category, "categories/1-A")
// Switch the query type to 'Product', so 'Filter' can reference document fields
.OfType<Product>()
// 'Filter' is evaluated against each retrieved Product document
.Filter(f => f.GreaterThan(p => p.PricePerUnit, 20))
.ToListAsync();
List<Product> products = session.Advanced
.RawQuery<Product>(@"
from index 'Products/ByCategory'
where Category == $category
filter PricePerUnit > $price")
.AddParameter("category", "categories/1-A")
.AddParameter("price", 20)
.ToList();
List<Product> products = await asyncSession.Advanced
.AsyncRawQuery<Product>(@"
from index 'Products/ByCategory'
where Category == $category
filter PricePerUnit > $price")
.AddParameter("category", "categories/1-A")
.AddParameter("price", 20)
.ToListAsync();
from index "Products/ByCategory"
where Category == "categories/1-A"
filter PricePerUnit > 20
Why use OfType<Product>() before Filter?
-
The
Querycall usesProducts_ByCategory.IndexEntryas the query’s initial result type.
TheWherelambda can therefore reference properties defined byIndexEntry, such asCategory. -
OfType<Product>()switches the query type toProductbeforeFilter,
so theFilterlambda can reference document fields such asPricePerUnit,
and the results are returned asProduct.A
Filterexpression that referencesPricePerUnitwould not compile beforeOfType<Product>(),
becauseIndexEntrydoes not define that property. -
OfTypechanges only the C# type, not the RQL sent to the server.
On the server,filterevaluates the original documents regardless of the C# type.
Filter with a Map-Reduce index query - static Map-Reduce index
-
When querying a Map-Reduce index, the
filtercondition is evaluated against the aggregation results,
so it references the reduce result fields rather than the original documents.
The same applies to dynamicgroup byqueries. -
Both this example and the dynamic group-by query example below use the following C# result class:
public class OrdersByCompanyResult{public string Company { get; set; }public int Count { get; set; }}
Create and deploy the following index, which counts orders per company.
It is a simplified version of Orders/ByCompany from the sample data, containing only Company and Count:
public class Orders_ByCompany : AbstractIndexCreationTask<Order, OrdersByCompanyResult>
{
public Orders_ByCompany()
{
Map = orders => from order in orders
select new OrdersByCompanyResult
{
Company = order.Company,
Count = 1
};
Reduce = results => from result in results
group result by result.Company into g
select new OrdersByCompanyResult
{
Company = g.Key,
Count = g.Sum(x => x.Count)
};
}
}
The following query returns aggregation results for companies that placed more than 20 orders.
The query uses filter to apply the Count > 20 condition to the aggregation results.
- Query
- Query_async
- DocumentQuery
- DocumentQuery_async
- RawQuery
- RawQuery_async
- RQL
List<OrdersByCompanyResult> companies = session
.Query<OrdersByCompanyResult>("Orders/ByCompany", isMapReduce: true)
// 'Filter' is evaluated against each aggregation result.
.Filter(r => r.Count > 20)
.ToList();
List<OrdersByCompanyResult> companies = await asyncSession
.Query<OrdersByCompanyResult>("Orders/ByCompany", isMapReduce: true)
// 'Filter' is evaluated against each aggregation result.
.Filter(r => r.Count > 20)
.ToListAsync();
List<OrdersByCompanyResult> companies = session.Advanced
.DocumentQuery<OrdersByCompanyResult>("Orders/ByCompany", isMapReduce: true)
// 'Filter' is evaluated against each aggregation result.
.Filter(f => f.GreaterThan(r => r.Count, 20))
.ToList();
List<OrdersByCompanyResult> companies = await asyncSession.Advanced
.AsyncDocumentQuery<OrdersByCompanyResult>("Orders/ByCompany", isMapReduce: true)
// 'Filter' is evaluated against each aggregation result.
.Filter(f => f.GreaterThan(r => r.Count, 20))
.ToListAsync();
List<OrdersByCompanyResult> companies = session.Advanced
.RawQuery<OrdersByCompanyResult>(@"
from index 'Orders/ByCompany'
// 'filter' is evaluated against each aggregation result.
filter Count > $minimum")
.AddParameter("minimum", 20)
.ToList();
List<OrdersByCompanyResult> companies = await asyncSession.Advanced
.AsyncRawQuery<OrdersByCompanyResult>(@"
from index 'Orders/ByCompany'
// 'filter' is evaluated against each aggregation result.
filter Count > $minimum")
.AddParameter("minimum", 20)
.ToListAsync();
from index "Orders/ByCompany"
// 'filter' is evaluated against each aggregation result.
filter Count > 20
Filter with a Map-Reduce index query - dynamic group-by query
The query groups orders by Company and returns aggregation results for companies with more than 20 orders.
RavenDB reuses a suitable auto Map-Reduce index or creates one when needed.
The query uses the OrdersByCompanyResult class defined in the static Map-Reduce index example.
- Query
- Query_async
- DocumentQuery
- DocumentQuery_async
- RawQuery
- RawQuery_async
- RQL
List<OrdersByCompanyResult> companies = session
.Query<Order>()
// Group orders by company using an auto Map-Reduce index.
.GroupBy(o => o.Company)
// 'Filter' is evaluated against each aggregation result.
// 'g.Count()' is translated to the aggregation result field 'Count'.
.Filter(g => g.Count() > 20)
.Select(g => new OrdersByCompanyResult
{
Company = g.Key,
Count = g.Count()
})
.ToList();
List<OrdersByCompanyResult> companies = await asyncSession
.Query<Order>()
// Group orders by company using an auto Map-Reduce index.
.GroupBy(o => o.Company)
// 'Filter' is evaluated against each aggregation result.
// 'g.Count()' is translated to the aggregation result field 'Count'.
.Filter(g => g.Count() > 20)
.Select(g => new OrdersByCompanyResult
{
Company = g.Key,
Count = g.Count()
})
.ToListAsync();
List<OrdersByCompanyResult> companies = session.Advanced
.DocumentQuery<Order>()
// Group orders by company using an auto Map-Reduce index.
.GroupBy("Company")
// 'Filter' is evaluated against each aggregation result.
.Filter(f => f.GreaterThan("Count", 20))
.SelectKey("Company")
.SelectCount("Count")
.OfType<OrdersByCompanyResult>()
.ToList();
List<OrdersByCompanyResult> companies = await asyncSession.Advanced
.AsyncDocumentQuery<Order>()
// Group orders by company using an auto Map-Reduce index.
.GroupBy("Company")
// 'Filter' is evaluated against each aggregation result.
.Filter(f => f.GreaterThan("Count", 20))
.SelectKey("Company")
.SelectCount("Count")
.OfType<OrdersByCompanyResult>()
.ToListAsync();
List<OrdersByCompanyResult> companies = session.Advanced
.RawQuery<OrdersByCompanyResult>(@"
from Orders
group by Company
// 'filter' is evaluated against each aggregation result.
filter Count > $minimum
select Company, count() as Count")
.AddParameter("minimum", 20)
.ToList();
List<OrdersByCompanyResult> companies = await asyncSession.Advanced
.AsyncRawQuery<OrdersByCompanyResult>(@"
from Orders
group by Company
// 'filter' is evaluated against each aggregation result.
filter Count > $minimum
select Company, count() as Count")
.AddParameter("minimum", 20)
.ToListAsync();
from Orders
group by Company
// 'filter' is evaluated against each aggregation result.
filter Count > 20
select Company, count() as Count
Auto-index used:
An auto Map-Reduce index that groups orders by Company and counts them,
such as Auto/Orders/ByCountReducedByCompany.
The following applies to dynamic group-by query.
-
RQL: Use the Count field:
In RQL,
count()inselecttells RavenDB to include aCountfield in the auto Map-Reduce index.
Thefilterclause reads this field beforeselectprojects the results.For example, with
select Company, count() as NumOrders:Expression Behavior filter Count > 20Checks the aggregation count. filter NumOrders > 20Returns no matches without reporting an error
because the projection alias is unavailable during filtering.filter count() > 20Throws an error because the RQL count()function
is not supported insidefilter. -
LINQ: Call Filter before Select:
Call
FilterafterGroupByand beforeSelect, usingg.Count()in the predicate.
The client translatesg.Count()to the aggregation result fieldCount.If
Selectrenames the count toNumOrders, a later.Filter(x => x.NumOrders > 20)generates RQL that checksNumOrders.
This field exists only in the projected output, so the query returns no matches without reporting an error.
Limit the number of scanned results
How the scan limit works:
-
Set the
limitargument ofFilter(LINQ and DocumentQuery), orfilter_limitin RQL,
to specify the maximum number of candidate results the filter examines.
By default, nofilter_limitis set. If set, its value must be greater than 0. -
The limit applies to all candidates examined by the filter, whether they pass or fail the condition.
Candidates beyond the limit aren't examined or returned, even if they would match. -
When the query includes
where,filter_limitapplies to the candidates that matchwhere.
Scan limit vs page size:
The page size caps the number of matching results returned.
Filtering can stop before reaching filter_limit if the page is full or no more candidates remain.
Learn more in Filter and paging.
For example, assume no explicit page size is set, the filter condition is Country == "USA",
and filter_limit is 2. The candidates are examined in the order shown below:
| Candidate result | Country | Examined by filter | Returned |
|---|---|---|---|
| Employee 1 | USA | Yes | Yes |
| Employee 2 | Poland | Yes | No |
| Employee 3 | USA | No: limit reached | No |
The filter examines two employees, but only Employee 1 is returned.
- A query can return fewer results, or even no results, while matching candidates exist beyond
filter_limit. - Which candidates are examined depends on the order in which the query retrieves them.
Use sorting to control this order.
Example: examine up to 100 orders:
On a non-sharded database, the following query examines up to 100 orders and returns those shipped to the UK.
The query also requests query statistics:
stats.ScannedResultsreports the number of examined candidatesorders.Countreports the number of returned matches.
- Query
- Query_async
- DocumentQuery
- DocumentQuery_async
- RawQuery
- RawQuery_async
- RQL
List<Order> orders = session
.Query<Order>()
// Get query statistics to see how many results were scanned
.Statistics(out QueryStatistics stats)
// Examine up to 100 candidate results
.Filter(o => o.ShipTo.Country == "UK", limit: 100)
.ToList();
// orders.Count: the number of examined orders that matched the filter.
// stats.ScannedResults: the number examined, at most 100.
List<Order> orders = await asyncSession
.Query<Order>()
// Get query statistics to see how many results were scanned
.Statistics(out QueryStatistics stats)
// Examine up to 100 candidate results
.Filter(o => o.ShipTo.Country == "UK", limit: 100)
.ToListAsync();
// orders.Count: the number of examined orders that matched the filter.
// stats.ScannedResults: the number examined, at most 100.
List<Order> orders = session.Advanced
.DocumentQuery<Order>()
// Get query statistics to see how many results were scanned
.Statistics(out QueryStatistics stats)
// Examine up to 100 candidate results
.Filter(f => f.Equals(o => o.ShipTo.Country, "UK"), limit: 100)
.ToList();
// orders.Count: the number of examined orders that matched the filter.
// stats.ScannedResults: the number examined, at most 100.
List<Order> orders = await asyncSession.Advanced
.AsyncDocumentQuery<Order>()
// Get query statistics to see how many results were scanned
.Statistics(out QueryStatistics stats)
// Examine up to 100 candidate results
.Filter(f => f.Equals(o => o.ShipTo.Country, "UK"), limit: 100)
.ToListAsync();
// orders.Count: the number of examined orders that matched the filter.
// stats.ScannedResults: the number examined, at most 100.
List<Order> orders = session.Advanced
.RawQuery<Order>(@"
from Orders
filter ShipTo.Country == $country
filter_limit $limit")
.AddParameter("country", "UK")
.AddParameter("limit", 100)
// Get query statistics to see how many results were scanned
.Statistics(out QueryStatistics stats)
.ToList();
// orders.Count: the number of examined orders that matched the filter.
// stats.ScannedResults: the number examined, at most 100.
List<Order> orders = await asyncSession.Advanced
.AsyncRawQuery<Order>(@"
from Orders
filter ShipTo.Country == $country
filter_limit $limit")
.AddParameter("country", "UK")
.AddParameter("limit", 100)
// Get query statistics to see how many results were scanned
.Statistics(out QueryStatistics stats)
.ToListAsync();
// orders.Count: the number of examined orders that matched the filter.
// stats.ScannedResults: the number examined, at most 100.
from Orders
filter ShipTo.Country == "UK"
filter_limit 100
Sharded document queries
For a non-Map-Reduce query on a sharded database, each shard applies filter_limit locally.
It is not a database-wide cap on the total work done by all shards.
The orchestrator also caps the number of returned results at filter_limit.
Learn more in Filter and sharding.
Filter and sorting
Execution order:
-
Sorting is applied before filtering.
UseOrderBy/OrderByDescendingin LINQ and DocumentQuery, ororder byin RQL, to determine the order in which the filter examines candidate results. Results that pass the filter retain this order. -
In LINQ and DocumentQuery, placing
OrderBybefore or afterFilterdoes not change the execution order.
The client generates RQL withorder bybeforefilter. -
With
filter_limit, sorting determines which candidates are examined before the limit is reached.
Example: examine the 50 highest-freight orders:
On a non-sharded database, the following query examines up to 50 orders, starting with those with the highest freight cost.
It returns the UK orders found among those candidates, in descending Freight order.
Orders beyond the first 50 candidates aren't examined or returned.
- Query
- Query_async
- DocumentQuery
- DocumentQuery_async
- RawQuery
- RawQuery_async
- RQL
List<Order> orders = session
.Query<Order>()
// Sort the retrieved results first (this uses an auto-index on 'Freight')
.OrderByDescending(o => o.Freight)
// Examine up to 50 candidates in descending freight order
.Filter(o => o.ShipTo.Country == "UK", limit: 50)
.ToList();
List<Order> orders = await asyncSession
.Query<Order>()
// Sort the retrieved results first (this uses an auto-index on 'Freight')
.OrderByDescending(o => o.Freight)
// Examine up to 50 candidates in descending freight order
.Filter(o => o.ShipTo.Country == "UK", limit: 50)
.ToListAsync();
List<Order> orders = session.Advanced
.DocumentQuery<Order>()
// Sort the retrieved results first (this uses an auto-index on 'Freight')
.OrderByDescending(o => o.Freight)
// Examine up to 50 candidates in descending freight order
.Filter(f => f.Equals(o => o.ShipTo.Country, "UK"), limit: 50)
.ToList();
List<Order> orders = await asyncSession.Advanced
.AsyncDocumentQuery<Order>()
// Sort the retrieved results first (this uses an auto-index on 'Freight')
.OrderByDescending(o => o.Freight)
// Examine up to 50 candidates in descending freight order
.Filter(f => f.Equals(o => o.ShipTo.Country, "UK"), limit: 50)
.ToListAsync();
List<Order> orders = session.Advanced
.RawQuery<Order>(@"
from Orders
order by Freight as double desc
filter ShipTo.Country == $country
filter_limit $limit")
.AddParameter("country", "UK")
.AddParameter("limit", 50)
.ToList();
List<Order> orders = await asyncSession.Advanced
.AsyncRawQuery<Order>(@"
from Orders
order by Freight as double desc
filter ShipTo.Country == $country
filter_limit $limit")
.AddParameter("country", "UK")
.AddParameter("limit", 50)
.ToListAsync();
from Orders
order by Freight as double desc
filter ShipTo.Country == "UK"
filter_limit 50
Expected results:
- With the unmodified sample data, 2 of the 50 examined orders match:
orders/112-Aandorders/809-A. - Auto-index used:
An auto-index coveringFreight, such asAuto/Orders/ByFreight.
TheShipTo.Countryfield used byfilterdoes not need to be indexed.
Choosing candidates consistently
-
Without explicit sorting:
Candidates are examined in the order the collection or index returns them.
This order can change as documents or indexes change, so don't rely on it to select a particular subset. -
Equal sort values:
If the sort field contains repeated values, add a unique secondary sort field when you need a deterministic choice among those candidates. See Chain ordering.
Filter and paging
Page through matching results
For document queries on a non-sharded database:
- Use
Taketo set the maximum number of matching results per page. - Use
Skipto advance past the candidates examined by previous requests.
The offset must include both the results returned and the candidates rejected by the filter.
In RQL, use limit <offset>, <pageSize> to set the offset and page size.
The following example returns full Order documents shipped to the USA, up to 10 per page.
It assumes the data and candidate order remain unchanged between requests.
No filter_limit is set, so each request can examine all remaining candidates if needed.
The loop stops when a page is empty:
- Query
- Query_async
- DocumentQuery
- DocumentQuery_async
- RawQuery
- RawQuery_async
- RQL
const int pageSize = 10;
int offset = 0;
List<Order> pagedResults;
do
{
pagedResults = session
.Query<Order>()
.Statistics(out QueryStatistics stats)
.Filter(o => o.ShipTo.Country == "USA")
// Skip the candidates examined by previous page requests
.Skip(offset)
// Return at most 'pageSize' results that passed the filter
.Take(pageSize)
.ToList();
// Process the current page here...
// Advance the offset by the results returned AND the results the filter rejected
offset += pagedResults.Count + (int)stats.SkippedResults;
}
while (pagedResults.Count > 0);
const int pageSize = 10;
int offset = 0;
List<Order> pagedResults;
do
{
pagedResults = await asyncSession
.Query<Order>()
.Statistics(out QueryStatistics stats)
.Filter(o => o.ShipTo.Country == "USA")
// Skip the candidates examined by previous page requests
.Skip(offset)
// Return at most 'pageSize' results that passed the filter
.Take(pageSize)
.ToListAsync();
// Process the current page here...
// Advance the offset by the results returned AND the results the filter rejected
offset += pagedResults.Count + (int)stats.SkippedResults;
}
while (pagedResults.Count > 0);
const int pageSize = 10;
int offset = 0;
List<Order> pagedResults;
do
{
pagedResults = session.Advanced
.DocumentQuery<Order>()
.Statistics(out QueryStatistics stats)
.Filter(f => f.Equals(o => o.ShipTo.Country, "USA"))
// Skip the candidates examined by previous page requests
.Skip(offset)
// Return at most 'pageSize' results that passed the filter
.Take(pageSize)
.ToList();
// Process the current page here...
// Advance the offset by the results returned AND the results the filter rejected
offset += pagedResults.Count + (int)stats.SkippedResults;
}
while (pagedResults.Count > 0);
const int pageSize = 10;
int offset = 0;
List<Order> pagedResults;
do
{
pagedResults = await asyncSession.Advanced
.AsyncDocumentQuery<Order>()
.Statistics(out QueryStatistics stats)
.Filter(f => f.Equals(o => o.ShipTo.Country, "USA"))
// Skip the candidates examined by previous page requests
.Skip(offset)
// Return at most 'pageSize' results that passed the filter
.Take(pageSize)
.ToListAsync();
// Process the current page here...
// Advance the offset by the results returned AND the results the filter rejected
offset += pagedResults.Count + (int)stats.SkippedResults;
}
while (pagedResults.Count > 0);
const int pageSize = 10;
int offset = 0;
List<Order> pagedResults;
do
{
pagedResults = session.Advanced
.RawQuery<Order>("from Orders filter ShipTo.Country == $country")
.AddParameter("country", "USA")
.Statistics(out QueryStatistics stats)
// Skip the candidates examined by previous page requests
.Skip(offset)
// Return at most 'pageSize' results that passed the filter
.Take(pageSize)
.ToList();
// Process the current page here...
// Advance the offset by the results returned AND the results the filter rejected
offset += pagedResults.Count + (int)stats.SkippedResults;
}
while (pagedResults.Count > 0);
const int pageSize = 10;
int offset = 0;
List<Order> pagedResults;
do
{
pagedResults = await asyncSession.Advanced
.AsyncRawQuery<Order>("from Orders filter ShipTo.Country == $country")
.AddParameter("country", "USA")
.Statistics(out QueryStatistics stats)
// Skip the candidates examined by previous page requests
.Skip(offset)
// Return at most 'pageSize' results that passed the filter
.Take(pageSize)
.ToListAsync();
// Process the current page here...
// Advance the offset by the results returned AND the results the filter rejected
offset += pagedResults.Count + (int)stats.SkippedResults;
}
while (pagedResults.Count > 0);
// The first page: skip 0 candidates, return up to 10 results that pass the filter
from Orders
filter ShipTo.Country == "USA"
limit 0, 10
// For the next page, set the offset to:
// the current offset + the number of results returned + SkippedResults
The examples capture query statistics with .Statistics(out QueryStatistics stats).
For these queries, stats.SkippedResults counts candidates rejected by the filter during the current request.
It does not include candidates bypassed by Skip.
After each request, advance the offset by both the returned results and the rejected candidates:
offset += pagedResults.Count + (int)stats.SkippedResults;
This follows the approach described in Paging through tampered results.
For example, with a page size of 2, suppose the orders are examined in the following order.
The filter keeps orders shipped to the USA:
| Candidate | Country | First-page outcome |
|---|---|---|
| Order 1 | USA | Returned |
| Order 2 | Poland | Rejected by the filter |
| Order 3 | USA | Returned; the page is full |
| Order 4 | USA | Not examined on this page |
Three candidates were examined: 2 returned and 1 rejected.
The next offset is therefore 3: 0 + 2 + 1.
Using Skip(2) would examine Order 3 again, repeating a result from the previous page.
Page with a scan limit
For the non-sharded document query above, set Filter(..., limit: n) or RQL filter_limit
to cap the number of candidates each request examines after its offset, including rejected candidates.
Filtering can stop earlier if the page is full or no candidates remain.
See Limit the number of scanned results.
The following example returns full Order documents shipped to the USA, up to 10 per page,
while examining at most 100 candidates per request. It assumes the data and candidate order remain unchanged between requests.
The loop continues when the page is full or the scan limit was reached, even if the page is empty:
- Query
- Query_async
- DocumentQuery
- DocumentQuery_async
- RawQuery
- RawQuery_async
- RQL
const int pageSize = 10;
const int scanLimit = 100;
int offset = 0;
List<Order> pagedResults;
QueryStatistics stats;
do
{
pagedResults = session
.Query<Order>()
.Statistics(out stats)
.Filter(o => o.ShipTo.Country == "USA", limit: scanLimit)
// Skip the candidates examined by previous page requests
.Skip(offset)
// Return at most 'pageSize' results that passed the filter
.Take(pageSize)
.ToList();
// Process the current page here...
// Advance the offset by the results returned AND the results the filter rejected
offset += pagedResults.Count + (int)stats.SkippedResults;
}
// Continue if the page is full or the scan limit was reached, even after an empty page.
while (pagedResults.Count == pageSize ||
stats.ScannedResults == scanLimit);
const int pageSize = 10;
const int scanLimit = 100;
int offset = 0;
List<Order> pagedResults;
QueryStatistics stats;
do
{
pagedResults = await asyncSession
.Query<Order>()
.Statistics(out stats)
.Filter(o => o.ShipTo.Country == "USA", limit: scanLimit)
// Skip the candidates examined by previous page requests
.Skip(offset)
// Return at most 'pageSize' results that passed the filter
.Take(pageSize)
.ToListAsync();
// Process the current page here...
// Advance the offset by the results returned AND the results the filter rejected
offset += pagedResults.Count + (int)stats.SkippedResults;
}
// Continue if the page is full or the scan limit was reached, even after an empty page.
while (pagedResults.Count == pageSize ||
stats.ScannedResults == scanLimit);
const int pageSize = 10;
const int scanLimit = 100;
int offset = 0;
List<Order> pagedResults;
QueryStatistics stats;
do
{
pagedResults = session.Advanced
.DocumentQuery<Order>()
.Statistics(out stats)
.Filter(f => f.Equals(o => o.ShipTo.Country, "USA"), limit: scanLimit)
// Skip the candidates examined by previous page requests
.Skip(offset)
// Return at most 'pageSize' results that passed the filter
.Take(pageSize)
.ToList();
// Process the current page here...
// Advance the offset by the results returned AND the results the filter rejected
offset += pagedResults.Count + (int)stats.SkippedResults;
}
// Continue if the page is full or the scan limit was reached, even after an empty page.
while (pagedResults.Count == pageSize ||
stats.ScannedResults == scanLimit);
const int pageSize = 10;
const int scanLimit = 100;
int offset = 0;
List<Order> pagedResults;
QueryStatistics stats;
do
{
pagedResults = await asyncSession.Advanced
.AsyncDocumentQuery<Order>()
.Statistics(out stats)
.Filter(f => f.Equals(o => o.ShipTo.Country, "USA"), limit: scanLimit)
// Skip the candidates examined by previous page requests
.Skip(offset)
// Return at most 'pageSize' results that passed the filter
.Take(pageSize)
.ToListAsync();
// Process the current page here...
// Advance the offset by the results returned AND the results the filter rejected
offset += pagedResults.Count + (int)stats.SkippedResults;
}
// Continue if the page is full or the scan limit was reached, even after an empty page.
while (pagedResults.Count == pageSize ||
stats.ScannedResults == scanLimit);
const int pageSize = 10;
const int scanLimit = 100;
int offset = 0;
List<Order> pagedResults;
QueryStatistics stats;
do
{
pagedResults = session.Advanced
.RawQuery<Order>(@"
from Orders
filter ShipTo.Country == $country
filter_limit $scanLimit")
.AddParameter("country", "USA")
.AddParameter("scanLimit", scanLimit)
.Statistics(out stats)
// Skip the candidates examined by previous page requests
.Skip(offset)
// Return at most 'pageSize' results that passed the filter
.Take(pageSize)
.ToList();
// Process the current page here...
// Advance the offset by the results returned AND the results the filter rejected
offset += pagedResults.Count + (int)stats.SkippedResults;
}
// Continue if the page is full or the scan limit was reached, even after an empty page.
while (pagedResults.Count == pageSize ||
stats.ScannedResults == scanLimit);
const int pageSize = 10;
const int scanLimit = 100;
int offset = 0;
List<Order> pagedResults;
QueryStatistics stats;
do
{
pagedResults = await asyncSession.Advanced
.AsyncRawQuery<Order>(@"
from Orders
filter ShipTo.Country == $country
filter_limit $scanLimit")
.AddParameter("country", "USA")
.AddParameter("scanLimit", scanLimit)
.Statistics(out stats)
// Skip the candidates examined by previous page requests
.Skip(offset)
// Return at most 'pageSize' results that passed the filter
.Take(pageSize)
.ToListAsync();
// Process the current page here...
// Advance the offset by the results returned AND the results the filter rejected
offset += pagedResults.Count + (int)stats.SkippedResults;
}
// Continue if the page is full or the scan limit was reached, even after an empty page.
while (pagedResults.Count == pageSize ||
stats.ScannedResults == scanLimit);
// First request: skip 0 candidates, return up to 10 matches,
// and examine at most 100 candidates.
from Orders
filter ShipTo.Country == "USA"
limit 0, 10
filter_limit 100
// Next offset: current offset + results returned + SkippedResults.
// Request another page if 10 results were returned or ScannedResults is 100.
- Advance the offset using the same calculation as before: add the returned results and
stats.SkippedResults. - Continue paging if
pagedResults.Count == pageSizeorstats.ScannedResults == scanLimit.
More candidates may remain in either case, so another request is needed to find out. - Stop paging when the page is smaller than
pageSizeand fewer thanscanLimitcandidates were examined.
The remaining candidates have been exhausted.
For example, if all 100 examined candidates are rejected, the page is empty and both ScannedResults and SkippedResults are 100.
The next offset is the current offset + 100, and the loop requests another page.
Paging considerations
TotalResults and page counts:
-
Do not use
TotalResultsto calculate the page count.
Withfilter, it can be lower or higher than the total number of matching results. -
A full-collection query may report only the matches found before filtering stops,
while an index query may report the number of index matches beforefilteris applied.
Sharded databases:
Paging and query statistics behave differently.
See Filter and sharding and Sharding: Paging query results.
Distinct projections and multiple index entries per document: See Paging.
Filter and projections
Use a projection to choose which fields to return from results that pass the filter.
Filtering happens before projection, so the filter can reference fields that aren't returned.
In Map-Reduce queries, the filter condition is evaluated against the aggregation results before projection.
See Filter with a static Map-Reduce index and Filter with a dynamic group-by query.
The following query filters companies located in the USA and returns only Name and Phone for each match.
Address.Country is used by the filter but isn't returned.
This full-collection query does not create an auto-index.
The projected results are returned as instances of the following class:
public class CompanyDetails
{
public string Name { get; set; }
public string Phone { get; set; }
}
- Query
- Query_async
- DocumentQuery
- DocumentQuery_async
- RawQuery
- RawQuery_async
- RQL
List<CompanyDetails> companies = session
.Query<Company>()
// Filter by 'Address.Country'
.Filter(c => c.Address.Country == "USA")
// Project only 'Name' and 'Phone' -
// 'Address.Country' is not projected, but can still be used in 'Filter'
.Select(c => new CompanyDetails
{
Name = c.Name,
Phone = c.Phone
})
.ToList();
List<CompanyDetails> companies = await asyncSession
.Query<Company>()
// Filter by 'Address.Country'
.Filter(c => c.Address.Country == "USA")
// Project only 'Name' and 'Phone' -
// 'Address.Country' is not projected, but can still be used in 'Filter'
.Select(c => new CompanyDetails
{
Name = c.Name,
Phone = c.Phone
})
.ToListAsync();
List<CompanyDetails> companies = session.Advanced
.DocumentQuery<Company>()
// Filter by 'Address.Country'
.Filter(f => f.Equals(c => c.Address.Country, "USA"))
// Project the fields defined in 'CompanyDetails' ('Name' and 'Phone')
.SelectFields<CompanyDetails>()
.ToList();
List<CompanyDetails> companies = await asyncSession.Advanced
.AsyncDocumentQuery<Company>()
// Filter by 'Address.Country'
.Filter(f => f.Equals(c => c.Address.Country, "USA"))
// Project the fields defined in 'CompanyDetails' ('Name' and 'Phone')
.SelectFields<CompanyDetails>()
.ToListAsync();
List<CompanyDetails> companies = session.Advanced
.RawQuery<CompanyDetails>(@"
from Companies
filter Address.Country == $country
select Name, Phone")
.AddParameter("country", "USA")
.ToList();
List<CompanyDetails> companies = await asyncSession.Advanced
.AsyncRawQuery<CompanyDetails>(@"
from Companies
filter Address.Country == $country
select Name, Phone")
.AddParameter("country", "USA")
.ToListAsync();
from Companies
filter Address.Country == "USA"
select Name, Phone
Session tracking
Projected results are not tracked by the session.
This also applies to full document objects returned inside a projection.
Modifying projected objects and calling SaveChanges() or SaveChangesAsync() will not update the original documents.
Learn more in Projections overview.
Filter by the original document field names
Filtering happens before projection, so names introduced by the projection are unavailable to the filter.
For example, this query filters by Address.Country and returns that field under the name CountryName:
from Companies
filter Address.Country == "USA"
select Address.Country as CountryName
CountryName names a field in the projected output.
Using filter CountryName == "USA" would check for a field named CountryName in the original document.
If the document has no CountryName field, the comparison returns no matches without reporting an error.
Filter by a related document
Use the RQL load clause (RavenQuery.Load in LINQ) with filter
to return documents based on fields in a related document.
For each candidate, the server loads the related document before evaluating the filter condition.
Loading related documents adds work for each examined candidate.
Set filter_limit to cap the number of candidates examined.
See Limit the number of scanned results.
In the following example, each product stores its supplier's document ID in Supplier.
The query loads each product's supplier and returns products whose supplier is located in Japan.
The loaded supplier is used by the filter and isn't returned.
This full-collection query does not create an auto-index.
- Query
- Query_async
- DocumentQuery
- DocumentQuery_async
- RawQuery
- RawQuery_async
- RQL
using Raven.Client.Documents.Queries;
// Load the supplier referenced by each product.
var query =
from p in session.Query<Product>()
let s = RavenQuery.Load<Supplier>(p.Supplier)
select p;
List<Product> products = query
// Switch to DocumentQuery to filter by the loaded supplier.
.ToDocumentQuery()
// The "s." prefix must match the 'let' variable name.
.Filter(f => f.Equals("s.Address.Country", "Japan"))
.ToList();
using Raven.Client.Documents.Queries;
// Load the supplier referenced by each product.
var query =
from p in asyncSession.Query<Product>()
let s = RavenQuery.Load<Supplier>(p.Supplier)
select p;
List<Product> products = await query
// Switch to AsyncDocumentQuery to filter by the loaded supplier alias.
.ToAsyncDocumentQuery()
// The "s." prefix must match the 'let' variable name.
.Filter(f => f.Equals("s.Address.Country", "Japan"))
.ToListAsync();
using Raven.Client.Documents.Queries;
using Raven.Client.Documents.Session.Tokens;
// Configure the related supplier load.
// Empty field lists preserve the full product document as the result.
var queryData = new QueryData(
fields: Array.Empty<string>(),
projections: Array.Empty<string>(),
fromAlias: "p",
loadTokens: new List<LoadToken>
{
LoadToken.Create("p.Supplier", "s")
});
List<Product> products = session.Advanced
.DocumentQuery<Product>()
.SelectFields<Product>(queryData)
// Filter on the loaded supplier's country.
.Filter(f => f.Equals("s.Address.Country", "Japan"))
.ToList();
using Raven.Client.Documents.Queries;
using Raven.Client.Documents.Session.Tokens;
// Configure the related supplier load.
// Empty field lists preserve the full product document as the result.
var queryData = new QueryData(
fields: Array.Empty<string>(),
projections: Array.Empty<string>(),
fromAlias: "p",
loadTokens: new List<LoadToken>
{
LoadToken.Create("p.Supplier", "s")
});
List<Product> products = await asyncSession.Advanced
.AsyncDocumentQuery<Product>()
.SelectFields<Product>(queryData)
// Filter on the loaded supplier's country.
.Filter(f => f.Equals("s.Address.Country", "Japan"))
.ToListAsync();
List<Product> products = session.Advanced
.RawQuery<Product>(@"
from Products as p
load p.Supplier as s
filter s.Address.Country == $country")
.AddParameter("country", "Japan")
.ToList();
List<Product> products = await asyncSession.Advanced
.AsyncRawQuery<Product>(@"
from Products as p
load p.Supplier as s
filter s.Address.Country == $country")
.AddParameter("country", "Japan")
.ToListAsync();
from Products as p
load p.Supplier as s
filter s.Address.Country == "Japan"
Expected results:
On a non-sharded database with the unmodified sample data, 6 products match.
Sharded databases
On a sharded database, load can retrieve a related document only if it resides on the same shard as the candidate.
A related document on another shard is loaded as null.
For this example, if the supplier is missing or resides on another shard, s.Address.Country == "Japan" does not match,
so the product is skipped without an error.
Use document anchoring to keep related documents in the same bucket and shard.
See Sharding: Unsupported querying features.
Filter with a JavaScript function
Use RQL's declare keyword to define a JavaScript function and call it from filter.
The server calls the function for each candidate examined by the filter.
The function can return true to keep the candidate, or return a value for the filter condition to compare.
Run these queries with RawQuery or AsyncRawQuery, or execute the RQL directly in Studio.
Pass only the document
The following function receives only the product document and returns true when the units in stock plus the units on order are below ReorderLevel.
The query returns full Product documents that meet this condition; no query parameter is needed.
A function is needed here because arithmetic can't be written directly in a filter condition.
- RawQuery
- RawQuery_async
- RQL
List<Product> products = session.Advanced
.RawQuery<Product>(@"
declare function needsReorder(product) {
// Add two fields and compare the result with a third
return product.UnitsInStock + product.UnitsOnOrder < product.ReorderLevel;
}
from Products as p
filter needsReorder(p)")
.ToList();
List<Product> products = await asyncSession.Advanced
.AsyncRawQuery<Product>(@"
declare function needsReorder(product) {
// Add two fields and compare the result with a third
return product.UnitsInStock + product.UnitsOnOrder < product.ReorderLevel;
}
from Products as p
filter needsReorder(p)")
.ToListAsync();
declare function needsReorder(product) {
// Add two fields and compare the result with a third
return product.UnitsInStock + product.UnitsOnOrder < product.ReorderLevel;
}
from Products as p
filter needsReorder(p)
Expected results: With the unmodified sample data, 8 products match.
Return a boolean value
When a function call is used directly as the filter condition, as in filter needsReorder(p) above,
the function must return the boolean value true for the candidate to be included.
Truthy values such as 1 or "yes" do not include the candidate.
Compare a calculated value
A function can return a value for the filter condition to compare.
This allows calculations that cannot be written directly in an RQL filter expression, such as multiplication.
The following query returns products whose stock value (UnitsInStock * PricePerUnit) is greater than 1000:
- RawQuery
- RawQuery_async
- RQL
List<Product> products = session.Advanced
.RawQuery<Product>(@"
declare function stockValue(product) {
return product.UnitsInStock * product.PricePerUnit;
}
from Products as p
filter stockValue(p) > 1000")
.ToList();
List<Product> products = await asyncSession.Advanced
.AsyncRawQuery<Product>(@"
declare function stockValue(product) {
return product.UnitsInStock * product.PricePerUnit;
}
from Products as p
filter stockValue(p) > 1000")
.ToListAsync();
declare function stockValue(product) {
return product.UnitsInStock * product.PricePerUnit;
}
from Products as p
filter stockValue(p) > 1000
Expected results: With the unmodified sample data, 5 products match.
Pass a query parameter as an argument
-
The following query returns employees whose
Titlestarts with"Sales", such as "Sales Representative" or "Sales Manager".
The comparison uses JavaScript's case-sensitivestartsWithmethod.
RQL'sstartsWith()helper is case-insensitive infilter. See Supported operators and limitations. -
In the
RawQueryandAsyncRawQueryexamples,.AddParameter("prefix", "Sales")sets the RQL query parameter$prefixto"Sales".
The calltitleStartsWith(e, $prefix)passes that value to the JavaScript function'sprefixparameter.
- RawQuery
- RawQuery_async
- RQL
List<Employee> employees = session.Advanced
.RawQuery<Employee>(@"
declare function titleStartsWith(employee, prefix) {
// String.prototype.startsWith is case-sensitive
return employee.Title.startsWith(prefix);
}
from Employees as e
filter titleStartsWith(e, $prefix)")
.AddParameter("prefix", "Sales")
.ToList();
List<Employee> employees = await asyncSession.Advanced
.AsyncRawQuery<Employee>(@"
declare function titleStartsWith(employee, prefix) {
// String.prototype.startsWith is case-sensitive
return employee.Title.startsWith(prefix);
}
from Employees as e
filter titleStartsWith(e, $prefix)")
.AddParameter("prefix", "Sales")
.ToListAsync();
declare function titleStartsWith(employee, prefix) {
// String.prototype.startsWith is case-sensitive
return employee.Title.startsWith(prefix);
}
from Employees as e
filter titleStartsWith(e, $prefix)
Query parameters:
{ "prefix": "Sales" }
Access a query parameter inside the function
-
The following query also returns employees whose
Titlestarts with"Sales", using a case-sensitive comparison.
The function reads$prefixdirectly inside its body, so only the employee document is passed as an argument. -
In the
RawQueryandAsyncRawQueryexamples,.AddParameter("prefix", "Sales")is still required to set the RQL query parameter$prefixto"Sales".
In this example, omitting that parameter can return no matches without reporting an error.
- RawQuery
- RawQuery_async
- RQL
List<Employee> employees = session.Advanced
.RawQuery<Employee>(@"
declare function titleStartsWithPrefix(employee) {
// '$prefix' is the query parameter, accessed directly
return employee.Title.startsWith($prefix);
}
from Employees as e
filter titleStartsWithPrefix(e)")
.AddParameter("prefix", "Sales")
.ToList();
List<Employee> employees = await asyncSession.Advanced
.AsyncRawQuery<Employee>(@"
declare function titleStartsWithPrefix(employee) {
// '$prefix' is the query parameter, accessed directly
return employee.Title.startsWith($prefix);
}
from Employees as e
filter titleStartsWithPrefix(e)")
.AddParameter("prefix", "Sales")
.ToListAsync();
declare function titleStartsWithPrefix(employee) {
// '$prefix' is the query parameter, accessed directly
return employee.Title.startsWith($prefix);
}
from Employees as e
filter titleStartsWithPrefix(e)
Query parameters:
{ "prefix": "Sales" }
Declared function behavior
- A declared function can also be called from
select. - Declared functions cannot be called from
where. - An uncaught JavaScript exception in a declared function fails the whole query.
Filter and sharding
Document queries
Filtering and scan limits
-
Each shard applies
filterto its own candidates.
Whenfilter_limitis set and the paging offset is 0, it caps how many candidates each shard examines.
The total number examined across all shards can therefore exceed that limit. -
The orchestrator (the node coordinating the query) combines the shard results.
Whenfilter_limitis set, it returns at most the smaller of that limit and the page size. -
Example:
Assume the first 10 candidate orders on each of three shards matchFreight >= 0.
Withfrom Orders filter Freight >= 0 filter_limit 10, each shard examines 10 orders.
The combinedScannedResultsis 30, while the orchestrator returns only 10 results.
Query statistics
ScannedResultsis the sum of the candidates examined by the shards.SkippedResultsis reported as 0 and does not include candidates rejected by the filter on the shards.
Paging
For a query that returns full documents and uses filter and paging, with or without where,
but without order by, load, or filter_limit, the offset skips matching results in the merged result set.
Advance it by the number of results returned: nextOffset = currentOffset + returnedResults.Count.
Related documents
load finds a related document only if it resides on the same shard as the candidate.
See Filter by a related document.
Map-Reduce queries
For queries against static Map-Reduce indexes and dynamic group by queries,
the shards return partial aggregation results without applying filter.
The orchestrator combines and re-reduces those results, then applies filter to the combined aggregation results.
filter_limit caps how many combined aggregation results it examines.
-
For these Map-Reduce queries -
ScannedResultscounts the combined aggregation results examined byfilteron the orchestrator.
SkippedResultscounts those rejected by the filter. -
Use
filterfor conditions on computed aggregation fields, such asCount.
Awherecondition is applied at the shards and can discard partial values before they are combined. -
Use
whereon a reduce-key (grouping) field, such asCompany, to narrow the shard results first. -
Example:
In the Map-Reduce example, a company with 15 orders on each of two shards has a combinedCountof 30.
filter Count > 20includes that combined result.
where Count > 20discards both partial results before they can be combined.
Learn more in Sharding: Filtering query results.
Supported operators and limitations
Supported RQL expressions
The following expressions can be used in an RQL filter clause:
| Expression | Supported syntax |
|---|---|
| Comparisons | =, ==, !=, <>, <, <=, >, >= |
| Field-to-field comparisons | Comparing two document fields, such as UnitsInStock < ReorderLevel |
| Logical expressions | and, or, and negation with and not or or not; parentheses for grouping |
| Membership | in |
| Built-in methods | startsWith(), endsWith(), regex(), exists() |
| Document ID | id() for document queries |
| Related document fields | Fields from documents loaded with load |
| Custom logic | Calls to JavaScript functions defined with declare |
Quote string values
Write string literals in single or double quotes, for example:
filter Address.Country == "USA" or filter Address.Country == 'USA'.
An unquoted identifier such as USA is interpreted as a field name.
For example: filter Address.Country == USA compares the values of the Address.Country and USA fields
in the same document.
Unintended field comparisons and missing or misspelled field names can produce unexpected results,
including no matches, without reporting an error.
Negating the entire condition
Use true and not (...).
Starting the condition directly with not can return no results without reporting an error:
from Companies
filter true and not (Address.Country == "USA")
The LINQ and DocumentQuery Filter APIs handle this automatically. See API behavior.
String comparisons
| Expression | Case sensitivity |
|---|---|
RQL startsWith() and endsWith() helpers | Case-insensitive |
RQL regex() helper | Case-insensitive by default; inline regex options can change this. |
String equality and in comparisons in filter | Case-sensitive |
JavaScript's native someString.startsWith(...) and someString.endsWith(...) methods | Case-sensitive |
For strict equality and string ordering rules, see How exploration queries work.
Unsupported RQL expressions
These restrictions also apply when using RawQuery or AsyncRawQuery:
-
Index-based methods:
search(),boost(),lucene(),exact(),moreLikeThis(), spatial methods, and vector search
cannot be used inside a filter condition. -
Arithmetic:
Expressions such asUnitsInStock * PricePerUnitcannot be used directly in an RQLfiltercondition.
Compute the value in a declared function and compare its result. -
between:
This operator is not supported in a filter condition and can return no results without reporting an error.
Use two comparisons instead:from Productsfilter PricePerUnit >= 10 and PricePerUnit <= 20 -
now()andtoday():
These functions cannot be used inside a filter condition.
Compare against an explicit date-time value instead. Learn more in Filter by date and time: Restrictions.
LINQ and DocumentQuery APIs
-
The LINQ, DocumentQuery, and AsyncDocumentQuery
FilterAPIs support comparisons and logical expressions.
DocumentQuery and AsyncDocumentQuery use theIFilterFactorymethods listed in Syntax. -
Use
RawQueryorAsyncRawQueryfor supported RQL features that theseFilterAPIs do not expose. -
IFilterFactory<T>comparison methods compare a field with a value.
For example,f.LessThan("UnitsInStock", "ReorderLevel")comparesUnitsInStockwith the literal string"ReorderLevel".
To compare two document fields, useRawQueryorAsyncRawQuerywith a condition such asfilter UnitsInStock < ReorderLevel.
LINQ limitations
-
Unsupported methods and field comparisons:
LINQFilterdoes not support methods such asStartsWith,EndsWith,In,Regex.IsMatch,
ContainsAny,ContainsAll, orstring.Contains, or comparisons between two document fields
(for example,p.UnitsInStock < p.ReorderLevel). These expressions throw during query translation.To compare two document fields, use
RawQueryorAsyncRawQuerywith a condition such asfilter UnitsInStock < ReorderLevel.
For supported RQL helpers or custom logic, useRawQueryorAsyncRawQuery,
optionally with a declared JavaScript function. -
string.Length:
LINQFilterdoes not translatestring.Lengthto JavaScript'slengthproperty.
For example,Filter(c => c.Name.Length > 30)generatesfilter Name.Length > $p0,
so this comparison matches no results without reporting an error.
Usefilter Name.length > 30withRawQueryorAsyncRawQuery.
API behavior
-
Calling
.Search()on the query adds awhere search(...)condition; it does not add a filter condition. -
Calling LINQ
Filtermore than once combines the conditions withand. -
Negation in
Filteris handled by the client,
so the RQL pitfall described in Negating the entire condition does not apply. -
For a negated comparison such as
Filter(p => !(p.PricePerUnit > 10)),
LINQ generatesfilter (true and not (PricePerUnit > $p0)). -
In DocumentQuery and AsyncDocumentQuery, the RQL generated by starting the condition with
Not()
depends on what followsNot():DocumentQuery Generated RQL f.Not().Equals("Address.Country", "USA")filter Address.Country != $p0f.Not().GreaterThan("PricePerUnit", 10)filter exists(PricePerUnit) and not PricePerUnit > $p0f.Not().OpenSubclause() ... .CloseSubclause()filter true and not (...)The
exists(...)form excludes documents that don't have the field.
Query and operation restrictions
The following queries and operations cannot include a filter clause:
-
Faceted search:
A faceted search query withfilterthrows anInvalidQueryException. -
Vector search:
A query that usesvector.search()inwherecannot also includefilter. -
Patch by query and delete by query:
Usewhereto select documents for patch by query and delete by query operations.
Syntax
-
Filteradds a condition to the query.
The query executes when results are requested, for example withToList()orToListAsync(). -
For the RQL clause order, see the outline in How exploration queries work.
LINQ
Filter is an extension method in Raven.Client.Documents.LinqExtensions.
The IQueryable<T> overload lets you call Filter after standard LINQ operators such as GroupBy:
public static IRavenQueryable<T> Filter<T>(
this IRavenQueryable<T> source,
Expression<Func<T, bool>> predicate,
int limit = int.MaxValue);
public static IRavenQueryable<T> Filter<T>(
this IQueryable<T> source,
Expression<Func<T, bool>> predicate,
int limit = int.MaxValue);
DocumentQuery and AsyncDocumentQuery
IDocumentQuery<T> Filter(Action<IFilterFactory<T>> builder, int limit = int.MaxValue);
IAsyncDocumentQuery<T> Filter(Action<IFilterFactory<T>> builder, int limit = int.MaxValue);
// After GroupBy (dynamic group-by query)
IGroupByDocumentQuery<T> Filter(Action<IFilterFactory<T>> builder, int limit = int.MaxValue);
IAsyncGroupByDocumentQuery<T> Filter(Action<IFilterFactory<T>> builder, int limit = int.MaxValue);
The builder action runs on the client and uses IFilterFactory<T> (in Raven.Client.Documents.Queries) to construct the filter condition.
The server evaluates the generated condition for each examined candidate.
Filter parameters
| Parameter | Type | Description |
|---|---|---|
| source | IRavenQueryable<T> / IQueryable<T> | RavenDB LINQ query to which the filter is added. |
| predicate | Expression<Func<T, bool>> | LINQ expression translated into a filter condition that the server evaluates for each examined candidate. |
| builder | Action<IFilterFactory<T>> | Constructs the filter condition for DocumentQuery, AsyncDocumentQuery, or a group-by query. |
| limit | int | Maximum number of candidate results examined, including rejected candidates. Must be greater than 0. Default: int.MaxValue. |
Scan limit
limit corresponds to RQL's filter_limit.
It does not set the maximum number of matching results returned.
The default value, int.MaxValue, sends no filter_limit.
Scanning can still stop when the page is full or candidates are exhausted.
Learn more in Limit the number of scanned results and Filter and paging.
For sharded queries, see Filter and sharding.
Filter builder methods
The IFilterFactory<T> interface provides the following comparison, logical, and grouping methods:
public interface IFilterFactory<T>
{
// Equality
IFilterFactory<T> Equals(string fieldName, object value);
IFilterFactory<T> Equals<TValue>(Expression<Func<T, object>> propertySelector,
TValue value);
IFilterFactory<T> NotEquals(string fieldName, object value);
IFilterFactory<T> NotEquals<TValue>(Expression<Func<T, object>> propertySelector,
TValue value);
// Comparison
IFilterFactory<T> GreaterThan(string fieldName, object value);
IFilterFactory<T> GreaterThan<TValue>(Expression<Func<T, object>> propertySelector,
TValue value);
IFilterFactory<T> GreaterThanOrEqual(string fieldName, object value);
IFilterFactory<T> GreaterThanOrEqual<TValue>(Expression<Func<T, object>> propertySelector,
TValue value);
IFilterFactory<T> LessThan(string fieldName, object value);
IFilterFactory<T> LessThan<TValue>(Expression<Func<T, object>> propertySelector,
TValue value);
IFilterFactory<T> LessThanOrEqual(string fieldName, object value);
IFilterFactory<T> LessThanOrEqual<TValue>(Expression<Func<T, object>> propertySelector,
TValue value);
// Logical operators and grouping
IFilterFactory<T> AndAlso();
IFilterFactory<T> OrElse();
IFilterFactory<T> Not();
IFilterFactory<T> OpenSubclause();
IFilterFactory<T> CloseSubclause();
// Overloads that accept 'MethodCall' and 'WhereParams' are omitted for brevity
}
Builder method parameters
| Parameter | Type | Description |
|---|---|---|
| fieldName | string | Document field or reduce result field to compare. Use a dotted path for nested fields, such as "Address.Country". |
| propertySelector | Expression<Func<T, object>> | Lambda expression selecting the field to compare. |
| value | object / TValue | Value to compare against. |