Oihana PHP Arango

DocumentsStreamTrait uses trait:short

Provides streaming capabilities for document retrieval from ArangoDB collections.

This trait extends DocumentsListTrait to add memory-efficient streaming functionality using PHP generators. Instead of loading all documents into memory at once, documents are yielded one by one, making it ideal for processing large result sets.

Tags
see
DocumentsListTrait

For the base query building and listing functionality

Table of Contents

Methods

buildListQuery()  : string
Builds an AQL query for listing documents with comprehensive filtering, sorting, and pagination.
stream()  : Generator<string|int, mixed>
Retrieves documents as a generator stream from the collection with filtering, sorting, and pagination support.

Methods

buildListQuery()

Builds an AQL query for listing documents with comprehensive filtering, sorting, and pagination.

public buildListQuery([array<string|int, mixed> $init = [] ][, array<string|int, mixed> &$bindVars = [] ]) : string

This method orchestrates the construction of a complete AQL query by combining various query components (FOR, FILTER, SORT, LIMIT, RETURN) based on the provided initialization parameters. It delegates to specialized methods for each query aspect (filtering, sorting, etc.) and compiles them into a single executable AQL statement.

Generated Query Structure:

FOR doc IN @@collection
  [LET variables...]
  FILTER doc.active == [1|0] [&& facets] [&& filter] [&& search] [&& conditions]
  SORT field1 ASC, field2 DESC
  LIMIT offset, limit
  RETURN { ...fields }

Query Building Process:

  1. Extract configuration parameters (limit, offset, variables, debug)
  2. Build FOR clause with collection binding
  3. Construct FILTER clause combining active, facets, filter, and search
  4. Generate SORT clause from sort criteria
  5. Add LIMIT/OFFSET for pagination
  6. Define RETURN clause with field selection
  7. Compile all components into final query
  8. Optionally debug the generated query

Usage Example:

$bindVars = [];
$query = $model->buildListQuery([
    'active'  => true,
    'filter'  => ['status' => 'published'],
    'sort'    => ['createdAt' => 'DESC'],
    'limit'   => 50,
    'offset'  => 0,
    'fields'  => ['_key', 'title', 'author'],
    'debug'   => true
], $bindVars);
// Returns: "FOR doc IN @@collection FILTER doc.active == 1 && ..."
// $bindVars now contains: ['@collection' => 'myCollection', ...]
Parameters
$init : array<string|int, mixed> = []

Configuration array with optional parameters:

Query Variables:*

  • variables (array, optional) Additional AQL LET statements to declare variables in the query. Example: ['total = LENGTH(doc.items)', 'avg = SUM(doc.prices) / total'] Default: []

Pagination:*

  • limit (int, optional) Maximum number of documents to return. Set to 0 for no limit. Example: 50 Default: 0

  • offset (int, optional) Number of documents to skip before returning results. Useful for pagination when combined with limit. Example: 100 (skip first 100 documents) Default: 0

Filtering:*

  • active (?bool, optional) Filter by document active status. true for active only, false for inactive only, null to ignore this filter. Processed by prepareActive(). Default: null

  • facets (?array, optional) Array of facet-based filter conditions. Facets are typically used for categorical filtering (categories, tags, types, etc.). Processed by prepareFacets(). Example: ['category' => 'electronics', 'brand' => 'Apple'] Default: null

  • conditions (?array, optional) Array of custom AQL filter conditions. When provided, this completely overrides the automatic combination of active/facets/filter/search. Use this for complex custom filtering logic. Example: ['doc.price > 100', 'doc.stock > 0'] Default: null

  • filter (?array, optional) Array of general filter conditions applied as key-value pairs. Processed by prepareFilter(). Example: ['status' => 'published', 'author.verified' => true] Default: null

  • search (?array, optional) Array of search conditions for text-based filtering. Typically used for full-text or partial string matching. Processed by prepareSearch(). Example: ['title' => 'laptop', 'description' => 'gaming'] Default: null

Sorting:*

  • sort (?array, optional) Array defining sort criteria. Keys are field names (support dot notation), values are 'ASC' or 'DESC'. Multiple fields create compound sorting. Processed by prepareSort(). Example: ['priority' => 'DESC', 'createdAt' => 'ASC'] Default: null

Field Selection:*

  • fields (?array<string>, optional) Array of field names to include in returned documents. Supports dot notation for nested fields. If not provided, all document fields are returned. Processed by returnFields(). Example: ['_key', 'title', 'author.name', 'metadata.tags'] Default: null (returns all fields)

Output Transformation:*

  • skin (?string, optional) Name of the skin/transformation to apply to result documents. Applied during the alter() phase after query execution. Example: 'summary', 'detailed', 'api' Default: null

Query Binding:*

  • binds (array<string, mixed>, optional) Additional AQL bind variables to include in the query. Merged with auto-generated bind variables. Example: ['minPrice' => 100, 'category' => 'books'] Default: []

Debugging:*

  • debug (bool, optional) Enable query debugging. When true, the generated AQL query and bind variables are logged via debugQuery() before returning. Default: false
$bindVars : array<string|int, mixed> = []

Reference to an array where bind variables will be collected. This array is populated during query construction with all necessary bind variables (collection name, filter values, search terms, etc.). After the method returns, this array contains all variables needed to execute the query.

Example of populated bindVars:*

[
    '@collection' => 'products',
    'active' => 1,
    'status' => 'published',
    'minPrice' => 100
]
Tags
throws
BindException

If there's an error during bind variable processing, such as:

  • Invalid bind variable names (reserved keywords, invalid characters)
  • Type conversion failures
  • Collection binding errors
ConstantException
ContainerExceptionInterface

If there's an error accessing the dependency injection container while resolving services needed during query construction

NotFoundExceptionInterface

If a required service (like a filter handler) is not found in the dependency injection container

ReflectionException

If a reflection error occurs during internal processing, such as:

  • Analyzing filter or sort field structures
  • Inspecting schema classes for field validation
  • Dynamic method invocation failures
UnsupportedOperationException
DependencyException
NotFoundException
ValidationException
see
list()

For executing the built query and retrieving results

prepareActive()

For active status filter preparation

prepareFacets()

For facet filter preparation

prepareFilter()

For general filter preparation

prepareSearch()

For search condition preparation

prepareSort()

For sort criteria preparation

returnFields()

For field selection preparation

Return values
string

The compiled AQL query string ready for execution. The query is a complete, executable AQL statement that can be passed to ArangoDB along with the populated $bindVars.

Example Output:*

FOR doc IN @@collection
  FILTER doc.active == @active && doc.status == @status
  SORT doc.createdAt DESC
  LIMIT 0, 50
  RETURN { _key: doc._key, title: doc.title, price: doc.price }

stream()

Retrieves documents as a generator stream from the collection with filtering, sorting, and pagination support.

public stream([array<string|int, mixed> $init = [] ]) : Generator<string|int, mixed>

This method provides memory-efficient iteration over large result sets by yielding documents one at a time instead of loading them all into memory. Each document is fully processed (schema mapping and alter() transformation) before being yielded.

Key Benefits:

  • Memory Efficient: Only one document in memory at a time
  • Early Processing: Start processing results before the query completes
  • Large Datasets: Handle millions of documents without memory issues
  • Full Feature Set: Same filtering, sorting, and pagination as list()

Generated AQL Query Structure:

FOR doc IN @@collection
  FILTER doc.active == [1|0] [&& facets] [&& search] [&& conditions]
  SORT field1 ASC, field2 DESC
  LIMIT offset, limit
  RETURN { ...fields }

Usage Example:

// Process large dataset efficiently
foreach ($model->stream(['limit' => 10000]) as $document) {
    // Process one document at a time
    processDocument($document);
}

// With complex filtering
$generator = $model->stream([
    'active' => true,
    'filter' => ['status' => 'published'],
    'search' => ['title' => 'PHP'],
    'sort'   => ['createdAt' => 'DESC'],
    'limit'  => 1000,
    'offset' => 0
]);
Parameters
$init : array<string|int, mixed> = []

Configuration array with optional parameters:

Query Binding:*

  • binds (array<string, mixed>, optional) Additional AQL bind variables to include in the query. Default: []

Pagination:*

  • limit (int, optional) Maximum number of documents to return. Set to 0 for no limit. Default: 0

  • offset (int, optional) Number of documents to skip before returning results. Useful for pagination when combined with limit. Default: 0

Filtering:*

  • active (?bool, optional) Filter by active status. true returns only active documents, false returns only inactive documents, null ignores this filter. Default: null

  • facets (?array, optional) Array of facet conditions for filtering. Processed by prepareFacets(). Example: ['category' => 'books', 'year' => 2024] Default: null

  • conditions (?array, optional) Array of custom filter conditions. When provided, this overrides the automatic combination of active/facets/filter/search conditions. Default: null

  • filter (?array, optional) Array of general filter conditions. Processed by prepareFilter(). Example: ['status' => 'published', 'author.verified' => true] Default: null

  • search (?array, optional) Array of search conditions for text-based filtering. Processed by prepareSearch(). Example: ['title' => 'search term', 'description' => 'keyword'] Default: null

Sorting:*

  • sort (?array, optional) Array defining sort criteria. Keys are field names, values are 'ASC' or 'DESC'. Processed by prepareSort(). Example: ['createdAt' => 'DESC', 'title' => 'ASC'] Default: null

Field Selection:*

  • fields (?array<string>, optional) Array of specific field names to return for each document. If not provided, all document fields are returned. Processed by returnFields(). Example: ['_key', 'title', 'author.name', 'publishedAt'] Default: null (all fields)

Output Transformation:*

  • skin (?string, optional) Name of the skin/transformation to apply to result documents. The skin is applied during the alter() phase. Default: null

Query Variables:*

  • variables (?array, optional) Additional AQL variables to declare in the query (LET statements). Default: []

Debugging:*

  • debug (?bool, optional) Enable query debugging. When true, logs the generated AQL query and bind variables via debugQuery(). Default: false
Tags
throws
ArangoException

If there's an error during ArangoDB query execution, such as:

  • Invalid AQL syntax
  • Collection not found
  • Connection issues
  • Query timeout
BindException

If there's an error binding parameters to the AQL query, such as:

  • Invalid bind variable names
  • Type mismatch in bind values
  • Reserved keyword usage
ConstantException
ContainerExceptionInterface

If there's an error accessing the dependency injection container

DependencyException
NotFoundExceptionInterface

If a required service is not found in the dependency injection container

NotFoundException
UnsupportedOperationException
ReflectionException

If a reflection error occurs during internal processing, such as:

  • Schema class not found
  • Invalid schema structure
  • Property access errors during hydration
see
list()

For loading all documents into memory at once

buildListQuery()

For the query construction logic

streamDocuments()

For the underlying generator implementation

Return values
Generator<string|int, mixed>

A PHP generator that yields documents one by one. Each yielded document has already been processed through schema mapping (if configured) and the alter() transformation method.

On this page

Search results