Relational algebra is at the heart of Calcite. Every query is represented as a tree of relational operators. You can translate from SQL to relational algebra, or you can build the tree directly.
Planner rules transform expression trees using mathematical identities that preserve semantics. For example, it is valid to push a filter into an input of an inner join if the filter does not reference columns from the other input.
Calcite optimizes queries by repeatedly applying planner rules to a relational expression. A cost model guides the process, and the planner engine generates an alternative expression that has the same semantics as the original but a lower cost.
The planning process is extensible. You can add your own relational operators, planner rules, cost model, and statistics.
The simplest way to build a relational expression is to use the algebra builder, RelBuilder. Here is an example:
(You can find the full code for this and other examples in RelBuilderExample.java.)
The code prints
It has created a scan of the
EMP table; equivalent to the SQL
Adding a Project
Now, let’s add a Project, the equivalent of
We just add a call to the
project method before calling
and the output is
The two calls to
builder.field create simple expressions
that return the fields from the input relational expression,
namely the TableScan created by the
Calcite has converted them to field references by ordinal,
Adding a Filter and Aggregate
A query with an Aggregate, and a Filter:
is equivalent to SQL
Push and pop
The builder uses a stack to store the relational expression produced by one step and pass it as an input to the next step. This allows the methods that produce relational expressions to produce a builder.
Most of the time, the only stack method you will use is
build(), to get the
last relational expression, namely the root of the tree.
Sometimes the stack becomes so deeply nested it gets confusing. To keep things straight, you can remove expressions from the stack. For example, here we are building a bushy join:
We build it in three stages. Store the intermediate results in variables
right, and use
push() to put them back on the stack when it is
time to create the final
Field names and ordinals
You can reference a field by name or ordinal.
Ordinals are zero-based. Each operator guarantees the order in which its output
fields occur. For example,
Project returns the fields in the generated by
each of the scalar expressions.
The field names of an operator are guaranteed to be unique, but sometimes that means that the names are not exactly what you expect. For example, when you join EMP to DEPT, one of the output fields will be called DEPTNO and another will be called something like DEPTNO_1.
Some relational expression methods give you more control over field names:
projectlets you wrap expressions using
alias(expr, fieldName). It removes the wrapper but keeps the suggested name (as long as it is unique).
values(String fieldNames, Object... values)accepts an array of field names. If any element of the array is null, the builder will generate a unique name.
If an expression projects an input field, or a cast of an input field, it will use the name of that input field.
Once the unique field names have been assigned, the names are immutable.
If you have a particular
RelNode instance, you can rely on the field names not
changing. In fact, the whole relational expression is immutable.
But if a relational expression has passed through several rewrite rules (see (RelOptRule), the field names of the resulting expression might not look much like the originals. At that point it is better to reference fields by ordinal.
When you are building a relational expression that accepts multiple inputs, you need to build field references that take that into account. This occurs most often when building join conditions.
Suppose you are building a join on EMP, which has 8 fields [EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO] and DEPT, which has 3 fields [DEPTNO, DNAME, LOC]. Internally, Calcite represents those fields as offsets into a combined input row with 11 fields: the first field of the left input is field #0 (0-based, remember), and the first field of the right input is field #8.
But through the builder API, you specify which field of which input.
To reference “SAL”, internal field #5,
builder.field(2, 0, "SAL"),
builder.field(2, "EMP", "SAL"),
builder.field(2, 0, 5).
This means “the field #5 of input #0 of two inputs”.
(Why does it need to know that there are two inputs? Because they are stored on
the stack; input #1 is at the top of the stack, and input #0 is below it.
If we did not tell the builder that were two inputs, it would not know how deep
to go for input #0.)
Similarly, to reference “DNAME”, internal field #9 (8 + 1),
builder.field(2, 1, "DNAME"),
builder.field(2, "DEPT", "DNAME"),
builder.field(2, 1, 1).
The following methods create a relational expression
push it onto the stack, and
||Creates a TableScan.|
||Creates a Values.|
||Creates a Filter over the AND of the given predicates.|
||Creates a Project. To override the default name, wrap expressions using
||Creates a Project that permutes the fields using
||Creates a Project that converts the fields to the given types, optionally also renaming them.|
||Creates an Aggregate.|
||Creates an Aggregate that eliminates duplicate records.|
||Creates a Sort.
In the first form, field ordinals are 0-based, and a negative ordinal indicates descending; for example, -2 means field 1 descending.
In the other forms, you can wrap expressions in
||Creates a Sort with offset and limit.|
||Creates a Sort that does not sort, only applies with offset and limit.|
||Creates a Join of the two most recent relational expressions.
The first form joins on a boolean expression (multiple conditions are combined using AND).
The last form joins on named fields; each side must have a field of each name.
||Creates a SemiJoin of the two most recent relational expressions.|
||Creates a Union of the
||Creates an Intersect of the
||Creates a Minus of the two most recent relational expressions.|
||Creates a Match.|
expr...Array of RexNode
orderKeysIterable of RexNode
fieldOrdinalOrdinal of a field within its row (starting from 0)
fieldNameName of a field, unique within its row
fieldName...Array of String
fieldNamesIterable of String
aggCall...Array of RelBuilder.AggCall
aggCallListIterable of RelBuilder.AggCall
value...Array of Object
tupleListIterable of List of RexLiteral
varHolderHolder of RexCorrelVariable
patternsMap whose key is String, value is RexNode
subsetsMap whose key is String, value is a sorted set of String
The builder methods perform various optimizations, including:
projectreturns its input if asked to project all columns in order
filterflattens the condition (so an
ORmay have more than 2 children), simplifies (converting say
x = 1 AND TRUEto
x = 1)
- If you apply
limit, the effect is as if you had called
There are annotation methods that add information to the top relational expression on the stack:
||Assigns a table alias to the top relational expression on the stack|
||Creates a correlation variable referencing the top relational expression|
||Pops the most recently created relational expression off the stack|
||Pushes a relational expression onto the stack. Relational methods such as
||Pushes a collection of relational expressions onto the stack|
||Returns the relational expression most recently put onto the stack, but does not remove it|
Scalar expression methods
The following methods return a scalar expression (RexNode).
Many of them use the contents of the stack. For example,
returns a reference to the “DEPTNO” field of the relational expression just
added to the stack.
||Reference, by name, to a field of the top-most relational expression|
||Reference, by ordinal, to a field of the top-most relational expression|
||Reference, by name, to a field of the (
||Reference, by ordinal, to a field of the (
||Reference, by table alias and field name, to a field at most
||Reference, by table alias and field name, to a field of the top-most relational expressions|
||Reference, by name, to a field of a record-valued expression|
||Reference, by ordinal, to a field of a record-valued expression|
||List of expressions referencing input fields by ordinal|
||List of expressions referencing input fields by a given mapping|
||List of expressions,
||Call to a function or operator|
||Logical AND. Flattens nested ANDs, and optimizes cases involving TRUE and FALSE.|
||Logical OR. Flattens nested ORs, and optimizes cases involving TRUE and FALSE.|
||Checks whether an expression is null|
||Checks whether an expression is not null|
||Renames an expression (only valid as an argument to
||Converts an expression to a given type|
||Changes sort direction to descending (only valid as an argument to
||Changes sort order to nulls first (only valid as an argument to
||Changes sort order to nulls last (only valid as an argument to
The following methods return patterns for use in
||Quantifies a pattern|
||Permutes a pattern|
||Excludes a pattern|
Group key methods
The following methods return a RelBuilder.GroupKey.
||Creates a group key of the given expressions|
||Creates a group key of the given expressions with grouping sets|
||Creates a group key of the given input columns with grouping sets|
Aggregate call methods
The following methods return an RelBuilder.AggCall.
||Creates a call to a given aggregate function, with an optional filter expression|
||Creates a call to the COUNT aggregate function|
||Creates a call to the COUNT(*) aggregate function|
||Creates a call to the SUM aggregate function|
||Creates a call to the MIN aggregate function|
||Creates a call to the MAX aggregate function|