Session: Querying: How to Stream Query Results

Query results can be streamed using the stream method from the advanced session operations. The query can be issued using either a static index, or it can be a dynamic one where it will be handled by an auto index.

Syntax

<T> CloseableIterator<StreamResult<T>> stream(IDocumentQuery<T> query);

<T> CloseableIterator<StreamResult<T>> stream(IDocumentQuery<T> query, Reference<StreamQueryStatistics> streamQueryStats);

<T> CloseableIterator<StreamResult<T>> stream(IRawDocumentQuery<T> query);

<T> CloseableIterator<StreamResult<T>> stream(IRawDocumentQuery<T> query, Reference<StreamQueryStatistics> streamQueryStats);
Parameters
query IDocumentQuery or IRawDocumentQuery Query to stream results for.
Reference streamQueryStats StreamQueryStatistics Information about performed query.
Return Value
CloseableIterator Iterator with entities.

Example I - Using Static Index

IDocumentQuery<Employee> query = session
    .query(Employee.class, Employees_ByFirstName.class)
    .whereEquals("FirstName", "Robert");

CloseableIterator<StreamResult<Employee>> results = session.advanced().stream(query);

while (results.hasNext()) {
    StreamResult<Employee> employee = results.next();
}

Example II - Dynamic Document Query

IDocumentQuery<Employee> query = session
    .advanced()
    .documentQuery(Employee.class)
    .whereEquals("FirstName", "Robert");

Reference<StreamQueryStatistics> streamQueryStatsRef = new Reference<>();
CloseableIterator<StreamResult<Employee>> results = session.advanced().stream(query, streamQueryStatsRef);

while (results.hasNext()) {
    StreamResult<Employee> employee = results.next();
}

Example III - Dynamic Raw Query

IRawDocumentQuery<Employee> query = session.advanced()
    .rawQuery(Employee.class, "from Employees where FirstName = 'Robert'");

CloseableIterator<StreamResult<Employee>> results = session.advanced().stream(query);

while (results.hasNext()) {
    StreamResult<Employee> employee = results.next();
}