Query Overview
-
Queries in RavenDB can be written with either of the following:
- LINQ - when querying with the session's
Querymethod. - Low-level API - when querying with the session's
DocumentQuerymethod. - RQL:
- when querying with the session's
RawQuerymethod. - when querying from the Query view in Studio.
- when querying with the session's
- LINQ - when querying with the session's
-
Queries defined with
QueryorDocumentQueryare translated by the RavenDB client to RQL when sent to the server. -
All queries in RavenDB use an index to provide results, even when you don't specify one.
Learn more below in Queries always provide results using an index. -
Queries that do Not specify which index to use are called Dynamic Queries.
This article displays examples of dynamic queries only.
For examples showing how to query an index see querying an index. -
The entities returned by the query are 'loaded' and tracked by the Session.
Entities will Not be tracked when:- Query returns a projection
- Tracking is disabled
-
Query results are cached by default. To disable query caching see NoCaching.
-
Queries are timed out after a configurable time period. See query timeout.
Queries always provide results using an index
-
Indexes let RavenDB return query results without scanning the entire dataset each and every time.
Queries always use an index to provide fast results regardless of the size of your data. -
When a query reaches a RavenDB instance, the instance calls its query optimizer to analyze the query
and determine which index should be used to retrieve the requested data. -
Learn more about indexes, their general concept, and the different index types in this indexes overview article.
-
You can choose the underlying search engine (Lucene or Corax) that RavenDB indexes use.
Learn more in selecting the search engine.
We differentiate between the following 3 query scenarios:
- Query a specific index - uses the index you specify (typically a static index).
- Query a collection - using an auto-index - uses an existing or newly created auto-index.
- Query a collection - query full collection | query by ID - reads directly from collection storage.
1. Query a specific index
Query type: Index query
Index used: The specified index (typically a static-index)
-
Static indexes are defined by the user, as opposed to auto-indexes, which the server creates to serve dynamic queries. Learn more in Auto indexes -vs- Static indexes.
To query a specific index, specify the index in the query. -
Example RQL:
from index "Employees/ByFirstName" where FirstName == "Laura"
See more examples in querying an index.
2. Query a collection - using an auto-index
Query type: Dynamic Query
Index used: Auto-index
When an auto-index is used
-
The query optimizer looks for a suitable AUTO-index when a dynamic query includes one or more of the following:
- A
wherecondition on fields other than the document ID,
or an ID condition not listed in Query by document ID. - An
order byclause to sort the results. - A
group byclause to group the results. - A
suggest()call in theselectclause to request term suggestions.
- A
How RavenDB selects or creates an auto-index
-
If a suitable auto-index (Not a static one...) already exists, RavenDB uses it to retrieve the results.
An auto-index is suitable when:- For queries without grouping -
it supports the fields and operations used inwhere,order by, andsuggest(). - For queries with
group by-
it is a map-reduce index that groups by exactly the fields in the query'sgroup byclause
and computes every aggregation the query selects (for example,count()orsum(Freight)).
- For queries without grouping -
-
Else, if no relevant auto-index is found, the query optimizer will create a new auto-index with fields that match the query criteria. At this time, and only at this time, the query waits for the new auto-index to finish indexing,
for up to 15 seconds (60 seconds for a streaming query), unless the query sets its own wait timeout with WaitForNonStaleResults.
If indexing is not done by then, the query returns the results indexed so far, marked as stale.
Subsequent queries that target this auto-index will be served immediately. -
The query optimizer may also create a new auto-index that combines the fields of an existing auto-index with any additional fields needed by the query.
Auto map-reduce indexes are merged this way only when their grouping keys are the same. -
Once the newly created auto-index is done indexing the data,
the old auto-index is removed in favor of the new one. -
Over time, an optimal set of indexes is generated by the query optimizer to answer your queries.
Query examples
-
Field filtering (
where)
Example RQL:from Employees where FirstName == "Laura"
See more examples in Session.Query below. -
Sorting without a
wherecondition
Sorting alone is enough to require an auto-index.
A query that has anorder byclause but nowherecondition is served by an auto-index, not by the raw collection. This applies to anyorder byclause, includingorder by id()andorder by random().Example RQL:
from Employees order by FirstName
If the Employees collection has no auto-index yet, this query creates theAuto/Employees/ByFirstNameauto-index. See more examples in Sort query results. -
Grouping (
group by)
Grouping alone is enough to require an auto map-reduce index, even without awhereororder byclause.Example RQL:
from Orders group by Company select count()
If no suitable auto map-reduce index already exists, this query creates theAuto/Orders/ByCountReducedByCompanyindex. See How to perform group by query. -
Term suggestions (
suggest())
Requesting term suggestions also requires an auto-index, even without awhereororder byclause.Example RQL:
from Products select suggest(Name, "chaig")
If no suitable auto-index already exists, this query creates theAuto/Products/BySuggest(Name)auto-index, with suggestions enabled forName.
See How to work with suggestions.
Exceptions and special cases
-
Counters and time series
Dynamic queries on counters and time series values don't create auto-indexes.
However, a static-index can be defined on Time series and Counters. -
The RQL
filterclause
The RQLfilterclause does not itself require or create an auto-index.
For example,from Employees filter FirstName == "Laura"reads from the raw collection and filters the documents on the server. Other clauses in the same query can still require an auto-index.
Learn more in Exploration queries.
3. Query a collection - query full collection | query by ID
Query type: Full collection Query
Index used: The raw collection (internal storage indexes)
Full collection query:
-
When querying a collection without specifying an index, with no
where,filter,order by, orgroup byclause and nosuggest()call, all documents from the specified collection are returned. -
RavenDB uses the raw collection documents in its internal storage indexes as the source for this query.
No auto-index is created. -
Example RQL:
from Employees
Query by document ID:
-
When querying a collection without specifying an index, these simple ID lookups can be served directly from collection storage:
id() = ...(orid() == ...) to look up one document.id() in (...)to look up a set of document IDs.startsWith(id(), ...)to look up documents whose IDs have a given prefix.
No auto-index is created when these simple ID lookups are used without sorting (
order by),
grouping (group by), or asuggest()call.Other RQL conditions on
id(), such as!=, ranges, or ID conditions combined withandoror,
require an auto-index.
To look up several documents by ID, useid() in (...)rather thanid() = ... or id() = .... -
On the server side, this type of query opens a single read transaction and extracts the documents directly from the raw collection storage. No search engine index (Lucene or Corax) is involved in this process.
-
Example RQL:
from Employees where id() == "employees/1-A"
See more examples below.
Session.Query
-
The simplest way to issue a query is by using the session's
Querymethod which supports LINQ.
Both the LINQ method syntax and the LINQ query syntax are supported. -
The following examples show dynamic queries that do not specify which index to use.
Please refer to querying an index for other examples. -
Querying can be enhanced using these extension methods.
Examples:
Query the full collection
- Method-syntax
- Method-syntax_async
- Query-syntax
- Query-syntax_async
- RQL
// This is a Full Collection Query
// No auto-index is created since no conditions, sorting, or grouping are applied
List<Employee> allEmployees = session
.Query<Employee>() // Query for all documents from 'Employees' collection
.ToList(); // Execute the query
// All 'Employee' entities are loaded and will be tracked by the session
// This is a Full Collection Query
// No auto-index is created since no conditions, sorting, or grouping are applied
List<Employee> allEmployees = await asyncSession
.Query<Employee>() // Query for all documents from 'Employees' collection
.ToListAsync(); // Execute the query
// All 'Employee' entities are loaded and will be tracked by the session
// This is a Full Collection Query
// No auto-index is created since no conditions, sorting, or grouping are applied
// Query for all documents from 'Employees' collection
IRavenQueryable<Employee> query = from employee in session.Query<Employee>()
select employee;
// Execute the query
List<Employee> allEmployees = query.ToList();
// All 'Employee' entities are loaded and will be tracked by the session
// This is a Full Collection Query
// No auto-index is created since no conditions, sorting, or grouping are applied
// Query for all documents from 'Employees' collection
IRavenQueryable<Employee> query = from employee in asyncSession.Query<Employee>()
select employee;
// Execute the query
List<Employee> allEmployees = await query.ToListAsync();
// All 'Employee' entities are loaded and will be tracked by the session
// This RQL is a Full Collection Query
// No auto-index is created since no conditions, sorting, or grouping are applied
from "Employees"
Query a collection by ID
- Method-syntax
- Method-syntax_async
- Query-syntax
- Query-syntax_async
- RQL
// Query collection by document ID
// No auto-index is created when querying only by ID
Employee employee = session
.Query<Employee>()
// Query for specific document from 'Employees' collection
.Where(x => x.Id == "employees/1-A")
// Execute the query
.FirstOrDefault();
// The resulting 'Employee' entity is loaded and will be tracked by the session
// Query collection by document ID
// No auto-index is created when querying only by ID
Employee employee = await asyncSession
.Query<Employee>()
// Query for specific document from 'Employees' collection
.Where(x => x.Id == "employees/1-A")
// Execute the query
.FirstOrDefaultAsync();
// The resulting 'Employee' entity is loaded and will be tracked by the session
// Query collection by document ID
// No auto-index is created when querying only by ID
// Query for specific document from 'Employees' collection
IRavenQueryable<Employee> query = from employee in session.Query<Employee>()
where employee.Id == "employees/1-A"
select employee;
// Execute the query
Employee employeeResult = query.FirstOrDefault();
// The resulting 'Employee' entity is loaded and will be tracked by the session
// Query collection by document ID
// No auto-index is created when querying only by ID
// Query for specific document from 'Employees' collection
IRavenQueryable<Employee> query = from employee in asyncSession.Query<Employee>()
where employee.Id == "employees/1-A"
select employee;
// Execute the query
Employee employeeResult = await query.FirstOrDefaultAsync();
// The resulting 'Employee' entity is loaded and will be tracked by the session
// This RQL queries the 'Employees' collection by ID
// No auto-index is created when querying only by ID
from "Employees" where id() == "employees/1-A"
Query a collection by a field value (where)
- Method-syntax
- Method-syntax_async
- Query-syntax
- Query-syntax_async
- RQL
// Query a collection by a field value
// An auto-index will be created if there isn't already an existing auto-index
// that indexes this document field
List<Employee> employees = session
.Query<Employee>()
// Query for all 'Employee' documents that match this predicate
.Where(x => x.FirstName == "Robert")
// Execute the query
.ToList();
// The resulting 'Employee' entities are loaded and will be tracked by the session
// Query a collection by a field value
// An auto-index will be created if there isn't already an existing auto-index
// that indexes this document field
List<Employee> employees = await asyncSession
.Query<Employee>()
// Query for all 'Employee' documents that match this predicate
.Where(x => x.FirstName == "Robert")
// Execute the query
.ToListAsync();
// The resulting 'Employee' entities are loaded and will be tracked by the session
// Query a collection by a field value
// An auto-index will be created if there isn't already an existing auto-index
// that indexes this document field
// Query for all 'Employee' documents that match the requested predicate
IRavenQueryable<Employee> query = from employee in session.Query<Employee>()
where employee.FirstName == "Robert"
select employee;
// Execute the query
List<Employee> employees = query.ToList();
// The resulting 'Employee' entities are loaded and will be tracked by the session
// Query a collection by a field value
// An auto-index will be created if there isn't already an existing auto-index
// that indexes this document field
// Query for all 'Employee' documents that match the requested predicate
IRavenQueryable<Employee> query = from employee in asyncSession.Query<Employee>()
where employee.FirstName == "Robert"
select employee;
// Execute the query
List<Employee> employees = await query.ToListAsync();
// The resulting 'Employee' entities are loaded and will be tracked by the session
// Query a collection by a field value
// An auto-index will be created if there isn't already an existing auto-index
// that indexes the requested field
from "Employees" where FirstName == "Robert"
Query a collection with paging
- Method-syntax
- Method-syntax_async
- Query-syntax
- Query-syntax_async
- RQL
// Query a collection with paging
// No auto-index is created since no conditions, sorting, or grouping are applied
List<Product> products = session
.Query<Product>()
.Skip(5) // Skip first 5 results
.Take(10) // Load up to 10 entities from 'Products' collection
.ToList(); // Execute the query
// The resulting 'Product' entities are loaded and will be tracked by the session
// Query a collection with paging
// No auto-index is created since no conditions, sorting, or grouping are applied
List<Product> products = await asyncSession
.Query<Product>()
.Skip(5) // Skip first 5 results
.Take(10) // Load up to 10 entities from 'Products' collection
.ToListAsync(); // Execute the query
// The resulting 'Product' entities are loaded and will be tracked by the session
// Query a collection with paging
// No auto-index is created since no conditions, sorting, or grouping are applied
IRavenQueryable<Product> query =
(from product in session.Query<Product>()
select product)
.Skip(5) // Skip first 5 results
.Take(10); // Load up to 10 entities from 'Products' collection
// Execute the query
List<Product> products = query.ToList();
// The resulting 'Product' entities are loaded and will be tracked by the session
// Query a collection with paging
// No auto-index is created since no conditions, sorting, or grouping are applied
IRavenQueryable<Product> query =
(from product in asyncSession.Query<Product>()
select product)
.Skip(5) // Skip first 5 results
.Take(10); // Load up to 10 entities from 'Products' collection
// Execute the query
List<Product> products = await query.ToListAsync();
// The resulting 'Product' entities are loaded and will be tracked by the session
// Query a collection with paging
// No auto-index is created since no conditions, sorting, or grouping are applied
from "Products" limit 5, 10 // skip 5, take 10
- By default, if the page size is not specified, all matching records will be retrieved from the database.
Session.Advanced.DocumentQuery
-
DocumentQueryprovides a full spectrum of low-level querying capabilities,
giving you more flexibility and control when making complex queries. -
Below is a simple DocumentQuery usage.
For a full description and more examples see:
Example:
- DocumentQuery
- DocumentQuery_async
- RQL
// Query with DocumentQuery - by a field value
// An auto-index will be created if there isn't already an existing auto-index
// that indexes this document field
List<Employee> employees = session
// Use DocumentQuery
.Advanced.DocumentQuery<Employee>()
// Query for all 'Employee' documents that match this predicate
.WhereEquals(x => x.FirstName, "Robert")
// Execute the query
.ToList();
// The resulting 'Employee' entities are loaded and will be tracked by the session
// Query with DocumentQuery - by a field value
// An auto-index will be created if there isn't already an existing auto-index
// that indexes this document field
List<Employee> employees = await asyncSession
// Use AsyncDocumentQuery
.Advanced.AsyncDocumentQuery<Employee>()
// Query for all 'Employee' documents that match this predicate
.WhereEquals(x => x.FirstName, "Robert")
// Execute the query
.ToListAsync();
// The resulting 'Employee' entities are loaded and will be tracked by the session
// Query a collection by a field value
// An auto-index will be created if there isn't already an existing auto-index
// that indexes the requested field
from "Employees" where FirstName = "Robert"
Session.Advanced.RawQuery
-
Queries defined with Query or DocumentQuery are translated by the RavenDB client to RQL
when sent to the server. -
The session also gives you a way to express the query directly in RQL using the
RawQuerymethod.
Example:
- RawQuery
- RawQuery_async
// Query with RawQuery - by a field value
// An auto-index will be created if there isn't already an existing auto-index
// that indexes this document field
List<Employee> employees = session
// Provide RQL to RawQuery
.Advanced.RawQuery<Employee>("from 'Employees' where FirstName = 'Robert'")
// Execute the query
.ToList();
// The resulting 'Employee' entities are loaded and will be tracked by the session
// Query with RawQuery - by a field value
// An auto-index will be created if there isn't already an existing auto-index
// that indexes this document field
List<Employee> employees = await asyncSession
// Provide RQL to AsyncRawQuery
.Advanced.AsyncRawQuery<Employee>("from 'Employees' where FirstName = 'Robert'")
// Execute the query
.ToListAsync();
// The resulting 'Employee' entities are loaded and will be tracked by the session
Custom methods and extensions for LINQ
-
Available custom methods and extensions for the session's Query method:
- AggregateBy
- AnyAsync
- Count
- CountLazily
- Customize
- FirstAsync
- FirstOrDefaultAsync
- GroupByArrayValues
- GroupByArrayContent
- Highlight
- Include
- Intersect
- Lazily
- LazilyAsync
- LongCount
- MoreLikeThis
- OfType
- OrderByDistance
- OrderByDistanceDescending
- OrderByScore
- OrderByScoreDescending
- ProjectInto
- Search
- SingleAsync
- SingleOrDefaultAsync
- Spatial
- Statistics
- SuggestUsing
- ToListAsync
- ToArrayAsync
- VectorSearch
- The available methods for the session's DocumentQuery method are listed in Custom methods and extensions.
Syntax
// Overloads for querying a collection OR an index:
// ================================================
IRavenQueryable<T> Query<T>(string indexName = null,
string collectionName = null, bool isMapReduce = false);
IDocumentQuery<T> DocumentQuery<T>(string indexName = null,
string collectionName = null, bool isMapReduce = false);
// Overloads for querying an index:
// ================================
IRavenQueryable<T> Query<T, TIndexCreator>();
IDocumentQuery<T> DocumentQuery<T, TIndexCreator>();
// RawQuery:
// =========
IRawDocumentQuery<T> RawQuery<T>(string query);
| Parameter | Type | Description |
|---|---|---|
| T | object | <ul><li>The type of entities queried</li></ul> |
| TIndexCreator | string | <ul><li>The index class type</li></ul> |
| collectionName | string | <ul><li>Name of a collection to query</li><li>No need to provide this param when specifying T</li><li>Specify the collection name when querying a collection that is createdon the fly, i.e. when querying Artifical Documents</li><li>Mutually exclusive with indexName</li></ul> |
| indexName | string | <ul><li>Name of index to query</li><li>Mutually exclusive with collectionName</li></ul> |
| isMapReduce | string | <ul><li>Whether querying a map-reduce index</li></ul> |
| query | string | <ul><li>The RQL query string</li></ul> |
| Return Value | |
|---|---|
IRavenQueryableIDocumentQueryIRawDocumentQuery | Instances exposing additional query methods and extensions |