Customize Query



addBeforeQueryExecutedListener and removeBeforeQueryExecutedListener

  • Use these methods to customize the query just before it is executed.

Example

$session->advanced()->addBeforeQueryListener(function ($sender, BeforeQueryEventArgs $event) {
    $event->getQueryCustomization()
        ->addBeforeQueryExecutedListener(function($q) {
            // set 'pageSize' to 10
            $q->setPageSize(10);
        });
});

$session->query(Employee::class)->toList();

Syntax

public function addBeforeQueryExecutedListener(Closure $action): DocumentQueryCustomizationInterface;
public function removeBeforeQueryExecutedListener(Closure $action): DocumentQueryCustomizationInterface;
Parameters Type Description
$action Closure An $action method that operates on the query

addAfterQueryExecutedListener and removeAfterQueryExecutedListener

  • Use these methods to access the raw query result after it is executed.

Example

$queryDuration = null;

$session->query(Employee::class)
    ->addAfterQueryExecutedListener(function($result) use (&$queryDuration) {
        $queryDuration = Duration::ofMillis($result->getDurationInMs());
    })
    ->toList();

Syntax

public function addAfterQueryExecutedListener(Closure $action): DocumentQueryCustomizationInterface;
public function removeAfterQueryExecutedListener(Closure $action): DocumentQueryCustomizationInterface;
Parameters Type Description
$action Closure An Action method that receives the raw query result

noCaching

  • By default, query results are cached.

  • You can use the noCaching customization to disable query caching.

  • Learn more in disable caching per session.

Example

$session->advanced()
    ->addBeforeQueryListener(function($sender, BeforeQueryEventArgs $event) {
        $event->getQueryCustomization()->noCaching();
    });

$results = $session->query(Employee::class)
    ->whereEquals("FirstName", "Robert")
    ->toList();

Syntax

public function noCaching(): DocumentQueryCustomizationInterface

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 entity tracking.

  • See disable entity tracking for all other options.

Example

$session->advanced()
    ->addBeforeQueryListener(function($sender, BeforeQueryEventArgs $event) {
        $event->getQueryCustomization()->noTracking();
    });

$results = $session->query(Employee::class)
    ->whereEquals("FirstName", "Robert")
    ->toList();

Syntax

public function noTracking(): DocumentQueryCustomizationInterface

Projection

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

    Projecting means the query returns only specific document fields instead of the full document.

  • If the index does Not store these fields, the field 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.
    Learn more about projections in:

Example

$session->advanced()
    ->addBeforeQueryListener(function($sender, BeforeQueryEventArgs $event) {
        $event->getQueryCustomization()->projection(ProjectionBehavior::default());
    });

$results = $session->query(Employee::class)
    ->selectFields(Employee::class, "name")
    ->toList();

Syntax

public function projection(ProjectionBehavior $projectionBehavior): DocumentQueryCustomizationInterface;

class ProjectionBehavior
{
    public static function default(): ProjectionBehavior;
    public static function fromIndex(): ProjectionBehavior;
    public static function fromIndexOrThrow(): ProjectionBehavior;
    public static function fromDocument(): ProjectionBehavior;
    public static function fromDocumentOrThrow(): ProjectionBehavior;
}
  • 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.

  • More ordering options are available in this Sorting article.

Example

$session->advanced()
    ->addBeforeQueryListener(function($sender, BeforeQueryEventArgs $event) {
        $event->getQueryCustomization()->randomOrdering();
    });

// Result will be ordered randomly each time
$results = $session->query(Employee::class)
    ->whereEquals("FirstName", "Robert")
    ->toList();

Syntax

public function randomOrdering(): DocumentQueryCustomizationInterface;
public function randomOrdering(?string $seed): DocumentQueryCustomizationInterface;
Parameters Type Description
$seed ?string Order the search results randomly using this seed.
Useful when executing repeated random queries.

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.

  • Learn more about stale results in stale indexes.

Example

$session->advanced()
    ->addBeforeQueryListener(function($sender, BeforeQueryEventArgs $event) {
        $event->getQueryCustomization()->waitForNonStaleResults();
    });

$results = $session->query(Employee::class)
    ->whereEquals("FirstName", "Robert")
    ->toList();

Syntax

public function waitForNonStaleResults(): DocumentQueryCustomizationInterface;
public function waitForNonStaleResults(Duration $waitTimeout): DocumentQueryCustomizationInterface;
Parameters Type Description
$waitTimeout Duration Time to wait for non-stale results.
Default is 15 seconds.

Methods return value

All of the above customization methods return the following:

Return value
DocumentQueryCustomizationInterface Returns self for easier method chaining