Navigation

Query Engine

Overview

To filter data in your Realms, you can leverage Realm Database’s query engine. Realm Database’s query engine uses a language inspired by NSPredicate.

Operators

There are several types of operators available to filter a Realm collection. Filters work by evaluating an operator expression for every object in the collection being filtered. If the expression resolves to true, Realm Database includes the object in the results collection.

An expression consists of one of the following:

  • The name of a property of the object currently being evaluated.
  • An operator and up to two argument expression(s).
  • A literal string, number, or date.

About the examples on this page

The examples in this page use a simple data set for a task list app. The two Realm object types are Project and Task. A Task has a name, assignee’s name, and completed flag. There is also an arbitrary number for priority – higher is more important – and a count of minutes spent working on it. A Project has zero or more Tasks.

See the schema for these two classes, Project and Task, below:

const TaskSchema = {
  name: "Task",
  properties: {
    name: "string",
    isComplete: "bool",
    priority: "int",
    progressMinutes: "int",
    assignee: "string?"
  }
};

const ProjectSchema = {
  name: "Project",
  properties: {
    name: "string",
    tasks: "Task[]"
  }
};

Comparison Operators

The most straightforward operation in a search is to compare values.

Operator Description
==
Evaluates to true if the left-hand expression is equal to the right-hand expression.
>
Evaluates to true if the left-hand numerical or date expression is greater than the right-hand numerical or date expression. For dates, this evaluates to true if the left-hand date is later than the right-hand date.
>=
Evaluates to true if the left-hand numerical or date expression is greater than or equal to the right-hand numerical or date expression. For dates, this evaluates to true if the left-hand date is later than or the same as the right-hand date.
in Evaluates to true if the left-hand expression is in the right-hand list.
<
Evaluates to true if the left-hand numerical or date expression is less than the right-hand numerical or date expression. For dates, this evaluates to true if the left-hand date is earlier than the right-hand date.
<=
Evaluates to true if the left-hand numeric expression is less than or equal to the right-hand numeric expression. For dates, this evaluates to true if the left-hand date is earlier than or the same as the right-hand date.
!=
Evaluates to true if the left-hand expression is not equal to the right-hand expression.

Example

The following example uses the query engine’s comparison operators to:

  • Find high priority tasks by comparing the value of the priority property value with a threshold number, above which priority can be considered high.
  • Find just-started or short-running tasks by seeing if the progressMinutes property falls within a certain range.
  • Find unassigned tasks by finding tasks where the assignee property is equal to null.
  • Find tasks assigned to specific teammates Ali or Jamie by seeing if the assignee property is in a list of names.
console.log("Number of high priority tasks: "
  + tasks.filtered("priority > 5").length);

console.log(
  "Number of just-started or short-running tasks: " +
    tasks.filtered("1 <= progressMinutes && progressMinutes < 10").length
);

console.log("Number of unassigned tasks: "
  + tasks.filtered("assignee == null").length);

Logical Operators

You can make compound predicates using logical operators.

Operator Description
and
&&
Evaluates to true if both left-hand and right-hand expressions are true.
not
!
Negates the result of the given expression.
or
||
Evaluates to true if either expression returns true.

Example

We can use the query language’s logical operators to find all of Ali’s completed tasks. That is, we find all tasks where the assignee property value is equal to ‘Ali’ AND the isComplete property value is true:

console.log(
  "Number of Ali's complete tasks: " +
    tasks.filtered("assignee == 'Ali' && isComplete == true").length
);

String Operators

You can compare string values using these string operators. Regex-like wildcards allow more flexibility in search.

Operator Description
beginsWith
Evaluates to true if the left-hand string expression begins with the right-hand string expression. This is similar to contains, but only matches if the left-hand string expression is found at the beginning of the right-hand string expression.
contains Evaluates to true if the left-hand string expression is found anywhere in the right-hand string expression. Not supported on the C# SDK.
endsWith
Evaluates to true if the left-hand string expression ends with the right-hand string expression. This is similar to contains, but only matches if the left-hand string expression is found at the very end of the right-hand string expression.
like

Evaluates to true if the left-hand string expression matches the right-hand string wildcard string expression. A wildcard string expression is a string that uses normal characters with two special wildcard characters:

  • The * wildcard matches zero or more of any character
  • The ? wildcard matches any character.

For example, the wildcard string “d?g” matches “dog”, “dig”, and “dug”, but not “ding”, “dg”, or “a dog”.

== (JS, Obj-C, Swift)
Evaluates to true if the left-hand string is lexicographically equal to the right-hand string.

Example

We use the query engine’s string operators to find projects with a name starting with the letter ‘e’ and projects with names that contain ‘ie’:

// Use [c] for case-insensitivity.
console.log(
  "Projects that start with 'e': " +
    projects.filtered("name BEGINSWITH[c] 'e'").length
);
console.log(
  "Projects that contain 'ie': " +
    projects.filtered("name CONTAINS 'ie'").length
);

Aggregate Operators

You can apply an aggregate operator to a collection property of a Realm object. Aggregate operators traverse a collection and reduce it to a single value.

Operator Description
@avg
Evaluates to the average value of a given numerical property across a collection.
@count
Evaluates to the number of objects in the given collection.
@max
Evaluates to the highest value of a given numerical property across a collection.
@min
Evaluates to the lowest value of a given numerical property across a collection.
@sum
Evaluates to the sum of a given numerical property across a collection.

Example

We create a couple of filters to show different facets of the data:

  • Projects with average tasks priority above 5.
  • Long running projects.
console.log(
  "Number of projects with average tasks priority above 5: " +
    projects.filtered("tasks.@avg.priority > 5").length
);
console.log(
  "Number of long-running projects: " +
    projects.filtered("tasks.@sum.progressMinutes > 120").length
);

Set Operators

A set operator uses specific rules to determine whether to pass each input collection object to the output collection by applying a given predicate to every element of a given list property of the object.

Operator Description
All Returns objects where the predicate evaluates to true for all objects in the collection.
Any Returns objects where the predicate evaluates to true for any objects in the collection.
None Returns objects where the predicate evaluates to false for all objects in the collection.

Example

We use the query engine’s set operators to find:

  • Projects with no complete tasks.
  • Projects with any top priority tasks.
console.log(
  "Number of projects with no complete tasks: " +
    projects.filtered("ALL tasks.isComplete == false").length
);
console.log(
  "Number of projects with any top priority tasks: " +
    projects.filtered("ANY tasks.priority == 10").length
);

Summary

  • There are several categories of operators available to filter results: comparison, logical, string, aggregate, and set operators.
←   Writes Encrypt a Realm  →