Session: Querying: How to Query

This session explains the following methods to query a database:

  • session.query
  • session.advanced().documentQuery
  • session.advanced().rawQuery

Session.Query

The most straightforward way to issue a query is by using the query method.

Syntax

<T> IDocumentQuery<T> query(Class<T> clazz);

<T> IDocumentQuery<T> query(Class<T> clazz, Query collectionOrIndexName);

<T, TIndex extends AbstractIndexCreationTask> IDocumentQuery<T> query(Class<T> clazz, Class<TIndex> indexClazz);
Parameters
clazz Class Target type
collectionOrIndexName Query Collection name of index name to use
indexClazz Class Indicates class of index to use
Return Value
IDocumentQuery Instance implementing IDocumentQuery interface containing additional query methods

Example I - Basic Dynamic Query

// load all entities from 'Employees' collection
List<Employee> employees = session.query(Employee.class)
    .toList();

The above is an example of a dynamic query which doesn't require you to specify an index name. RavenDB will create an auto index automatically if necessary.

The provided Employee type as the generic type parameter does not only define the type of returned results, but it also indicates that the queried collection will be Employees.

Example II - Query Syntax

// load all entities from 'Employees' collection
// where FirstName equals 'Robert'
List<Employee> employees = session.query(Employee.class)
    .whereEquals("FirstName", "Robert")
    .toList();

Example III - Using Specific Index

// load all entities from 'Employees' collection
// where firstName equals 'Robert'
// using 'Employees/ByName' index
List<Employee> employees = session.query(Employee.class, index("Employees/ByName"))
    .whereEquals("FirstName", "Robert")
    .toList();

or

// load all entities from 'Employees' collection
// where firstName equals 'Robert'
// using 'Employees/ByName' index
List<Employee> employees = session.query(Employee.class, Employees_ByName.class)
    .whereEquals("FirstName", "Robert")
    .toList();

session.advanced().documentQuery

Example IV

// load all employees hired between
// 1/1/2002 and 12/31/2002
List<Employee> employees = session.advanced().documentQuery(Employee.class)
    .whereBetween("HiredAt",
        LocalDate.of(2002, 1, 1), LocalDate.of(2002, 12, 31))
    .toList();

session.advanced().rawQuery

Queries in RavenDB use a SQL-like language called RavenDB Query Language (RQL). All of the above queries generate RQL sent to the server. The session also gives you the way to express the query directly in RQL using rawQuery method.

Example IV

// load all entities from 'Employees' collection
// where FirstName equals 'Robert'
List<Employee> employees = session.advanced()
    .rawQuery(Employee.class,
        "from Employees where FirstName = 'Robert'")
    .toList();