Table API and SQL are experimental features
The Table API is a SQL-like expression language for relational stream and batch processing that can be easily embedded in Flink’s DataSet and DataStream APIs (Java and Scala).
The Table API and SQL interface operate on a relational Table
abstraction, which can be created from external data sources, or existing DataSets and DataStreams. With the Table API, you can apply relational operators such as selection, aggregation, and joins on Table
s.
Table
s can also be queried with regular SQL, as long as they are registered (see Registering Tables). The Table API and SQL offer equivalent functionality and can be mixed in the same program. When a Table
is converted back into a DataSet
or DataStream
, the logical plan, which was defined by relational operators and SQL queries, is optimized using Apache Calcite and transformed into a DataSet
or DataStream
program.
The Table API and SQL are part of the flink-table Maven project. The following dependency must be added to your project in order to use the Table API and SQL:
Note: The Table API is currently not part of the binary distribution. See linking with it for cluster execution here.
TableEnvironment
s have an internal table catalog to which tables can be registered with a unique name. After registration, a table can be accessed from the TableEnvironment
by its name.
Note: DataSet
s or DataStream
s can be directly converted into Table
s without registering them in the TableEnvironment
.
A DataSet
is registered as a Table
in a BatchTableEnvironment
as follows:
Note: The name of a DataSet
Table
must not match the ^_DataSetTable_[0-9]+
pattern which is reserved for internal use only.
A DataStream
is registered as a Table
in a StreamTableEnvironment
as follows:
Note: The name of a DataStream
Table
must not match the ^_DataStreamTable_[0-9]+
pattern which is reserved for internal use only.
A Table
that originates from a Table API operation or a SQL query is registered in a TableEnvironment
as follows:
A registered Table
that originates from a Table API operation or SQL query is treated similarly as a view as known from relational DBMS, i.e., it can be inlined when optimizing the query.
An external table is registered in a TableEnvironment
using a TableSource
as follows:
A TableSource
can provide access to data stored in various storage systems such as databases (MySQL, HBase, …), file formats (CSV, Apache Parquet, Avro, ORC, …), or messaging systems (Apache Kafka, RabbitMQ, …).
Currently, Flink provides the CsvTableSource
to read CSV files and the Kafka08JsonTableSource
/Kafka09JsonTableSource
to read JSON objects from Kafka.
A custom TableSource
can be defined by implementing the BatchTableSource
or StreamTableSource
interface.
Class name | Maven dependency | Batch? | Streaming? | Description |
CsvTableSouce |
flink-table |
Y | Y | A simple source for CSV files. |
Kafka08JsonTableSource |
flink-connector-kafka-0.8 |
N | Y | A Kafka 0.8 source for JSON data. |
Kafka09JsonTableSource |
flink-connector-kafka-0.9 |
N | Y | A Kafka 0.9 source for JSON data. |
All sources that come with the flink-table
dependency can be directly used by your Table programs. For all other table sources, you have to add the respective dependency in addition to the flink-table
dependency.
To use the Kafka JSON source, you have to add the Kafka connector dependency to your project:
flink-connector-kafka-0.8
for Kafka 0.8, andflink-connector-kafka-0.9
for Kafka 0.9, respectively.You can then create the source as follows (example for Kafka 0.8):
// The JSON field names and types
String[] fieldNames = new String[] { "id", "name", "score"};
Class<?>[] fieldTypes = new Class<?>[] { Integer.class, String.class, Double.class };
KafkaJsonTableSource kafkaTableSource = new Kafka08JsonTableSource(
kafkaTopic,
kafkaProperties,
fieldNames,
fieldTypes);
By default, a missing JSON field does not fail the source. You can configure this via:
// Fail on missing JSON field
tableSource.setFailOnMissingField(true);
You can work with the Table as explained in the rest of the Table API guide:
tableEnvironment.registerTableSource("kafka-source", kafkaTableSource);
Table result = tableEnvironment.ingest("kafka-source");
The CsvTableSource
is already included in flink-table
without additional dependecies.
It can be configured with the following properties:
path
The path to the CSV file, required.fieldNames
The names of the table fields, required.fieldTypes
The types of the table fields, required.fieldDelim
The field delimiter, ","
by default.rowDelim
The row delimiter, "\n"
by default.quoteCharacter
An optional quote character for String values, null
by default.ignoreFirstLine
Flag to ignore the first line, false
by default.ignoreComments
An optional prefix to indicate comments, null
by default.lenient
Flag to skip records with parse error instead to fail, false
by default.You can create the source as follows:
You can work with the Table as explained in the rest of the Table API guide in both stream and batch TableEnvironment
s:
The Table API provides methods to apply relational operations on DataSets and Datastreams both in Scala and Java.
The central concept of the Table API is a Table
which represents a table with relational schema (or relation). Tables can be created from a DataSet
or DataStream
, converted into a DataSet
or DataStream
, or registered in a table catalog using a TableEnvironment
. A Table
is always bound to a specific TableEnvironment
. It is not possible to combine Tables of different TableEnvironments.
Note: The only operations currently supported on streaming Tables are selection, projection, and union.
When using Flink’s Java DataSet API, DataSets are converted to Tables and Tables to DataSets using a TableEnvironment
.
The following example shows:
DataSet
is converted to a Table
,Table
is converted back to a DataSet
.With Java, expressions must be specified by Strings. The embedded expression DSL is not supported.
Please refer to the Javadoc for a full list of supported operations and a description of the expression syntax.
The Table API is enabled by importing org.apache.flink.api.scala.table._
. This enables
implicit conversions to convert a DataSet
or DataStream
to a Table. The following example shows:
DataSet
is converted to a Table
,Table
is converted back to a DataSet
.The expression DSL uses Scala symbols to refer to field names and code generation to transform expressions to efficient runtime code. Please note that the conversion to and from Tables only works when using Scala case classes or Java POJOs. Please refer to the Type Extraction and Serialization section to learn the characteristics of a valid POJO.
Another example shows how to join two Tables:
Notice, how the field names of a Table can be changed with as()
or specified with toTable()
when converting a DataSet to a Table. In addition, the example shows how to use Strings to specify relational expressions.
Creating a Table
from a DataStream
works in a similar way.
The following example shows how to convert a DataStream
to a Table
and filter it with the Table API.
Please refer to the Scaladoc for a full list of supported operations and a description of the expression syntax.
A registered table can be accessed from a TableEnvironment
as follows:
tEnv.scan("tName")
scans a Table
that was registered as "tName"
in a BatchTableEnvironment
.tEnv.ingest("tName")
ingests a Table
that was registered as "tName"
in a StreamTableEnvironment
.The Table API features a domain-specific language to execute language-integrated queries on structured data in Scala and Java. This section gives a brief overview of the available operators. You can find more details of operators in the Javadoc.
Operators | Description |
---|---|
Select |
Similar to a SQL SELECT statement. Performs a select operation. You can use star ( |
As |
Renames fields. |
Where / Filter |
Similar to a SQL WHERE clause. Filters out rows that do not pass the filter predicate. or |
GroupBy |
Similar to a SQL GROUPBY clause. Groups the rows on the grouping keys, with a following aggregation operator to aggregate rows group-wise. |
Join |
Similar to a SQL JOIN clause. Joins two tables. Both tables must have distinct field names and at least one equality join predicate must be defined through join operator or using a where or filter operator. |
LeftOuterJoin |
Similar to a SQL LEFT OUTER JOIN clause. Joins two tables. Both tables must have distinct field names and at least one equality join predicate must be defined. |
RightOuterJoin |
Similar to a SQL RIGHT OUTER JOIN clause. Joins two tables. Both tables must have distinct field names and at least one equality join predicate must be defined. |
FullOuterJoin |
Similar to a SQL FULL OUTER JOIN clause. Joins two tables. Both tables must have distinct field names and at least one equality join predicate must be defined. |
Union |
Similar to a SQL UNION clause. Unions two tables with duplicate records removed. Both tables must have identical field types. |
UnionAll |
Similar to a SQL UNION ALL clause. Unions two tables. Both tables must have identical field types. |
Intersect |
Similar to a SQL INTERSECT clause. Intersect returns records that exist in both tables. If a record is present one or both tables more than once, it is returned just once, i.e., the resulting table has no duplicate records. Both tables must have identical field types. |
IntersectAll |
Similar to a SQL INTERSECT ALL clause. IntersectAll returns records that exist in both tables. If a record is present in both tables more than once, it is returned as many times as it is present in both tables, i.e., the resulting table might have duplicate records. Both tables must have identical field types. |
Minus |
Similar to a SQL EXCEPT clause. Minus returns records from the left table that do not exist in the right table. Duplicate records in the left table are returned exactly once, i.e., duplicates are removed. Both tables must have identical field types. |
MinusAll |
Similar to a SQL EXCEPT ALL clause. MinusAll returns the records that do not exist in the right table. A record that is present n times in the left table and m times in the right table is returned (n - m) times, i.e., as many duplicates as are present in the right table are removed. Both tables must have identical field types. |
Distinct |
Similar to a SQL DISTINCT clause. Returns records with distinct value combinations. |
Order By |
Similar to a SQL ORDER BY clause. Returns records globally sorted across all parallel partitions. |
Limit |
Similar to a SQL LIMIT clause. Limits a sorted result to a specified number of records from an offset position. Limit is technically part of the Order By operator and thus must be preceded by it. or |
Operators | Description |
---|---|
Select |
Similar to a SQL SELECT statement. Performs a select operation. You can use star ( |
As |
Renames fields. |
Where / Filter |
Similar to a SQL WHERE clause. Filters out rows that do not pass the filter predicate. or |
GroupBy |
Similar to a SQL GROUPBY clause. Groups rows on the grouping keys, with a following aggregation operator to aggregate rows group-wise. |
Join |
Similar to a SQL JOIN clause. Joins two tables. Both tables must have distinct field names and an equality join predicate must be defined using a where or filter operator. |
LeftOuterJoin |
Similar to a SQL LEFT OUTER JOIN clause. Joins two tables. Both tables must have distinct field names and at least one equality join predicate must be defined. |
RightOuterJoin |
Similar to a SQL RIGHT OUTER JOIN clause. Joins two tables. Both tables must have distinct field names and at least one equality join predicate must be defined. |
FullOuterJoin |
Similar to a SQL FULL OUTER JOIN clause. Joins two tables. Both tables must have distinct field names and at least one equality join predicate must be defined. |
Union |
Similar to a SQL UNION clause. Unions two tables with duplicate records removed, both tables must have identical field types. |
UnionAll |
Similar to a SQL UNION ALL clause. Unions two tables, both tables must have identical field types. |
Intersect |
Similar to a SQL INTERSECT clause. Intersect returns records that exist in both tables. If a record is present in one or both tables more than once, it is returned just once, i.e., the resulting table has no duplicate records. Both tables must have identical field types. |
IntersectAll |
Similar to a SQL INTERSECT ALL clause. IntersectAll returns records that exist in both tables. If a record is present in both tables more than once, it is returned as many times as it is present in both tables, i.e., the resulting table might have duplicate records. Both tables must have identical field types. |
Minus |
Similar to a SQL EXCEPT clause. Minus returns records from the left table that do not exist in the right table. Duplicate records in the left table are returned exactly once, i.e., duplicates are removed. Both tables must have identical field types. |
MinusAll |
Similar to a SQL EXCEPT ALL clause. MinusAll returns the records that do not exist in the right table. A record that is present n times in the left table and m times in the right table is returned (n - m) times, i.e., as many duplicates as are present in the right table are removed. Both tables must have identical field types. |
Distinct |
Similar to a SQL DISTINCT clause. Returns records with distinct value combinations. |
Order By |
Similar to a SQL ORDER BY clause. Returns records globally sorted across all parallel partitions. |
Limit |
Similar to a SQL LIMIT clause. Limits a sorted result to a specified number of records from an offset position. Limit is technically part of the Order By operator and thus must be preceded by it. or |
Some of the operators in previous sections expect one or more expressions. Expressions can be specified using an embedded Scala DSL or as Strings. Please refer to the examples above to learn how expressions can be specified.
This is the EBNF grammar for expressions:
Here, literal
is a valid Java literal, fieldReference
specifies a column in the data (or all columns if *
is used), and functionIdentifier
specifies a supported scalar function. The
column names and function names follow Java identifier syntax. The column name rowtime
is a reserved logical attribute in streaming environments. Expressions specified as Strings can also use prefix notation instead of suffix notation to call operators and functions.
If working with exact numeric values or large decimals is required, the Table API also supports Java’s BigDecimal type. In the Scala Table API decimals can be defined by BigDecimal("123456")
and in Java by appending a “p” for precise e.g. 123456p
.
In order to work with temporal values the Table API supports Java SQL’s Date, Time, and Timestamp types. In the Scala Table API literals can be defined by using java.sql.Date.valueOf("2016-06-27")
, java.sql.Time.valueOf("10:10:42")
, or java.sql.Timestamp.valueOf("2016-06-27 10:10:42.123")
. The Java and Scala Table API also support calling "2016-06-27".toDate()
, "10:10:42".toTime()
, and "2016-06-27 10:10:42.123".toTimestamp()
for converting Strings into temporal types. Note: Since Java’s temporal SQL types are time zone dependent, please make sure that the Flink Client and all TaskManagers use the same time zone.
Temporal intervals can be represented as number of months (Types.INTERVAL_MONTHS
) or number of milliseconds (Types.INTERVAL_MILLIS
). Intervals of same type can be added or subtracted (e.g. 1.hour + 10.minutes
). Intervals of milliseconds can be added to time points (e.g. "2016-08-10".toDate + 5.days
).
The Table API is a declarative API to define queries on batch and streaming tables. Projection, selection, and union operations can be applied both on streaming and batch tables without additional semantics. Aggregations on (possibly) infinite streaming tables, however, can only be computed on finite groups of records. Group-window aggregates group rows into finite groups based on time or row-count intervals and evaluate aggregation functions once per group. For batch tables, group-windows are a convenient shortcut to group records by time intervals.
Group-windows are defined using the window(w: GroupWindow)
clause. The following example shows how to define a group-window aggregation on a table.
In streaming environments, group-window aggregates can only be computed in parallel, if they are keyed, i.e., there is an additional groupBy
attribute. Group-window aggregates without additional groupBy
, such as in the example above, can only be evaluated in a single, non-parallel task. The following example shows how to define a keyed group-window aggregation on a table.
The GroupWindow
parameter defines how rows are mapped to windows. GroupWindow
is not an interface that users can implement. Instead, the Table API provides a set of predefined GroupWindow
classes with specific semantics, which are translated into underlying DataStream
or DataSet
operations. The supported window definitions are listed below.
By assigning the group-window an alias using as
, properties such as the start and end timestamp of a time window can be accessed in the select
statement.
A tumbling window assigns rows to non-overlapping, continuous windows of fixed length. For example, a tumbling window of 5 minutes groups rows in 5 minutes intervals. Tumbling windows can be defined on event-time, processing-time, or on a row-count.
Tumbling windows are defined by using the Tumble
class as follows:
Method | Required? | Description |
---|---|---|
over |
Required. | Defines the length the window, either as time or row-count interval. |
on |
Required for streaming event-time windows and windows on batch tables. | Defines the time mode for streaming tables (rowtime is a logical system attribute); for batch tables, the time attribute on which records are grouped. |
as |
Optional. | Assigns an alias to the window that can be used in the following select() clause to access window properties such as window start or end time. |
A sliding window has a fixed size and slides by a specified slide interval. If the slide interval is smaller than the window size, sliding windows are overlapping. Thus, rows can be assigned to multiple windows. For example, a sliding window of 15 minutes size and 5 minute slide interval assigns each row to 3 different windows of 15 minute size, which are evaluated in an interval of 5 minutes. Sliding windows can be defined on event-time, processing-time, or on a row-count.
Sliding windows are defined by using the Slide
class as follows:
Method | Required? | Description |
---|---|---|
over |
Required. | Defines the length of the window, either as time or row-count interval. |
every |
Required. | Defines the slide interval, either as time or row-count interval. The slide interval must be of the same type as the size interval. |
on |
Required for event-time windows and windows on batch tables. | Defines the time mode for streaming tables (rowtime is a logical system attribute); for batch tables, the time attribute on which records are grouped |
as |
Optional. | Assigns an alias to the window that can be used in the following select() clause to access window properties such as window start or end time. |
Session windows do not have a fixed size but their bounds are defined by an interval of inactivity, i.e., a session window is closes if no event appears for a defined gap period. For example a session window with a 30 minute gap starts when a row is observed after 30 minutes inactivity (otherwise the row would be added to an existing window) and is closed if no row is added within 30 minutes. Session windows can work on event-time or processing-time.
A session window is defined by using the Session
class as follows:
Method | Required? | Description |
---|---|---|
withGap |
Required. | Defines the gap between two windows as time interval. |
on |
Required for event-time windows and windows on batch tables. | Defines the time mode for streaming tables (rowtime is a logical system attribute); for batch tables, the time attribute on which records are grouped |
as |
Optional. | Assigns an alias to the window that can be used in the following select() clause to access window properties such as window start or end time. |
Currently the following features are not supported yet:
SQL queries are specified using the sql()
method of the TableEnvironment
. The method returns the result of the SQL query as a Table
which can be converted into a DataSet
or DataStream
, used in subsequent Table API queries, or written to a TableSink
(see Writing Tables to External Sinks). SQL and Table API queries can seamlessly mixed and are holistically optimized and translated into a single DataStream or DataSet program.
A Table
, DataSet
, DataStream
, or external TableSource
must be registered in the TableEnvironment
in order to be accessible by a SQL query (see Registering Tables).
Note: Flink’s SQL support is not feature complete, yet. Queries that include unsupported SQL features will cause a TableException
. The limitations of SQL on batch and streaming tables are listed in the following sections.
The current version supports selection (filter), projection, inner equi-joins, grouping, non-distinct aggregates, and sorting on batch tables.
Among others, the following SQL features are not supported, yet:
COUNT(DISTINCT name)
)Note: Tables are joined in the order in which they are specified in the FROM
clause. In some cases the table order must be manually tweaked to resolve Cartesian products.
SQL queries can be executed on streaming Tables (Tables backed by DataStream
or StreamTableSource
) like standard SQL.
The current version of streaming SQL only supports SELECT
, FROM
, WHERE
, and UNION
clauses. Aggregations or joins are not supported yet.
Flink uses Apache Calcite for SQL parsing. Currently, Flink SQL only supports query-related SQL syntax and only a subset of the comprehensive SQL standard. The following BNF-grammar describes the supported SQL features:
query:
values
| {
select
| selectWithoutFrom
| query UNION [ ALL ] query
| query EXCEPT query
| query INTERSECT query
}
[ ORDER BY orderItem [, orderItem ]* ]
[ LIMIT { count | ALL } ]
[ OFFSET start { ROW | ROWS } ]
[ FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } ONLY]
orderItem:
expression [ ASC | DESC ]
select:
SELECT [ ALL | DISTINCT ]
{ * | projectItem [, projectItem ]* }
FROM tableExpression
[ WHERE booleanExpression ]
[ GROUP BY { groupItem [, groupItem ]* } ]
[ HAVING booleanExpression ]
selectWithoutFrom:
SELECT [ ALL | DISTINCT ]
{ * | projectItem [, projectItem ]* }
projectItem:
expression [ [ AS ] columnAlias ]
| tableAlias . *
tableExpression:
tableReference [, tableReference ]*
| tableExpression [ NATURAL ] [ LEFT | RIGHT | FULL ] JOIN tableExpression [ joinCondition ]
joinCondition:
ON booleanExpression
| USING '(' column [, column ]* ')'
tableReference:
tablePrimary
[ [ AS ] alias [ '(' columnAlias [, columnAlias ]* ')' ] ]
tablePrimary:
[ TABLE ] [ [ catalogName . ] schemaName . ] tableName
values:
VALUES expression [, expression ]*
groupItem:
expression
| '(' ')'
| '(' expression [, expression ]* ')'
For a better definition of SQL queries within a Java String, Flink SQL uses a lexical policy similar to Java:
"SELECT a AS `my field` FROM t"
).Although not every SQL feature is implemented yet, some string combinations are already reserved as keywords for future use. If you want to use one of the following strings as a field name, make sure to surround them with backticks (e.g. `value`
, `count`
).
The Table API is built on top of Flink’s DataSet and DataStream API. Internally, it also uses Flink’s TypeInformation
to distinguish between types. The Table API does not support all Flink types so far. All supported simple types are listed in org.apache.flink.api.table.Types
. The following table summarizes the relation between Table API types, SQL types, and the resulting Java class.
Table API | SQL | Java type |
---|---|---|
Types.STRING |
VARCHAR |
java.lang.String |
Types.BOOLEAN |
BOOLEAN |
java.lang.Boolean |
Types.BYTE |
TINYINT |
java.lang.Byte |
Types.SHORT |
SMALLINT |
java.lang.Short |
Types.INT |
INTEGER, INT |
java.lang.Integer |
Types.LONG |
BIGINT |
java.lang.Long |
Types.FLOAT |
REAL, FLOAT |
java.lang.Float |
Types.DOUBLE |
DOUBLE |
java.lang.Double |
Types.DECIMAL |
DECIMAL |
java.math.BigDecimal |
Types.DATE |
DATE |
java.sql.Date |
Types.TIME |
TIME |
java.sql.Time |
Types.TIMESTAMP |
TIMESTAMP(3) |
java.sql.Timestamp |
Types.INTERVAL_MONTHS |
INTERVAL YEAR TO MONTH |
java.lang.Integer |
Types.INTERVAL_MILLIS |
INTERVAL DAY TO SECOND(3) |
java.lang.Long |
Advanced types such as generic types, composite types (e.g. POJOs or Tuples), and arrays can be fields of a row. Generic types and arrays are treated as a black box within Table API and SQL yet. Composite types, however, are fully supported types where fields of a composite type can be accessed using the .get()
operator in Table API and dot operator (e.g. MyTable.pojoColumn.myField
) in SQL. Composite types can also be flattened using .flatten()
in Table API or MyTable.pojoColumn.*
in SQL.
Both the Table API and SQL come with a set of built-in functions for data transformations. This section gives a brief overview of the available functions so far.
Function | Description |
---|---|
Returns true if the given expression is null. |
|
Returns true if the given expression is not null. |
|
Returns true if the given boolean expression is true. False otherwise (for null and false). |
|
Returns true if given boolean expression is false. False otherwise (for null and true). |
|
Returns true if the given boolean expression is not true (for null and false). False otherwise. |
|
Returns true if given boolean expression is not false (for null and true). False otherwise. |
|
Calculates the Euler's number raised to the given power. |
|
Calculates the base 10 logarithm of given value. |
|
Calculates the natural logarithm of given value. |
|
Calculates the given number raised to the power of the other value. |
|
Calculates the square root of a given value. |
|
Calculates the absolute value of given value. |
|
Calculates the largest integer less than or equal to a given number. |
|
Calculates the smallest integer greater than or equal to a given number. |
|
Creates a substring of the given string at the given index for the given length. The index starts at 1 and is inclusive, i.e., the character at the index is included in the substring. The substring has the specified length or less. |
|
Creates a substring of the given string beginning at the given index to the end. The start index starts at 1 and is inclusive. |
|
Removes leading and/or trailing characters from the given string. By default, whitespaces at both sides are removed. |
|
Returns the length of a String. |
|
Returns all of the characters in a string in upper case using the rules of the default locale. |
|
Returns all of the characters in a string in lower case using the rules of the default locale. |
|
Converts the initial letter of each word in a string to uppercase. Assumes a string containing only [A-Za-z0-9], everything else is treated as whitespace. |
|
Returns true, if a string matches the specified LIKE pattern. E.g. "Jo_n%" matches all strings that start with "Jo(arbitrary letter)n". |
|
Returns true, if a string matches the specified SQL regex pattern. E.g. "A+" matches all strings that consist of at least one "A". |
|
Returns the position of string in an other string starting at 1. Returns 0 if string could not be found. E.g. |
|
Replaces a substring of string with a string starting at a position (starting at 1). An optional length specifies how many characters should be removed. E.g. |
|
Parses a date string in the form "yy-mm-dd" to a SQL date. |
|
Parses a time string in the form "hh:mm:ss" to a SQL time. |
|
Parses a timestamp string in the form "yy-mm-dd hh:mm:ss.fff" to a SQL timestamp. |
|
Creates an interval of months for a given number of years. |
|
Creates an interval of months for a given number of months. |
|
Creates an interval of milliseconds for a given number of days. |
|
Creates an interval of milliseconds for a given number of hours. |
|
Creates an interval of milliseconds for a given number of minutes. |
|
Creates an interval of milliseconds for a given number of seconds. |
|
Creates an interval of milliseconds. |
|
Extracts parts of a time point or time interval. Returns the part as a long value. E.g. |
|
Returns the quarter of a year from a SQL date. E.g. |
|
Rounds a time point down to the given unit. E.g. |
|
Rounds a time point up to the given unit. E.g. |
|
Returns the current SQL date in UTC time zone. |
|
Returns the current SQL time in UTC time zone. |
|
Returns the current SQL timestamp in UTC time zone. |
|
Returns the current SQL time in local time zone. |
|
Returns the current SQL timestamp in local time zone. |
|
Determines whether two anchored time intervals overlap. Time point and temporal are transformed into a range defined by two time points (start, end). The function evaluates |
|
Creates an interval of rows. |
|
Converts a Flink composite type (such as Tuple, POJO, etc.) and all of its direct subtypes into a flat representation where every subtype is a separate field. In most cases the fields of the flat representation are named similarly to the original fields but with a dollar separator (e.g. |
|
Accesses the field of a Flink composite type (such as Tuple, POJO, etc.) by index or name and returns it's value. E.g. |
Function | Description |
---|---|
Returns true if the given expression is null. |
|
Returns true if the given expression is not null. |
|
Returns true if the given boolean expression is true. False otherwise (for null and false). |
|
Returns true if given boolean expression is false. False otherwise (for null and true). |
|
Returns true if the given boolean expression is not true (for null and false). False otherwise. |
|
Returns true if given boolean expression is not false (for null and true). False otherwise. |
|
Calculates the Euler's number raised to the given power. |
|
Calculates the base 10 logarithm of given value. |
|
Calculates the natural logarithm of given value. |
|
Calculates the given number raised to the power of the other value. |
|
Calculates the square root of a given value. |
|
Calculates the absolute value of given value. |
|
Calculates the largest integer less than or equal to a given number. |
|
Calculates the smallest integer greater than or equal to a given number. |
|
Creates a substring of the given string at the given index for the given length. The index starts at 1 and is inclusive, i.e., the character at the index is included in the substring. The substring has the specified length or less. |
|
Creates a substring of the given string beginning at the given index to the end. The start index starts at 1 and is inclusive. |
|
Removes leading and/or trailing characters from the given string. |
|
Returns the length of a String. |
|
Returns all of the characters in a string in upper case using the rules of the default locale. |
|
Returns all of the characters in a string in lower case using the rules of the default locale. |
|
Converts the initial letter of each word in a string to uppercase. Assumes a string containing only [A-Za-z0-9], everything else is treated as whitespace. |
|
Returns true, if a string matches the specified LIKE pattern. E.g. "Jo_n%" matches all strings that start with "Jo(arbitrary letter)n". |
|
Returns true, if a string matches the specified SQL regex pattern. E.g. "A+" matches all strings that consist of at least one "A". |
|
Returns the position of string in an other string starting at 1. Returns 0 if string could not be found. E.g. |
|
Replaces a substring of string with a string starting at a position (starting at 1). An optional length specifies how many characters should be removed. E.g. |
|
Parses a date string in the form "yy-mm-dd" to a SQL date. |
|
Parses a time string in the form "hh:mm:ss" to a SQL time. |
|
Parses a timestamp string in the form "yy-mm-dd hh:mm:ss.fff" to a SQL timestamp. |
|
Creates an interval of months for a given number of years. |
|
Creates an interval of months for a given number of months. |
|
Creates an interval of milliseconds for a given number of days. |
|
Creates an interval of milliseconds for a given number of hours. |
|
Creates an interval of milliseconds for a given number of minutes. |
|
Creates an interval of milliseconds for a given number of seconds. |
|
Creates an interval of milliseconds. |
|
Extracts parts of a time point or time interval. Returns the part as a long value. E.g. |
|
Returns the quarter of a year from a SQL date. E.g. |
|
Rounds a time point down to the given unit. E.g. |
|
Rounds a time point up to the given unit. E.g. |
|
Returns the current SQL date in UTC time zone. |
|
Returns the current SQL time in UTC time zone. |
|
Returns the current SQL timestamp in UTC time zone. |
|
Returns the current SQL time in local time zone. |
|
Returns the current SQL timestamp in local time zone. |
|
Determines whether two anchored time intervals overlap. Time point and temporal are transformed into a range defined by two time points (start, end). The function evaluates |
|
Creates an interval of rows. |
|
Converts a Flink composite type (such as Tuple, POJO, etc.) and all of its direct subtypes into a flat representation where every subtype is a separate field. In most cases the fields of the flat representation are named similarly to the original fields but with a dollar separator (e.g. |
|
Accesses the field of a Flink composite type (such as Tuple, POJO, etc.) by index or name and returns it's value. E.g. |
The Flink SQL functions (including their syntax) are a subset of Apache Calcite’s built-in functions. Most of the documentation has been adopted from the Calcite SQL reference.
Comparison functions | Description |
---|---|
Equals. |
|
Not equal. |
|
Greater than. |
|
Greater than or equal. |
|
Less than. |
|
Less than or equal. |
|
Whether value is null. |
|
Whether value is not null. |
|
Whether two values are not equal, treating null values as the same. |
|
Whether two values are equal, treating null values as the same. |
|
Whether value1 is greater than or equal to value2 and less than or equal to value3. |
|
Whether value1 is less than value2 or greater than value3. |
|
Whether string1 matches pattern string2. An escape character can be defined if necessary. |
|
Whether string1 does not match pattern string2. An escape character can be defined if necessary. |
|
Whether string1 matches regular expression string2. An escape character can be defined if necessary. |
|
Whether string1 does not match regular expression string2. An escape character can be defined if necessary. |
|
Whether value is equal to a value in a list. |
|
Whether value is not equal to every value in a list. |
|
Whether sub-query returns at least one row. Only supported if the operation can be rewritten in a join and group operation. |
Logical functions | Description |
---|---|
Whether boolean1 is TRUE or boolean2 is TRUE. |
|
Whether boolean1 and boolean2 are both TRUE. |
|
Whether boolean is not TRUE; returns UNKNOWN if boolean is UNKNOWN. |
|
Whether boolean is FALSE; returns FALSE if boolean is UNKNOWN. |
|
Whether boolean is not FALSE; returns TRUE if boolean is UNKNOWN. |
|
Whether boolean is TRUE; returns FALSE if boolean is UNKNOWN. |
|
Whether boolean is not TRUE; returns TRUE if boolean is UNKNOWN. |
|
Whether boolean is UNKNOWN. |
|
Whether boolean is not UNKNOWN. |
Arithmetic functions | Description |
---|---|
Returns numeric. |
|
Returns negative numeric. |
|
Returns numeric1 plus numeric2. |
|
Returns numeric1 minus numeric2. |
|
Returns numeric1 multiplied by numeric2. |
|
Returns numeric1 divided by numeric2. |
|
Returns numeric1 raised to the power of numeric2. |
|
Returns the absolute value of numeric. |
|
Returns the remainder (modulus) of numeric1 divided by numeric2. The result is negative only if numeric1 is negative. |
|
Returns the square root of numeric. |
|
Returns the natural logarithm (base e) of numeric. |
|
Returns the base 10 logarithm of numeric. |
|
Returns e raised to the power of numeric. |
|
Rounds numeric up, and returns the smallest number that is greater than or equal to numeric. |
|
Rounds numeric down, and returns the largest number that is less than or equal to numeric. |
String functions | Description |
---|---|
Concatenates two character strings. |
|
Returns the number of characters in a character string. |
|
As CHAR_LENGTH(string). |
|
Returns a character string converted to upper case. |
|
Returns a character string converted to lower case. |
|
Returns the position of the first occurrence of string1 in string2. |
|
Removes leading and/or trailing characters from string2. By default, whitespaces at both sides are removed. |
|
Replaces a substring of string1 with string2. |
|
Returns a substring of a character string starting at a given point. |
|
Returns a substring of a character string starting at a given point with a given length. |
|
Returns string with the first letter of each word converter to upper case and the rest to lower case. Words are sequences of alphanumeric characters separated by non-alphanumeric characters. |
Conditional functions | Description |
---|---|
Simple case. |
|
Searched case. |
|
Returns NULL if the values are the same. For example, |
|
Provides a value if the first value is null. For example, |
Type conversion functions | Description |
---|---|
Converts a value to a given type. |
Temporal functions | Description |
---|---|
Parses a date string in the form "yy-mm-dd" to a SQL date. |
|
Parses a time string in the form "hh:mm:ss" to a SQL time. |
|
Parses a timestamp string in the form "yy-mm-dd hh:mm:ss.fff" to a SQL timestamp. |
|
Parses an interval string in the form "dd hh:mm:ss.fff" for SQL intervals of milliseconds or "yyyy-mm" for SQL intervals of months. An interval range might be e.g. |
|
Returns the current SQL date in UTC time zone. |
|
Returns the current SQL time in UTC time zone. |
|
Returns the current SQL timestamp in UTC time zone. |
|
Returns the current SQL time in local time zone. |
|
Returns the current SQL timestamp in local time zone. |
|
Extracts parts of a time point or time interval. Returns the part as a long value. E.g. |
|
Rounds a time point down to the given unit. E.g. |
|
Rounds a time point up to the given unit. E.g. |
Aggregate functions | Description |
---|---|
Returns the number of input rows for which value is not null. |
|
Returns the number of input rows. |
|
Returns the average (arithmetic mean) of numeric across all input values. |
|
Returns the sum of numeric across all input values. |
|
Returns the maximum value of value across all input values. |
|
Returns the minimum value of value across all input values. |
Value access functions | Description |
---|---|
Accesses the field of a Flink composite type (such as Tuple, POJO, etc.) by name and returns it's value. |
|
Converts a Flink composite type (such as Tuple, POJO, etc.) and all of its direct subtypes into a flat representation where every subtype is a separate field. |
If a required scalar function is not contained in the built-in functions, it is possible to define custom, user-defined scalar functions for both the Table API and SQL. A user-defined scalar functions maps zero, one, or multiple scalar values to a new scalar value.
In order to define a scalar function one has to extend the base class ScalarFunction
in org.apache.flink.api.table.functions
and implement (one or more) evaluation methods. The behavior of a scalar function is determined by the evaluation method. An evaluation method must be declared publicly and named eval
. The parameter types and return type of the evaluation method also determine the parameter and return types of the scalar function. Evaluation methods can also be overloaded by implementing multiple methods named eval
.
The following example snippet shows how to define your own hash code function:
By default the result type of an evaluation method is determined by Flink’s type extraction facilities. This is sufficient for basic types or simple POJOs but might be wrong for more complex, custom, or composite types. In these cases TypeInformation
of the result type can be manually defined by overriding ScalarFunction#getResultType()
.
Internally, the Table API and SQL code generation works with primitive values as much as possible. If a user-defined scalar function should not introduce much overhead through object creation/casting during runtime, it is recommended to declare parameters and result types as primitive types instead of their boxed classes. Types.DATE
and Types.TIME
can also be represented as int
. Types.TIMESTAMP
can be represented as long
.
The following example shows an advanced example which takes the internal timestamp representation and also returns the internal timestamp representation as a long value. By overriding ScalarFunction#getResultType()
we define that the returned long value should be interpreted as a Types.TIMESTAMP
by the code generation.
The following operations are not supported yet:
A Table
can be written to a TableSink
, which is a generic interface to support a wide variety of file formats (e.g. CSV, Apache Parquet, Apache Avro), storage systems (e.g., JDBC, Apache HBase, Apache Cassandra, Elasticsearch), or messaging systems (e.g., Apache Kafka, RabbitMQ). A batch Table
can only be written to a BatchTableSink
, a streaming table requires a StreamTableSink
. A TableSink
can implement both interfaces at the same time.
Currently, Flink only provides a CsvTableSink
that writes a batch or streaming Table
to CSV-formatted files. A custom TableSink
can be defined by implementing the BatchTableSink
and/or StreamTableSink
interface.
The Table API provides a configuration (the so-called TableConfig
) to modify runtime behavior. It can be accessed through the TableEnvironment
.
By default, the Table API supports null
values. Null handling can be disabled to improve preformance by setting the nullCheck
property in the TableConfig
to false
.
The Table API provides a mechanism to describe the graph of operations that leads to the resulting output. This is done through the TableEnvironment#explain(table)
method. It returns a string describing two graphs: the Abstract Syntax Tree of the relational algebra query and Flink’s Execution Plan of the Job.
Table explain
is supported for both BatchTableEnvironment
and StreamTableEnvironment
. Currently StreamTableEnvironment
doesn’t support the explanation of the Execution Plan.
The following code shows an example and the corresponding output: