ObjectBox Queries
ObjectBox queries return persisted objects that match user defined criteria. Learn here how to use the QueryBuilder class and specify criteria to create Queries with ObjectBox DB in Java.
With ObjectBox DB you use the QueryBuilder class to specify criteria and create Query objects. The Query class will actually run the query and return matching objects.

QueryBuilder

The QueryBuilder<T> class lets you build custom queries for your entities. Create an instance via Box.query() .
QueryBuilder offers several methods to define query conditions for properties of an entity. To specify a property ObjectBox does not use their names as text but meta-information "underscore" classes (like User_) that are generated during build time. The meta-information classes have a static field for each property (like User_.firstName). This allows referencing properties safely with compile-time checks to prevent runtime errors, for example, because of typos.
Here are two examples using a simple and a more complicated query:
Simple condition example: Query for all users with the first name “Joe”:
Java
Kotlin
Dart
1
Query<User> query = userBox.query().equal(User_.firstName, "Joe").build();
2
List<User> joes = query.find();
3
query.close();
Copied!
1
val query = userBox.query().equal(User_.firstName, "Joe").build()
2
val joes = query.find()
3
query.close()
4
5
// Or shorten with use:
6
val joes = userBox.query().equal(User_.firstName, "Joe").build()
7
.use { it.find() }
Copied!
1
Query<User> query = userBox.query(User_.firstName.equals('Joe')).build();
2
List<User> joes = query.find();
3
query.close();
Copied!
Multiple conditions example: Get users with the first name “Joe” that are born later than 1970 and whose last name starts with “O”.
Java
Kotlin
Dart
1
Query<User> query = userBox.query()
2
.equal(User_.firstName, "Joe")
3
.greater(User_.yearOfBirth, 1970)
4
.startsWith(User_.lastName, "O")
5
.build();
6
List<User> youngJoes = query.find();
7
query.close(); // Or keep the query instance to re-use it
Copied!
1
val query = userBox.query()
2
.equal(User_.firstName, "Joe")
3
.greater(User_.yearOfBirth, 1970)
4
.startsWith(User_.lastName, "O")
5
.build()
6
val youngJoes = query.find()
7
query.close() // Or keep the query instance to re-use it
Copied!
1
Query<User> query = userBox.query(
2
User_.firstName.equals('Joe') &
3
User_.yearOfBirth.greaterThan(1970) &
4
User_.lastName.startsWith('O')).build();
5
List<User> youngJoes = query.find();
Copied!

New Query API (Java/Kotlin 3.0)

ObjectBox Java/Kotlin 3.0.0 introduces a new query API that accepts complex nested conditions, e.g. the equivalent of (A or B) and (C or D).
To build a query with the new API use Box.query(condition) and supply a condition built using entity Property methods, like property.equal(value). All properties of an entity can be accessed using its underscore class. For example, for an entity User a property could be User_.firstName, a condition using it could be User_.firstName.equal("Joe").
Simple condition example: Query for all users with the first name “Joe”.
Java
Kotlin
Dart
1
Query<User> query = userBox.query(User_.firstName.equal("Joe")).build();
2
List<User> joes = query.find();
3
query.close();
Copied!
1
val query = userBox.query(User_.firstName.equal("Joe")).build()
2
val joes = query.find()
3
query.close()
Copied!
1
Query<User> query = userBox.query(User_.firstName.equals('Joe')).build();
2
List<User> joes = query.find();
3
query.close();
Copied!
Multiple conditions example: Get users with the first name “Joe” that are born later than 1970 and whose last name starts with “O”.
Java
Kotlin
Dart
1
Query<User> query = userBox.query(
2
User_.firstName.equal("Joe")
3
.and(User_.yearOfBirth.greater(1970))
4
.and(User_.lastName.startsWith("O")))
5
.build();
6
List<User> youngJoes = query.find();
7
query.close();
Copied!
1
val query = userBox.query(
2
User_.firstName equal "Joe"
3
and (User_.yearOfBirth greater 1970)
4
and (User_.lastName startsWith "O")
5
.build()
6
val youngJoes = query.find()
7
query.close()
Copied!
1
Query<User> query = userBox.query(
2
User_.firstName.equal('Joe')
3
.and(User_.yearOfBirth.greaterThan(1970))
4
.and(User_.lastName.startsWith('O')))
5
.build();
6
7
// or use operator overloads:
8
Query<User> query = userBox.query(
9
User_.firstName.equal('Joe') &
10
User_.yearOfBirth.greaterThan(1970) &
11
User_.lastName.startsWith('O'))
12
.build();
Copied!
Conditions are combined with QueryCondition.and(condition) or QueryCondition.or(condition). This implicitly adds parentheses around the combined conditions, e.g. cond1.and(cond2) is logically equivalent to (cond1 AND cond2).
To nest conditions pass a single or combined condition.
Java
Kotlin
Dart
1
// equal AND (less OR oneOf)
2
Query<User> query = box.query(
3
User_.firstName.equal("Joe")
4
.and(User_.age.less(12)
5
.or(User_.stamp.oneOf(new long[]{1012}))))
6
.order(User_.age)
7
.build();
Copied!
1
// equal AND (less OR oneOf)
2
val query = box.query(
3
User_.firstName equal "Joe"
4
and (User_.age less 12
5
or (User_.stamp oneOf longArrayOf(1012))))
6
.order(User_.age)
7
.build()
Copied!
1
Query<User> query = box.query(
2
User_.firstName.equal('Joe')
3
.and(User_.age.lessThan(12)
4
.or(User_.stamp.oneOf([1012]))))
5
.order(User_.age)
6
.build();
Copied!

Other notable changes

    property.oneOf(array) replaces the in(property, array) (inValues(property, array) for Kotlin) condition.
    Use Kotlin infix functions to write condition and condition and condition or condition.
    Use Dart operator overloads to write condition & condition and condition | conditon
    Use condition.alias(aliasName) to set an alias for a condition that can later be used with the Query setParameter methods.

Notable conditions

In addition to expected conditions like equal(), notEqual(), greater() and less() there are also conditions like:
    isNull() and notNull(),
    between() to filter for values that are between the given two,
    in() and notIn() to filter for values that match any in the given array,
    startsWith(), endsWith() and contains() for extended String filtering.
In addition, there is and() and or() to build more complex combinations of conditions.
For an overview of all available criteria, please refer to the QueryBuilder class and its method documentations.

Ordering results

In addition to specifying conditions, you can order the returned results using the order() method:
Java
Kotlin
Dart
1
Query<User> query = userBox.query().equal(User_.firstName, "Joe")
2
.order(User_.lastName) // in ascending order, ignoring case
3
.build();
Copied!
1
val query = userBox.query().equal(User_.firstName, "Joe")
2
.order(User_.lastName) // in ascending order, ignoring case
3
.build()
Copied!
1
// in ascending order, ignoring case
2
final qBuilder = box.query(User_.firstName.equals('Joe')..order(User_.lastName);
3
final query = qBuilder.build();
Copied!
You can also pass flags to order() to sort in descending order, to sort case sensitive or to specially treat null values. For example to sort the above results in descending order and case sensitive instead:
Java
Kotlin
Dart
1
.order(User_.lastName, QueryBuilder.DESCENDING | QueryBuilder.CASE_SENSITIVE)
Copied!
1
.order(User_.lastName, QueryBuilder.DESCENDING or QueryBuilder.CASE_SENSITIVE)
Copied!
1
.order(User_.lastName, flags: Order.descending | Order.caseSensitive)
Copied!
Order directives can also be chained. Check the method documentation (Java) for details.

Debug queries

To see what query is actually executed by ObjectBox:
Java
Kotlin
Dart
1
// Set the LOG_QUERY_PARAMETERS debug flag
2
BoxStore store = MyObjectBox.builder()
3
.debugFlags(DebugFlags.LOG_QUERY_PARAMETERS)
4
.build();
5
6
// Execute a query
7
query.find();
Copied!
1
// Set the LOG_QUERY_PARAMETERS debug flag
2
val store = MyObjectBox.builder()
3
.debugFlags(DebugFlags.LOG_QUERY_PARAMETERS)
4
.build()
5
6
// Execute a query
7
query.find()
Copied!
1
print(query.describeParameters());
Copied!
Then in your console (or logcat on Android) you will see log output like:
1
Parameters for query #2:
2
(firstName ==(i) "Joe"
3
AND age < 12)
Copied!

Query

Queries are created (and not yet executed) by calling build() on the QueryBuilder.
1
Query<User> query = builder.build();
Copied!

Finding objects

There are a couple of find methods to retrieve objects matching the query:
1
// return all entities matching the query
2
List<User> joes = query.find();
3
4
// return only the first result or null if none
5
User joe = query.findFirst();
6
7
// return the only result or null if none, throw if more than one result
8
User joe = query.findUnique();
Copied!
To return all entities matching the query simply call find().
To only return the first result, use findFirst().
If you expect a unique result, call findUnique() instead. It will give you a single result or null, if no matching entity was found and throw an exception if there was more than one result.

Reusing Queries and Parameters

If you frequently run the same query you should cache the Query object and re-use it. To make a Query more reusable you can change the values, or query parameters, of each condition you added even after the Query is built. Let's see how.
Assume we want to find a list of User with specific firstName values. First, we build a regular Query with an equal() condition for firstName. Because we have to pass an initial parameter value to equal() but plan to override it before running the Query later, we just pass an empty string:
Java
Kotlin
Dart
1
// build a query
2
Query<User> query = userBox.query().equal(User_.firstName, "").build();
Copied!
1
// build a query
2
Query<User> query = userBox.query().equal(User_.firstName, "").build();
Copied!
1
// build a query
2
final query = userBox.query(User_.firstName.equals('')).build();
Copied!
Now at some later point, we want to run the Query with an actual value for the equals condition onfirstName :
Java
Kotlin
Dart
1
// change firstName parameter to "Joe", get results
2
List<User> joes = query.setParameter(User_.firstName, "Joe").find();
3
...
4
// change firstName parameter to "Jake", get results
5
List<User> jakes = query.setParameter(User_.firstName, "Jake").find();
Copied!
1
// change firstName parameter to "Joe", get results
2
List<User> joes = query.setParameter(User_.firstName, "Joe").find();
3
...
4
// change firstName parameter to "Jake", get results
5
List<User> jakes = query.setParameter(User_.firstName, "Jake").find();
Copied!
1
// change firstName parameter to "Joe", get results
2
query.param(User_.firstName).value = 'Joe';
3
final joes = query.find();
4
...
5
// change firstName parameter to "Jake", get results
6
final jakes = (query..param(User_.firstName).value = 'Jake').find();
Copied!
You might already be wondering what happens if you have more than one condition using firstName? For this purpose you can assign each parameter an alias while specifying the condition:
Java
Kotlin
Dart
1
// assign alias "name" to the equal() query parameter
2
Query<User> query = userBox.query()
3
.equal(User_.firstName, "").parameterAlias("name");
Copied!
1
// assign alias "name" to the equal() query parameter
2
Query<User> query = userBox.query()
3
.equal(User_.firstName, "").parameterAlias("name");
Copied!
1
// assign alias "name" to the equal() query parameter
2
final query = userBox.query(User_.firstName.equals('', alias: 'name')).build();
Copied!
Then, when setting a new parameter value pass the alias instead of the property:
Java
Kotlin
Dart
1
// change parameter with alias "name" to "Joe", get results
2
List<User> joes = query.setParameter("name", "Joe").find();
Copied!
1
// change parameter with alias "name" to "Joe", get results
2
List<User> joes = query.setParameter("name", "Joe").find();
Copied!
1
// change parameter with alias "name" to "Joe", get results
2
final joes = (query..param(User_.firstName, alias: 'name').value = 'Joe').find();
Copied!

Limit, Offset, and Pagination

Sometimes you only need a subset of a query, for example, the first 10 elements to display in your user interface. This is especially helpful (and resource-efficient) when you have a high number of entities and you cannot limit the result using query conditions only.
Java
Kotlin
Dart
1
// offset by 10, limit to at most 5 results
2
List<User> joes = query.find(10, 5);
Copied!
1
// offset by 10, limit to at most 5 results
2
val joes = query.find(10, 5)
Copied!
1
// offset by 10, limit to at most 5 results
2
query
3
..offset = 10
4
..limit = 5;
5
List<User> joes = query.find();
Copied!
offset: The first offset results are skipped.
limit: At most limit results are returned.

Lazy loading results

Only Java/Kotlin
To avoid loading query results right away, Query offers findLazy() and findLazyCached() which return a LazyList of the query results.
LazyList is a thread-safe, unmodifiable list that reads entities lazily only once they are accessed. Depending on the find method called, the lazy list will be cached or not. Cached lazy lists store the previously accessed objects to avoid loading entities more than once. Some features of the list are limited to cached lists (e.g. features that require the entire list). See the LazyList class documentation for more details.

Query results stream

Only Dart
Instead of reading the whole result (list of objects) using find() you can stream it using stream() :
Dart
1
Query<User> query = userBox.query().build();
2
Stream<User stream = query.stream();
3
await stream.forEach((User user) => print(user));
4
query.close();
Copied!

Removing Objects

To remove all objects matching a query, call query.remove() .

PropertyQuery

If you only want to return the values of a particular property and not a list of full objects you can use a PropertyQuery. After building a query, simply call property(Property) to define the property followed by the appropriate find method.
For example, instead of getting all Users, to just get their email addresses:
Java
Kotlin
Dart
1
String[] emails = userBox.query().build()
2
.property(User_.email)
3
.findStrings();
4
5
// or use .findString() to return just the first result
Copied!
1
val emails = userBox.query().build()
2
.property(User_.email)
3
.findStrings()
4
5
// or use .findString() to return just the first result
Copied!
1
final query = userBox.query().build();
2
List<String> emails = query.property(User_.email).find();
3
query.close();
Copied!
Note: the returned array of property values is not in any particular order, even if you did specify an order when building the query.

Handling null values

By default, null values are not returned. However, you can specify a replacement value to return if a property is null:
Java
Kotlin
Dart
1
// includes 'unknown' for each null email
2
String[] emails = userBox.query().build()
3
.property(User_.email)
4
.nullValue("unknown")
5
.findStrings();
Copied!
1
// includes 'unknown' for each null email
2
val emails = userBox.query().build()
3
.property(User_.email)
4
.nullValue("unknown")
5
.findStrings()
Copied!
1
final query = userBox.query().build();
2
// includes 'unknown' for each null email
3
List<String> emails = query.property(User_.email).find(replaceNullWith: 'unknown');
4
query.close();
Copied!

Distinct and unique results

The property query can also only return distinct values:
Java
Kotlin
Dart
1
PropertyQuery pq = userBox.query().build().property(User_.firstName);
2
3
// returns ['joe'] because by default, the case of strings is ignored.
4
String[] names = pq.distinct().findStrings();
5
6
// returns ['Joe', 'joe', 'JOE']
7
String[] names = pq.distinct(StringOrder.CASE_SENSITIVE).findStrings();
8
9
// the query can be configured to throw there is more than one value
10
String[] names = pq.unique().findStrings();
Copied!
1
val pq = userBox.query().build().property(User_.firstName)
2
3
// returns ['joe'] because by default, the case of strings is ignored.
4
val names = pq.distinct().findStrings()
5
6
// returns ['Joe', 'joe', 'JOE']
7
val names = pq.distinct(StringOrder.CASE_SENSITIVE).findStrings()
8
9
// the query can be configured to throw there is more than one value
10
val names = pq.unique().findStrings()
Copied!
1
final query = userBox.query().build();
2
PropertyQuery<String> pq = query.property(User_.firstName);
3
pq.distinct = true;
4
5
// returns ['Joe', 'joe', 'JOE']
6
List<String> names = pq.find();
7
8
// returns ['joe']
9
pq.caseSensitive = false;
10
List<String> names = pq.find();
11
query.close();
Copied!

Aggregating values

Property queries (JavaDoc and Dart API docs) also offer aggregate functions to directly calculate the minimum, maximum, average, sum and count of all found values:
    min() / minDouble(): Finds the minimum value for the given property over all objects matching the query.
    max() / maxDouble(): Finds the maximum value.
    sum() / sumDouble(): Calculates the sum of all values. Note: the non-double version detects overflows and throws an exception in that case.
    avg() : Calculates the average (always a double) of all values.
    count(): returns the number of results. This is faster than finding and getting the length of the result array. Can be combined with distinct() to count only the number of distinct values.

Add query conditions for related entities (links)

After creating a relation between entities, you might want to add a query condition for a property that only exists in the related entity. In SQL this is solved using JOINs. But as ObjectBox is not a SQL database we built something very similar: links. Links are based on Relations - see the doc page for the introduction.
Assume there is a Person that can be associated with multiple Address entities:
Java
Kotlin
Dart
1
@Entity
2
public class Person {
3
@Id long id;
4
String name;
5
ToMany<Address> addresses;
6
}
7
@Entity
8
public class Address {
9
@Id long id;
10
String street;
11
String zip;
12
}
Copied!
1
@Entity
2
class Person {
3
@Id var id: Long = 0
4
var name: String? = null
5
lateinit var addresses: ToMany<Address>
6
}
7
@Entity
8
class Address {
9
@Id var id: Long = 0
10
var street: String? = null
11
var zip: String? = null
12
{
Copied!
1
@Entity()
2
class Person {
3
int id;
4
String name;
5
final addresses = ToMany<Address>();
6
}
7
8
@Entity()
9
class Address {
10
int id;
11
String street;
12
String zip;
13
}
Copied!
To get a Person with a certain name that also lives on a specific street, we need to query the associated Address entities of a Person. To do this, use the link() method of the query builder to tell that the addresses relation should be queried. Then add a condition for Address:
Java
Kotlin
Dart
1
// get all Person objects named "Elmo"...
2
QueryBuilder<Person> builder = personBox
3
.query().equal(Person_.name, "Elmo");
4
// ...which have an address on "Sesame Street"
5
builder.link(Person_.addresses).equal(Address_.street, "Sesame Street");
6
List<Person> elmosOnSesameStreet = builder.build().find();
Copied!
1
// get all Person objects named "Elmo"...
2
val builder = personBox.query().equal(Person_.name, "Elmo")
3
// ...which have an address on "Sesame Street"
4
builder.link(Person_.addresses).equal(Address_.street, "Sesame Street")
5
val elmosOnSesameStreet = builder.build().find()
Copied!
1
// get all Person objects named "Elmo"...
2
QueryBuilder<Person> builder = personBox.query(Person_.name.equals('Elmo'));
3
// ...which have an address on "Sesame Street"
4
builder.linkMany(Person_.addresses, Address_.street.equals('Sesame Street'));
5
Query<Person> query = builder.build();
6
List<Person> elmosOnSesameStreet = query.find();
7
query.close();
Copied!
What if we want to get a list of Address instead of Person? If you know ObjectBox relations well, you would probably add a @Backlink relation to Address and build your query using it with link() as shown above:
Java
Kotlin
Dart
1
@Entity
2
public class Address {
3
// ...
4
@Backlink(to = "addresses")
5
ToMany<Person> persons;
6
}
7
8
// get all Address objects with street "Sesame Street"...
9
QueryBuilder<Address> builder = addressBox
10
.query().equal(Address_.street, "Sesame Street");
11
// ...which are linked from a Person named "Elmo"
12
builder.link(Address_.persons).equal(Person_.name, "Elmo");
13
List<Address> sesameStreetsWithElmo = builder.build().find();
Copied!
1
@Entity
2
class Address {
3
// ...
4
@Backlink(to = "addresses")
5
lateinit var persons: ToMany<Person>
6
}
7
8
// get all Address objects with street "Sesame Street"...
9
val builder = addressBox.query().equal(Address_.street, "Sesame Street")
10
// ...which are linked from a Person named "Elmo"
11
builder.link(Address_.persons).equal(Person_.name, "Elmo")
12
val sesameStreetsWithElmo = builder.build().find()
Copied!
1
@Entity()
2
class Address {
3
...
4
5
@Backlink()
6
final persons = ToMany<Person>();
7
}
8
9
// get all Address objects with street "Sesame Street"...
10
QueryBuilder<Address> builder =
11
addressBox.query(Address_.street.equals('Sesame Street'));
12
// ...which are linked from a Person named "Elmo"
13
builder.linkMany(Address_.persons, Person_.name.equals('Elmo'));
14
Query<Address> query = builder.build();
15
List<Address> sesameStreetsWithElmo = query.find();
16
query.close();
Copied!
But actually, you do not have to modify the Address entity (you still can if you need the @Backlink elsewhere). Instead, we can use the backlink() method to create a backlink to the addresses relation from Person just for that query:
Java
Kotlin
Dart
1
// get all Address objects with street "Sesame Street"...
2
QueryBuilder<Address> builder = addressBox.query()
3
.equal(Address_.street, "Sesame Street");
4
// ...which are linked from a Person named "Elmo"
5
builder.backlink(Person_.addresses).equal(Person_.name, "Elmo");
6
List<Address> sesameStreetsWithElmo = builder.build().find();
Copied!
1
// get all Address objects with street "Sesame Street"...
2
val builder = addressBox.query().equal(Address_.street, "Sesame Street")
3
// ...which are linked from a Person named "Elmo"
4
builder.backlink(Person_.addresses).equal(Person_.name, "Elmo")
5
val sesameStreetsWithElmo = builder.build().find()
Copied!
1
// get all Address objects with street "Sesame Street"...
2
QueryBuilder<Address> builder =
3
addressBox.query(Address_.street.equals('Sesame Street'));
4
// ...which are linked from a Person named "Elmo"
5
builder.backlinkMany(Person_.addresses, Person_.name.equals('Elmo'));
6
Query<Address> query = builder.build();
7
List<Address> sesameStreetsWithElmo = query.find();
8
query.close();
Copied!

Eager Loading of Relations

Only Java/Kotlin
By default relations are loaded lazily: when you first access a ToOne or ToMany property it will perform a database lookup to get its data. On each subsequent access it will use a cached version of that data.
Java
Kotlin
1
List<Customer> customers = customerBox.query().build().find();
2
// Customer has a ToMany called orders.
3
// First access: this will cause a database lookup.
4
Order order = customers.get(0).orders.get(0);
Copied!
1
val customers = customerBox.query().build().find()
2
// Customer has a ToMany called orders
3
val order = customers[0].orders[0] // first access: causes a database lookup
Copied!
While this initial lookup is fast, you might want to prefetch ToOne or ToMany values before the query results are returned. To do this call the QueryBuilder.eager method when building your query and pass the RelationInfo objects associated with the ToOne and ToMany properties to prefetch:
Java
Kotlin
1
List<Customer> customers = customerBox.query()
2
.eager(Customer_.orders) // Customer has a ToMany called orders.
3
.build()
4
.find();
5
// First access: this will cause a database lookup.
6
Order order = customers.get(0).orders.get(0);
Copied!
1
val customers = customerBox.query()
2
.eager(Customer_.orders) // Customer has a ToMany called orders
3
.build()
4
.find()
5
customers[0].orders[0] // first access: this will NOT cause a database lookup
Copied!
Eager loading only works one level deep. If you have nested relations and you want to prefetch relations of all children, you can instead add a query filter as described below. Use it to simply access all relation properties, which triggers them to lookup there values as described above.

Query filters

Only Java/Kotlin
Query filters come into play when you are looking for objects that need to match complex conditions, which cannot be fully expressed with the QueryBuilder class. Filters are written in Java and thus can express any complexity. Needless to say, that database conditions can be matched more efficiently than Java-based filters. Thus you will get the best results when you use both together:
    1.
    Narrow down results using standard database conditions to a reasonable number (use QueryBuilder to get “candidates”)
    2.
    Now filter those candidates using the QueryFilter Java interface to identify final results
A QueryFilter implementation looks at one candidate object at a time and returns true if the candidate is a result or false if not.
Example:
1
// Reduce object count to reasonable value.
2
songBox.query().equal(Song_.bandId, bandId)
3
// Filter is performed on candidate objects.
4
.filter((song) -> song.starCount * 2 > song.downloads);
Copied!
Notes on performance: 1) ObjectBox creates objects very fast. 2) The virtual machine is tuned to garbage collect short-lived objects. Notes 1) and 2) combined makes a case for filtering because ObjectBox creates candidate objects of which some are not used and thus get garbage collected quickly after their creation.

Query filters and ToMany relation

The ToMany class offers additional methods that can be convenient in query filters:
    hasA: returns true if one of the elements matches the given QueryFilter
    hasAll: returns true if all of the elements match the given QueryFilter
    getById: return the element with the given ID (value of the property with the @Id annotation)
Last modified 8d ago