Skip to main content

Query Overview

  • Queries in RavenDB can be written with either of the following:

    • LINQ - when querying with the session's Query method.
    • Low-level API - when querying with the session's DocumentQuery method.
    • RQL:
      • when querying with the session's RawQuery method.
      • when querying from the Query view in Studio.
  • Queries defined with Query or DocumentQuery are 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 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:

  1. Query a specific index - uses the index you specify (typically a static index).
  2. Query a collection - using an auto-index - uses an existing or newly created auto-index.
  3. 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 where condition on fields other than the document ID,
      or an ID condition not listed in Query by document ID.
    • An order by clause to sort the results.
    • A group by clause to group the results.
    • A suggest() call in the select clause to request term suggestions.

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 in where, order by, and suggest().
    • For queries with group by -
      it is a map-reduce index that groups by exactly the fields in the query's group by clause
      and computes every aggregation the query selects (for example, count() or sum(Freight)).
  • 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 where condition
    Sorting alone is enough to require an auto-index.
    A query that has an order by clause but no where condition is served by an auto-index, not by the raw collection. This applies to any order by clause, including order by id() and order by random().

    Example RQL:   from Employees order by FirstName
    If the Employees collection has no auto-index yet, this query creates the Auto/Employees/ByFirstName auto-index. See more examples in Sort query results.

  • Grouping (group by)
    Grouping alone is enough to require an auto map-reduce index, even without a where or order by clause.

    Example RQL:   from Orders group by Company select count()
    If no suitable auto map-reduce index already exists, this query creates the Auto/Orders/ByCountReducedByCompany index. See How to perform group by query.

  • Term suggestions (suggest())
    Requesting term suggestions also requires an auto-index, even without a where or order by clause.

    Example RQL:   from Products select suggest(Name, "chaig")
    If no suitable auto-index already exists, this query creates the Auto/Products/BySuggest(Name) auto-index, with suggestions enabled for Name.
    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 filter clause
    The RQL filter clause 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, or group by clause and no suggest() 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() = ... (or id() == ...) 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 a suggest() call.

    Other RQL conditions on id(), such as !=, ranges, or ID conditions combined with and or or,
    require an auto-index.
    To look up several documents by ID, use id() in (...) rather than id() = ... 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 Query method 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

// 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

Query a collection by ID

// 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 a collection by a field value (where)

// 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 with paging

// 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
  • By default, if the page size is not specified, all matching records will be retrieved from the database.

Session.Advanced.DocumentQuery​

  • DocumentQuery provides 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:

// 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

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 RawQuery method.


Example:

// 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

Custom methods and extensions for LINQ​


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);
ParameterTypeDescription
Tobject<ul><li>The type of entities queried</li></ul>
TIndexCreatorstring<ul><li>The index class type</li></ul>
collectionNamestring<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 created
on the fly, i.e. when querying Artifical Documents</li><li>Mutually exclusive with indexName</li></ul>
indexNamestring<ul><li>Name of index to query</li><li>Mutually exclusive with collectionName</li></ul>
isMapReducestring<ul><li>Whether querying a map-reduce index</li></ul>
querystring<ul><li>The RQL query string</li></ul>
Return Value
IRavenQueryable
IDocumentQuery
IRawDocumentQuery
Instances exposing additional query methods and extensions

In this article