Skip to main content

Customize Query

BeforeQueryExecuted

Use BeforeQueryExecuted to customize the query just before it is executed.

Example

List<Employee> results = session
.Query<Employee>()
// Call 'Customize' with 'BeforeQueryExecuted'
.Customize(x => x.BeforeQueryExecuted(query =>
{
// Can modify query parameters
query.SkipDuplicateChecking = true;
// Can apply any needed action, e.g. write to log
_logger.Info($"Query to be executed is: {query.Query}");
}))
.Where(x => x.FirstName == "Robert")
.ToList();

Syntax

IDocumentQueryCustomization BeforeQueryExecuted(Action<IndexQuery> action);
ParameterTypeDescription
actionAction<IndexQuery>An Action method that operates on the query.
The query is passed in the IndexQuery param.

AfterQueryExecuted

Use AfterQueryExecuted to access the raw query result after it is executed.

Example

List<Employee> results = session
.Query<Employee>()
// Call 'Customize' with 'AfterQueryExecuted'
.Customize(x => x.AfterQueryExecuted(rawResult =>
{
// Can access the raw query result
var queryDuration = rawResult.DurationInMs;
// Can apply any needed action, e.g. write to log
_logger.Info($"{rawResult.LastQueryTime}");
}))
.ToList();

Syntax

IDocumentQueryCustomization AfterQueryExecuted(Action<QueryResult> action);
ParameterTypeDescription
actionAction<Panel>An Action method that receives the raw query result.
The query result is passed in the QueryResult param.

AfterStreamExecuted

  • Use AfterStreamExecuted to retrieve a raw (blittable) result of the streaming query.
  • Learn more about streaming queries in how to stream query results.

Example

long totalStreamedResultsSize = 0;

// Define the query
var query = session
.Query<Employee>()
// Call 'Customize' with 'AfterStreamExecuted'
.Customize(x => x.AfterStreamExecuted(streamResult =>
// Can access the stream result
totalStreamedResultsSize += streamResult.Size));

// Call 'Stream' to execute the query
var streamResults = session.Advanced.Stream(query);

Syntax

IDocumentQueryCustomization AfterStreamExecuted(Action<BlittableJsonReaderObject> action);
ParameterTypeDescription
actionAction<BlittableJsonReaderObject>An Action method that recieves a single stream query result.
The stream result is passed in the BlittableJsonReaderObject param.

NoCaching

  • By default, query results are cached.
  • You can use the NoCaching customization to disable query caching.
  • To disable caching for the entire session, see disable caching per session.

Example

List<Employee> results = session
.Query<Employee>()
// Call 'Customize' with 'NoCaching'
.Customize(x => x.NoCaching())
.Where(x => x.FirstName == "Robert")
.ToList();

Syntax

IDocumentQueryCustomization NoCaching();

NoTracking

  • By default, the Session tracks all changes made to all entities that it has either loaded, stored, or queried for.
  • You can use the NoTracking customization to disable tracking for entities returned by a query.
  • See disable entity tracking for all other options.

Example

List<Employee> results = session
.Query<Employee>()
// Call 'Customize' with 'NoTracking'
.Customize(x => x.NoTracking())
.Where(x => x.FirstName == "Robert")
.ToList();

Syntax

IDocumentQueryCustomization NoTracking();

Projection

  • Projecting query results means that the query returns only specific document fields, rather than the entire document.
    Learn more about projections in:

  • By default, when querying an index and projecting query results,
    the server will try to retrieve field values from the fields stored in the index.
    If the index does Not store these fields, the fields' values will be retrieved from the documents.
    Use the Projection method to customize and modify this behavior.

  • Note:
    Entities resulting from a projecting query are Not tracked by the session.

Example

List<string> results = session
.Query<Employees_ByFullName.IndexEntry, Employees_ByFullName>()
// Call 'Customize'
// Pass the requested projection behavior to the 'Projection' method
.Customize(x => x.Projection(ProjectionBehavior.FromDocumentOrThrow))
// Select the fields that will be returned by the projection
.Select(x => x.FullName)
.ToList();

In the above example:

  • Field 'FullName' is stored in the index (see index definition in the rightmost tab).
    However, the server will try to fetch the value from the document since the default behavior was modified to FromDocumentOrThrow.
  • An exception will be thrown since an 'Employee' document does not contain the property 'FullName'.
    (based on the Northwind sample data).

Syntax

IDocumentQueryCustomization Projection(ProjectionBehavior projectionBehavior);

public enum ProjectionBehavior {
Default,
FromIndex,
FromIndexOrThrow,
FromDocument,
FromDocumentOrThrow
}
  • Default
    Retrieve values from the stored index fields when available.
    If fields are not stored then get values from the document,
    a field that is not found in the document is skipped.
  • FromIndex
    Retrieve values from the stored index fields when available.
    A field that is not stored in the index is skipped.
  • FromIndexOrThrow
    Retrieve values from the stored index fields when available.
    An exception is thrown if the index does not store the requested field.
  • FromDocument
    Retrieve values directly from the documents store.
    A field that is not found in the document is skipped.
  • FromDocumentOrThrow
    Retrieve values directly from the documents store.
    An exception is thrown if the document does not contain the requested field.

RandomOrdering

  • Use RandomOrdering to order the query results randomly.
  • For additional ordering options, see Sort query results.

Example

List<Employee> results = session
.Query<Employee>()
// Call 'Customize' with 'RandomOrdering'
.Customize(x => x.RandomOrdering())
.ToList();

Syntax

IDocumentQueryCustomization RandomOrdering();
IDocumentQueryCustomization RandomOrdering(string seed);
ParameterTypeDescription
seedstringOrder the search results randomly using this seed.
Useful when executing repeated random queries.

Timings

  • Use Timings to get detailed stats of the time spent by the server on each part of the query.
  • The timing statistics will be included in the query results.
  • Learn more in how to include query timings.

Example

List<Employee> results = session
.Query<Employee>()
// Call 'Customize' with 'Timings'
// Provide an out param for the timings results
.Customize(x => x.Timings(out QueryTimings timings))
.Where(x => x.FirstName == "Robert")
.ToList();

Syntax

IDocumentQueryCustomization Timings(out QueryTimings timings);
ParameterTypeDescription
timingsQueryTimingsAn out param that will be filled with the timings results

WaitForNonStaleResults

  • All queries in RavenDB provide results using an index, even when you don't specify one.
    See detailed explanation in Queries always provide results using an index.

  • Use WaitForNonStaleResults to instruct the query to wait for non-stale results from the index.

  • A TimeoutException will be thrown if the query is not able to return non-stale results within the specified
    (or default) timeout.

  • Note: This feature is Not available when streaming the query results.
    Calling WaitForNonStaleResults with a streaming query will throw an exception.

  • Learn more about stale results in stale indexes.

Example

List<Employee> results = session
.Query<Employee>()
// Call 'Customize' with 'WaitForNonStaleResults'
.Customize(x => x.WaitForNonStaleResults(TimeSpan.FromSeconds(10)))
.Where(x => x.FirstName == "Robert")
.ToList();

Syntax

IDocumentQueryCustomization WaitForNonStaleResults(TimeSpan? waitTimeout);
ParameterTypeDescription
waitTimeoutTimeSpan?Time to wait for non-stale results.
Default is 15 seconds.

WithTag

  • Use WithTag to attach a user-defined string label to a query.

  • The tag is sent as a URL query parameter (&tag=...) with each /queries request,
    making it easy to identify specific queries in server-side logs and during debugging.

  • The tag value cannot be null, empty, or whitespace. An ArgumentException is thrown if it is.

  • Supported by standard queries, lazy queries, and aggregation queries.

Example

List<Employee> results = session
.Query<Employee>()
// Call 'Customize' with 'WithTag'
// Attach an identifying label to this query
.Customize(x => x.WithTag("Employees-from-London"))
.Where(x => x.Address.City == "London")
.ToList();

Syntax

// From IDocumentQueryCustomization (used with Customize() on Query/LINQ)
IDocumentQueryCustomization WithTag(string tag);

// From IQueryBase (used directly on DocumentQuery and RawQuery)
TSelf WithTag(string tag);
ParameterTypeDescription
tagstringA user-defined label to attach to the query. Cannot be null, empty, or whitespace.

Methods return value

All of the above customization methods return the following:

Query return value
IDocumentQueryCustomizationReturns self for easier method chaining.
DocumentQuery return value
IQueryBaseReturns self for easier method chaining.

In this article