Skip to main content

Exploration Queries

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:

    1. 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 the from and where clauses.
      The retrieved results are the candidate results for filtering.
      If sorting is specified, it determines the order in which the filter examines them.

    2. 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:

  • 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_limit in 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 where clause.
      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:

    • filter comes after group by, where, order by, and load, and before select and include.
      limit and filter_limit come last: limit controls paging, and filter_limit caps 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 results
      where ... // Optional: narrow the candidate results
      order by ... // Optional: sort candidates before filtering
      load ... // Optional: load related documents for 'filter'
      filter <condition> // Evaluated per candidate, without using an index
      select ... // Optional: projection
      include ... // Optional: send related documents to the client with the results
      limit <offset>, <pageSize> // Optional: paging
      filter_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:

    • ScannedResults counts the candidates actually examined by the filter.
    • SkippedResults includes 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 filter when you need to evaluate a condition on fields that aren't indexed.
    Using where for the same condition has these implications:

    • In a static-index query, where can use only the index fields.
      A where condition on any other field throws an error.
    • In a dynamic query, a where condition on a new field makes RavenDB create an auto-index that includes it.

    Using filter avoids these indexing requirements because it evaluates the condition directly against the retrieved results.

  • Use filter when the required condition cannot be expressed as an ordinary RQL where comparison,
    for example:

  • On a sharded database, use filter when the condition applies to an aggregated value of a Map-Reduce or group by query, such as Count. filter evaluates the combined results, while where evaluates 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 filter would otherwise need to scan a large dataset.
    The cost of filter grows with the number of results it examines.

where vs filter:​

Featurewherefilter
Evaluated againstAn index, for ordinary field conditionsA document or aggregation result
Index usageUses 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
WorkUses indexed fields to find matchesExamines results individually, until the page is full, filter_limit is reached, or results are exhausted
String comparisonCase-insensitive by defaultCase-sensitive
Typical useRecurring queriesAd-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:

FeaturePurposeEffect on query execution
Disabling auto-index creationPrevent 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.

QueryResult
from Products where UnitsInStock > 10❌ Fails
where needs an auto-index, and creating one is disabled.
from Products filter UnitsInStock > 10✅ Runs
filter scans the Products documents. No index is needed.

Use them together​

  • Disable auto-index creation to protect the database from unplanned indexes,
    and use filter to explore data that no index covers.

  • filter doesn't exempt the rest of the query:
    Conditions on ordinary document fields in where, or sorting by document fields with order by,
    still require an auto-index in a collection query, so the settings still apply.


Where to disable auto-index creation​

SettingApplies toEffect
Studio:
Disable creating new Auto-Indexes
Queries and patches run from the Studio, per databaseQueries 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 filter with 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 evaluate where conditions 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.
  • For queries on Map-Reduce indexes and dynamic group by queries,
    filter evaluates 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, filter applies 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, filter examines 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 full Company document.
    No page size or filter_limit is set, so the filter examines the entire collection:

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();

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.

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 a where condition on document fields other than just the document ID, an order by clause 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 by queries use an auto Map-Reduce index.
    See Filter with a dynamic group-by query.

  • Narrow the results with where first: only results matching that where condition are examined by filter.
    The fields referenced in filter are not added to the auto-index.

  • The following query returns full Company documents that match both conditions:

    • where: Contact.Title equals "Sales Representative" (case-insensitive).
    • filter: Address.Country equals "Germany" (case-sensitive).
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();

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, where evaluates its condition against the index-fields,
    while filter evaluates its condition against the original documents.
    The filter condition can therefore reference document fields that aren't included in the index.

  • filter cannot see fields that exist only in the index, even if they are stored.
    For example, if an index computes StockValue = UnitsInStock * PricePerUnit and the documents have no StockValue field, filter StockValue > 1000 returns no matches without reporting an error.

  • For example, create and deploy the following index, which indexes only the product's Category field:

    public class Products_ByCategory : AbstractIndexCreationTask<Product>
    {
    public class IndexEntry
    {
    // The index field
    public string Category { get; set; }
    }

    public Products_ByCategory()
    {
    Map = products => from product in products
    select new IndexEntry
    {
    Category = product.Category
    };
    }
    }

  • Query the index for beverages (categories/1-A), then filter the retrieved documents to those whose PricePerUnit is greater than 20.
    PricePerUnit is not indexed by this index, so a where condition on it would fail.

    Each matching result is a full Product document.
    The query uses the specified static index. No auto-index is created:

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();

Why use OfType<Product>() before Filter?​

  • The Query call uses Products_ByCategory.IndexEntry as the query’s initial result type.
    The Where lambda can therefore reference properties defined by IndexEntry, such as Category.

  • OfType<Product>() switches the query type to Product before Filter,
    so the Filter lambda can reference document fields such as PricePerUnit,
    and the results are returned as Product.

    A Filter expression that references PricePerUnit would not compile before OfType<Product>(),
    because IndexEntry does not define that property.

  • OfType changes only the C# type, not the RQL sent to the server.
    On the server, filter evaluates 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 filter condition is evaluated against the aggregation results,
    so it references the reduce result fields rather than the original documents.
    The same applies to dynamic group by queries.

  • 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.

List<OrdersByCompanyResult> companies = session
.Query<OrdersByCompanyResult>("Orders/ByCompany", isMapReduce: true)
// 'Filter' is evaluated against each aggregation result.
.Filter(r => r.Count > 20)
.ToList();

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.

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();

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() in select tells RavenDB to include a Count field in the auto Map-Reduce index.
    The filter clause reads this field before select projects the results.

    For example, with select Company, count() as NumOrders:

    ExpressionBehavior
    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 inside filter.
  • LINQ: Call Filter before Select:

    Call Filter after GroupBy and before Select, using g.Count() in the predicate.
    The client translates g.Count() to the aggregation result field Count.

    If Select renames the count to NumOrders, a later .Filter(x => x.NumOrders > 20) generates RQL that checks NumOrders.
    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 limit argument of Filter (LINQ and DocumentQuery), or filter_limit in RQL,
    to specify the maximum number of candidate results the filter examines.
    By default, no filter_limit is 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_limit applies to the candidates that match where.


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 resultCountryExamined by filterReturned
Employee 1USAYesYes
Employee 2PolandYesNo
Employee 3USANo: limit reachedNo

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.ScannedResults reports the number of examined candidates
  • orders.Count reports the number of returned matches.
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.

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.
    Use OrderBy / OrderByDescending in LINQ and DocumentQuery, or order by in 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 OrderBy before or after Filter does not change the execution order.
    The client generates RQL with order by before filter.

  • 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.

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();

Expected results:

  • With the unmodified sample data, 2 of the 50 examined orders match: orders/112-A and orders/809-A.
  • Auto-index used:
    An auto-index covering Freight, such as Auto/Orders/ByFreight.
    The ShipTo.Country field used by filter does 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 Take to set the maximum number of matching results per page.
  • Use Skip to 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:

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);

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:

CandidateCountryFirst-page outcome
Order 1USAReturned
Order 2PolandRejected by the filter
Order 3USAReturned; the page is full
Order 4USANot 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:

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);
  • Advance the offset using the same calculation as before: add the returned results and stats.SkippedResults.
  • Continue paging if pagedResults.Count == pageSize or stats.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 pageSize and fewer than scanLimit candidates 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 TotalResults to calculate the page count.
    With filter, 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 before filter is 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; }
}

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();

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.

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.

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();

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.

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();

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:

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();

Expected results: With the unmodified sample data, 5 products match.

Pass a query parameter as an argument​

  • The following query returns employees whose Title starts with "Sales", such as "Sales Representative" or "Sales Manager".
    The comparison uses JavaScript's case-sensitive startsWith method.
    RQL's startsWith() helper is case-insensitive in filter. See Supported operators and limitations.

  • In the RawQuery and AsyncRawQuery examples, .AddParameter("prefix", "Sales") sets the RQL query parameter $prefix to "Sales".
    The call titleStartsWith(e, $prefix) passes that value to the JavaScript function's prefix parameter.

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();

Access a query parameter inside the function​

  • The following query also returns employees whose Title starts with "Sales", using a case-sensitive comparison.
    The function reads $prefix directly inside its body, so only the employee document is passed as an argument.

  • In the RawQuery and AsyncRawQuery examples, .AddParameter("prefix", "Sales") is still required to set the RQL query parameter $prefix to "Sales".
    In this example, omitting that parameter can return no matches without reporting an error.

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();

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 filter to its own candidates.
    When filter_limit is 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.
    When filter_limit is 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 match Freight >= 0.
    With from Orders filter Freight >= 0 filter_limit 10, each shard examines 10 orders.
    The combined ScannedResults is 30, while the orchestrator returns only 10 results.


Query statistics​

  • ScannedResults is the sum of the candidates examined by the shards.
  • SkippedResults is 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.


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 -
    ScannedResults counts the combined aggregation results examined by filter on the orchestrator.
    SkippedResults counts those rejected by the filter.

  • Use filter for conditions on computed aggregation fields, such as Count.
    A where condition is applied at the shards and can discard partial values before they are combined.

  • Use where on a reduce-key (grouping) field, such as Company, to narrow the shard results first.

  • Example:
    In the Map-Reduce example, a company with 15 orders on each of two shards has a combined Count of 30.
    filter Count > 20 includes that combined result.
    where Count > 20 discards 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:

ExpressionSupported syntax
Comparisons=, ==, !=, <>, <, <=, >, >=
Field-to-field comparisonsComparing two document fields, such as UnitsInStock < ReorderLevel
Logical expressionsand, or, and negation with and not or or not; parentheses for grouping
Membershipin
Built-in methodsstartsWith(), endsWith(), regex(), exists()
Document IDid() for document queries
Related document fieldsFields from documents loaded with load
Custom logicCalls 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​

ExpressionCase sensitivity
RQL startsWith() and endsWith() helpersCase-insensitive
RQL regex() helperCase-insensitive by default; inline regex options can change this.
String equality and in comparisons in filterCase-sensitive
JavaScript's native someString.startsWith(...) and someString.endsWith(...) methodsCase-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 as UnitsInStock * PricePerUnit cannot be used directly in an RQL filter condition.
    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 Products
    filter PricePerUnit >= 10 and PricePerUnit <= 20
  • now() and today():
    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 Filter APIs support comparisons and logical expressions.
    DocumentQuery and AsyncDocumentQuery use the IFilterFactory methods listed in Syntax.

  • Use RawQuery or AsyncRawQuery for supported RQL features that these Filter APIs do not expose.

  • IFilterFactory<T> comparison methods compare a field with a value.
    For example, f.LessThan("UnitsInStock", "ReorderLevel") compares UnitsInStock with the literal string "ReorderLevel".
    To compare two document fields, use RawQuery or AsyncRawQuery with a condition such as filter UnitsInStock < ReorderLevel.


LINQ limitations​

  • Unsupported methods and field comparisons:
    LINQ Filter does not support methods such as StartsWith, EndsWith, In, Regex.IsMatch,
    ContainsAny, ContainsAll, or string.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 RawQuery or AsyncRawQuery with a condition such as filter UnitsInStock < ReorderLevel.
    For supported RQL helpers or custom logic, use RawQuery or AsyncRawQuery,
    optionally with a declared JavaScript function.

  • string.Length:
    LINQ Filter does not translate string.Length to JavaScript's length property.
    For example, Filter(c => c.Name.Length > 30) generates filter Name.Length > $p0,
    so this comparison matches no results without reporting an error.
    Use filter Name.length > 30 with RawQuery or AsyncRawQuery.


API behavior​

  • Calling .Search() on the query adds a where search(...) condition; it does not add a filter condition.

  • Calling LINQ Filter more than once combines the conditions with and.

  • Negation in Filter is 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 generates filter (true and not (PricePerUnit > $p0)).

  • In DocumentQuery and AsyncDocumentQuery, the RQL generated by starting the condition with Not()
    depends on what follows Not():

    DocumentQueryGenerated RQL
    f.Not().Equals("Address.Country", "USA")filter Address.Country != $p0
    f.Not().GreaterThan("PricePerUnit", 10)filter exists(PricePerUnit) and not PricePerUnit > $p0
    f.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 with filter throws an InvalidQueryException.

  • Vector search:
    A query that uses vector.search() in where cannot also include filter.

  • Patch by query and delete by query:
    Use where to select documents for patch by query and delete by query operations.

Syntax​

  • Filter adds a condition to the query.
    The query executes when results are requested, for example with ToList() or ToListAsync().

  • 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​

ParameterTypeDescription
sourceIRavenQueryable<T> / IQueryable<T>RavenDB LINQ query to which the filter is added.
predicateExpression<Func<T, bool>>LINQ expression translated into a filter condition that the server evaluates for each examined candidate.
builderAction<IFilterFactory<T>>Constructs the filter condition for DocumentQuery, AsyncDocumentQuery, or a group-by query.
limitintMaximum 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​

ParameterTypeDescription
fieldNamestringDocument field or reduce result field to compare. Use a dotted path for nested fields, such as "Address.Country".
propertySelectorExpression<Func<T, object>>Lambda expression selecting the field to compare.
valueobject / TValueValue to compare against.

In this article