DUE TO SPAM, SIGN-UP IS DISABLED. Goto Selfserve wiki signup and request an account.
Status
Current state: ["Accepted"]
Discussion thread: https://lists.apache.org/thread/c36wmd5y3crqwvr10z6700tsxhw4x721
JIRA:
FLINK-40185
-
Getting issue details...
STATUS
Released: <Flink Version>
Please keep the discussion on the mailing list rather than commenting on the wiki (wiki discussions get unwieldy fast).
Motivation
PyFlink already provides the Table API as the primary relational API for Python users. The motivation for introducing a DataFrame API is therefore not that the Table API lacks fluent calls or Python-style method names. Instead, the gap is at the level of user workflow. The Table API is organized around Flink's Table/SQL programming model: users typically work with TableEnvironment, catalogs, table descriptors, schemas, SQL expressions, and connector options. This is the right abstraction for Flink's relational engine, but it is not the most natural starting point for many Python data engineering, data science, and ML-oriented workloads.
A Python DataFrame API provides a task-oriented entry point on top of the same Table API foundation. Users can start from familiar Python data sources such as records, dictionaries, pandas DataFrames, Arrow tables, Parquet files, or Kafka topics, then express transformations as DataFrame operations such as projection, filtering, derived columns, joins, aggregations, null handling, and Python UDF or batch function application. These operations still compile to the existing Table API and are planned and executed by Flink's optimizer and runtime. In this sense, the DataFrame API is a Python-facing layer that bridges the Python data ecosystem and Flink's streaming/distributed execution model, rather than a new execution model or a replacement for the Table API.
Goals
- Provide a Python DataFrame-style API for common PyFlink data processing workflows
- Lower the entry barrier for Python users who are familiar with DataFrame APIs but new to Flink's Table/SQL abstractions
- Preserve Flink semantics and execution capabilities, including streaming, batch, checkpointing, fault tolerance, connectors, and optimizer support
- Enable seamless interoperability with the existing Table API through explicit conversion between DataFrame and Table
- Improve ergonomics for Python UDF, vectorized batch processing, and ML/AI-style data enrichment workloads
Non-Goals
- Replace the Table API or SQL API — the DataFrame API is a complementary Python-facing layer
- Provide full compatibility with Pandas, Polars, Ray Data, or any existing DataFrame library — the API follows Flink semantics while borrowing widely adopted DataFrame ergonomics
- Introduce a new execution model, optimizer, connector abstraction, or runtime semantics — DataFrame operations delegate to the existing Table API and Flink runtime
Public Interfaces
This FLIP introduces a new Python module, pyflink.dataframe, as a public Python-facing API for constructing and transforming Flink-backed DataFrames:
import pyflink.dataframe as pf
The API is a complementary layer on top of the existing PyFlink Table API. It does not change the public interfaces of the Table API, SQL API, or DataStream API.
The public API surface introduced by this FLIP consists of the following categories. Detailed method signatures, parameters, and examples are described in the Proposed Changes section.
- DataFrame creation APIs: pf.from_records(), pf.from_dict(), pf.from_pandas(), pf.from_arrow(), pf.from_table(), and pf.range(). These functions create DataFrames backed by PyFlink Tables.
- Source and sink convenience APIs: pf.read_parquet(), pf.read_json(), pf.read_kafka(), pf.read_generic(), DataFrame.write_parquet(), DataFrame.write_json(), DataFrame.write_kafka(), and DataFrame.write_generic(). These APIs are Python-facing wrappers over existing Flink connector and format semantics.
- Core classes: DataFrame and GroupedDataFrame. DataFrame exposes relational transformations such as select, filter/where, with_column, join, group_by, agg, map, map_batches, drop_duplicates, top_n, windowing, null/NaN handling, conversion, and execution helpers.
- Expression, type, and UDF helpers: pf.col(), pf.lit(), pf.DataType, and pf.udf(). DataFrame expressions reuse the existing PyFlink Table expression system and map to Flink logical types and UDF mechanisms.
- Context and configuration APIs: pf.set_table_environment(), pf.get_table_environment(), and pf.config. These APIs expose, under pyflink.dataframe, the TableEnvironment-aligned context and configuration capabilities needed by DataFrame workflows: users can bind DataFrame operations to an existing TableEnvironment, retrieve the underlying environment for interop, and configure Flink/Table settings through a single entry point whether that environment is injected or lazily created.
The user-facing documentation for this API is planned to live under the Flink APIs section of Flink's developer overview documentation. For example, in the 2.3 docs site this corresponds to https://nightlies.apache.org/flink/flink-docs-release-2.3/docs/dev/overview/, where the DataFrame API would appear alongside the other core Flink APIs.
Proposed Changes
1. DataFrame Creation
Functions to construct DataFrames from various sources.
from_dict
def from_dict(
data: Mapping[str, Sequence[Any]],
schema: Optional[List[str]] = None
) -> DataFrame
Create a DataFrame from a column-oriented dictionary.
Example:
df = pf.from_dict({"name": ["Alice", "Bob"], "age": [30, 25]})
from_records
def from_records(
data: Sequence[Union[Sequence[Any], Mapping[str, Any]]],
schema: Optional[List[str]] = None
) -> DataFrame
Create a DataFrame from a row-oriented list of records (dicts or tuples).
Example:
df = pf.from_records([{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}])
df = pf.from_records([(1, "x"), (2, "y")], schema=["id", "label"])
from_pandas
def from_pandas(
pdf: pandas.DataFrame,
schema: Optional[List[str]] = None
) -> DataFrame
Create a DataFrame from a pandas DataFrame.
Example:
import pandas as pd
pdf = pd.DataFrame({"a": [1, 2, 3]})
df = pf.from_pandas(pdf)
from_arrow
def from_arrow(
table: pyarrow.Table,
schema: Optional[List[str]] = None
) -> DataFrame
Create a DataFrame from a PyArrow Table. PyArrow is the standard columnar interchange format in the Python data ecosystem, enabling efficient interop across libraries.
Example:
import pyarrow as pa
arrow_table = pa.table({"id": [1, 2, 3], "name": ["a", "b", "c"]})
df = pf.from_arrow(arrow_table)
from_table
def from_table(table: Table) -> DataFrame
Wrap an existing PyFlink Table as a DataFrame for interop.
Example:
table = t_env.from_path("my_table")
df = pf.from_table(table)
range
def range(
start_or_end: int,
end: Optional[int] = None,
step: int = 1
) -> DataFrame
Generate a DataFrame with a single column id of type INT64, containing a sequence of integers. Useful for testing, prototyping, and generating synthetic data.
range(n)— generates[0, 1, ..., n-1]range(start, end)— generates[start, start+1, ..., end-1]range(start, end, step)— generates[start, start+step, ...,]up to (but not including)end
Example:
df = pf.range(10) # id: [0, 1, 2, ..., 9]
df = pf.range(5, 10) # id: [5, 6, 7, 8, 9]
df = pf.range(0, 100, 10) # id: [0, 10, 20, ..., 90]
Declaring Event Time (watermark)
The in-memory and Python-native creation functions — from_dict, from_records, from_pandas, and from_arrow — accept an optional watermark parameter to declare an event-time attribute and watermark strategy on the created DataFrame, so that downstream event-time operations (event-time windows, interval joins, temporal joins) work without an extra source round-trip.
watermark: Optional[Tuple[str, str]] = None
- The parameter is a
(column, expression)tuple.columnis the name of the rowtime column;expressionis the watermark SQL expression, e.g. bounded out-of-orderness"ts - INTERVAL '5' SECOND". - The named
columnmust resolve toTIMESTAMP(3)orTIMESTAMP_LTZ(3). After the call, that column becomes the rowtime attribute of the DataFrame. - This mirrors the
watermark=(column, expression)form used by the source readers (read_kafka,read_parquet, ...), so event time is declared the same way regardless of where the data comes from. - When omitted, the created DataFrame carries no event-time attribute (event-time operators are unavailable until a watermark is declared at a source).
Example:
import datetime
import pyflink.dataframe as pf
df = pf.from_records(
[
(1, datetime.datetime(2024, 1, 1, 12, 0, 0)),
(2, datetime.datetime(2024, 1, 1, 12, 0, 5)),
],
schema=["id", "ts"],
watermark=("ts", "ts - INTERVAL '5' SECOND"),
)
# "ts" is now the event-time attribute; event-time windows can be applied downstream.
2. I/O — Sources and Sinks
The DataFrame API exposes source and sink helpers in pairs where possible. Each pair follows the same principle: expose typed and convenient Python parameters for commonly used connector and format options, map them to the corresponding Flink connector and format options. Flink supports a large and growing set of connectors and formats; the sections below document only a representative few as examples. Less common connectors or formats — and advanced options not yet surfaced as typed parameters — remain fully reachable through read_generic / write_generic, which take the raw connector identifier plus an arbitrary options dict, without waiting for a dedicated wrapper.
read_parquet / write_parquet
def read_parquet(
path: str,
*,
schema: Dict[str, DataType],
monitor_interval: Optional[str] = None,
path_regex_pattern: Optional[str] = None,
) -> DataFrame
def DataFrame.write_parquet(
self,
path: str,
*,
mode: str = "append",
compression: str = "SNAPPY",
rolling_policy_file_size: str = "128mb",
rolling_policy_rollover_interval: str = "30min",
rolling_policy_check_interval: Optional[str] = None,
partition_commit_trigger: str = "process-time",
partition_commit_delay: str = "0s",
partition_commit_policy_kind: Optional[str] = None,
) -> None
read_parquet() and write_parquet() use Flink's filesystem connector with the Parquet format. path, monitor_interval, and path_regex_pattern map to filesystem source options. The sink options correspond to Parquet compression, filesystem rolling policy options, and partition commit options.
Example:
df = pf.read_parquet(
"s3:///data/events/",
monitor_interval="60s",
schema={
"id": DataType.int64(),
"name": DataType.string(),
"event_time": DataType.timestamp_ltz(),
},
)
result = df.select("id", "name")
result.write_parquet("s3:///output/events/", compression="ZSTD")
read_json / write_json
def read_json(
path: str,
*,
schema: Dict[str, DataType],
monitor_interval: Optional[str] = None,
path_regex_pattern: Optional[str] = None,
format_options: Optional[Dict[str, str]] = None,
) -> DataFrame
def DataFrame.write_json(
self,
path: str,
*,
mode: str = "append",
rolling_policy_file_size: str = "128mb",
rolling_policy_rollover_interval: str = "30min",
rolling_policy_check_interval: Optional[str] = None,
partition_commit_trigger: str = "process-time",
partition_commit_delay: str = "0s",
partition_commit_policy_kind: Optional[str] = None,
format_options: Optional[Dict[str, str]] = None,
) -> None
read_json() and write_json() use Flink's filesystem connector with the JSON format. They follow the same filesystem options as read_parquet() and write_parquet(), while format-specific behavior is passed through format_options.
read_kafka / write_kafka
def read_kafka(
bootstrap_servers: str,
*,
topic: Optional[Union[str, List[str]]] = None,
topic_pattern: Optional[str] = None,
group_id: Optional[str] = None,
schema: Dict[str, DataType],
format: str = "json",
format_options: Optional[Dict[str, str]] = None,
key_format: Optional[str] = None,
key_format_options: Optional[Dict[str, str]] = None,
key_fields: Optional[List[str]] = None,
key_fields_prefix: Optional[str] = None,
value_format: Optional[str] = None,
value_format_options: Optional[Dict[str, str]] = None,
value_fields_include: Literal["ALL", "EXCEPT_KEY"] = "ALL",
startup_mode: Literal[
"earliest-offset", "latest-offset", "group-offsets",
"timestamp", "specific-offsets"
] = "group-offsets",
startup_specific_offsets: Optional[Union[str, Dict[int, int]]] = None,
startup_timestamp_millis: Optional[int] = None,
topic_partition_discovery_interval: str = "5 min",
bounded_mode: Literal[
"unbounded", "group-offsets", "latest-offset",
"timestamp", "specific-offsets"
] = "unbounded",
bounded_timestamp_millis: Optional[int] = None,
bounded_specific_offsets: Optional[Union[str, Dict[int, int]]] = None,
properties: Optional[Dict[str, str]] = None,
) -> DataFrame
def DataFrame.write_kafka(
self,
bootstrap_servers: str,
*,
topic: str,
format: str = "json",
format_options: Optional[Dict[str, str]] = None,
key_format: Optional[str] = None,
key_fields: Optional[List[str]] = None,
value_format: Optional[str] = None,
value_fields_include: Literal["ALL", "EXCEPT_KEY"] = "ALL",
delivery_guarantee: Literal["none", "at-least-once", "exactly-once"] = "at-least-once",
properties: Optional[Dict[str, str]] = None,
parallelism: Optional[int] = None,
) -> None
read_kafka() and write_kafka() use Flink's Kafka SQL connector. The parameters map to Kafka connector options, including topic, topic-pattern, properties.*, scan.startup.*, scan.bounded.*, key/value format options, delivery guarantee, and topic partition discovery. Kafka header metadata can still be modeled through the existing connector metadata mechanism when needed.
Example:
events = pf.read_kafka(
"localhost:9092",
topic="events",
format="json",
schema={"user_id": DataType.int64(), "event": DataType.string()},
startup_mode="earliest-offset",
)
events.write_kafka(
"localhost:9092",
topic="output-events",
format="json",
delivery_guarantee="at-least-once",
)
read_generic / write_generic
def read_generic(
connector: str,
*,
schema: Dict[str, DataType],
options: Dict[str, str]
) -> DataFrame
def DataFrame.write_generic(
self,
connector: str,
*,
options: Dict[str, str]
) -> None
These generic APIs are escape hatches for connectors that do not need a dedicated Python helper or for advanced connector options. Other connector-specific APIs will follow the same design: expose typed and convenient Python parameters for commonly used connector and format options, keep connector-specific options aligned with the corresponding Flink connector and format options, and provide read_generic() / write_generic() for less common connectors or advanced options.
Example:
orders = pf.read_generic(
"filesystem",
schema={
"order_id": DataType.string(),
"amount": DataType.float64(),
},
options={
"path": "s3:///warehouse/orders/",
"format": "json",
"json.ignore-parse-errors": "true"
}
)
orders.write_generic(
"filesystem",
options={
"path": "s3:///warehouse/filtered-orders/",
"sink.rolling-policy.file-size": "128mb",
"format": "json"
}
)
read_catalog_table / write_catalog_table
def read_catalog_table(path: str) -> DataFrame
def write_catalog_table(self, path: str, *, overwrite=False) -> None
Read a catalog table into a DataFrame, or write a DataFrame to a catalog table. path is table_name, db_name.table_name, or catalog_name.db_name.table_name; short paths resolve against the current catalog/database set via use_catalog / use_database. Create the catalog with create_catalog first.
Example:
pf.create_catalog("my_fluss", {
"type": "fluss",
"bootstrap.servers": "localhost:9123",
})
# Read by full path, or by short path after use_catalog / use_database
df = pf.read_catalog_table("my_fluss.my_database.my_table")
pf.use_catalog("my_fluss")
df = pf.read_catalog_table("my_database.my_table")
pf.use_database("my_database")
df = pf.read_catalog_table("my_table")
# Write a DataFrame to a catalog table
df.write_catalog_table("my_database.my_table")
df.write_catalog_table("my_table", overwrite=True)
Event Time and Computed Columns
All source readers — read_parquet, read_json, read_kafka, read_generic, and read_catalog_table — accept two optional parameters for declaring event time and derived columns:
computed_columns: Optional[Dict[str, str]] = None
watermark: Optional[Tuple[str, str]] = None
computed_columns={name: expression}appends virtual columns derived from existing columns. This is the standard way to turn a non-TIMESTAMP(3)time field (e.g. an epochBIGINTor a string) into a valid rowtime attribute, so thatwatermarkcan reference the derived column. Computed columns are evaluated in declaration order and may reference physical columns.watermark=(column, expression)declares the rowtime attribute and watermark strategy.columnis the rowtime column name andexpressionis the watermark SQL expression (e.g."ts - INTERVAL '5' SECOND"). The named column must resolve toTIMESTAMP(3)orTIMESTAMP_LTZ(3).
Example — Kafka source whose time field is an epoch in milliseconds:
events = pf.read_kafka(
"localhost:9092",
topic="events",
format="json",
schema={
"user_id": DataType.int64(),
"event": DataType.string(),
"ts_millis": DataType.int64(),
},
computed_columns={"event_time": "TO_TIMESTAMP_LTZ(ts_millis, 3)"},
watermark=("event_time", "event_time - INTERVAL '5' SECOND"),
)
# "event_time" is the event-time attribute; event-time windows can be applied downstream.
Example — declare event time on a catalog table (original table unchanged):
orders = pf.read_catalog_table(
"my_catalog.my_db.orders",
watermark=("order_time", "order_time - INTERVAL '5' SECOND"),
)
Writing to Multiple Sinks
By default each write_* call is eager: it compiles the DataFrame into its own Flink job and submits it immediately (waiting for completion in local execution). Calling several write_* methods therefore produces several independent jobs, each re-reading the source and re-computing the shared operators — in streaming this means the same source (e.g. a Kafka topic) is consumed once per sink.
To write to multiple sinks efficiently, collect the writes into a statement set and execute them together. They compile into a single job whose shared sources and operators are read/computed once and fanned out to all sinks.
def create_statement_set() -> StatementSet
# StatementSet
def execute(self) -> TableResult
def explain(self) -> str
Pass statement_set= to any write_* method to stage the write instead of executing it immediately, then call StatementSet.execute() once to submit the combined job.
Example:
import pyflink.dataframe as pf
from pyflink.dataframe import DataType
events = pf.read_kafka(
"localhost:9092", topic="events", format="json",
schema={"user_id": DataType.int64(), "event": DataType.string()},
)
enriched = events.filter(pf.col("user_id") > 0)
sset = pf.create_statement_set()
enriched.write_parquet("s3:///lake/events/", statement_set=sset) # staged, not executed
enriched.write_kafka("localhost:9092", topic="events-clean", statement_set=sset) # staged
sset.execute() # one job: the Kafka source is read once and fanned out to both sinks
Semantics and trade-offs:
- Shared sources and operators: the optimizer reuses duplicated sources and sub-plans (
table.optimizer.reuse-source-enabledandtable.optimizer.reuse-sub-plan-enabled, both enabled by default) when the sinks share the same upstream DataFrame lineage. - Unified checkpointing: all sinks live in one job and share one set of checkpoint barriers, giving consistent checkpointing across sinks — unlike independent per-sink jobs.
- Coupled backpressure and failover: because the sinks share one DAG, a slow sink backpressures the shared source and thus the other sinks, and a failure in any sink fails over the whole job. When sinks must be isolated, keep them as separate eager writes.
- Client actions are separate:
create_statement_setonly collects externalwrite_*sinks; client-side actions such ascollectandto_pandaspull data back to the driver and execute on their own.
3. DataFrame — Catalog Management
Catalogs let DataFrame jobs read from and write to externally managed metadata stores (Hive, Paimon, Fluss, etc.). Create a catalog once, then reference its tables through read_catalog_table / write_catalog_table in the I/O section.
create_catalog / get_catalog
def create_catalog(name: str, options: Dict[str, str]) -> None
def get_catalog(name: str) -> Optional[Catalog]
Create a catalog in the DataFrame default TableEnvironment. name is the catalog name; options is a dict of catalog options (keys and values are converted to strings). get_catalog returns the registered Catalog handle (or None if it does not exist).
Example:
import pyflink.dataframe as pf
pf.create_catalog("my_fluss", {
"type": "fluss",
"bootstrap.servers": "localhost:9123",
})
# Retrieve the underlying Catalog handle for advanced operations
catalog = pf.get_catalog("my_fluss")
Catalog & Database Navigation
def use_catalog(name: str) -> None
def get_current_catalog() -> Optional[str]
def list_catalogs() -> List[str]
def use_database(name: str) -> None
def get_current_database() -> Optional[str]
def list_databases() -> List[str]
Navigate catalogs and databases. Setting the current catalog and database lets you reference tables by short paths instead of the full catalog_name.db_name.table_name.
Example:
pf.use_catalog("my_fluss")
pf.get_current_catalog() # 'my_fluss'
pf.list_catalogs() # ['default_catalog', 'my_fluss']
pf.use_database("my_database")
pf.get_current_database() # 'my_database'
pf.list_databases() # ['default_database', 'my_database']
4. DataFrame — Column Operations
select
def select(self, *columns: Union[str, Expression, List[Union[str, Expression]]], **projections: Expression) -> DataFrame
Select (project) columns from the DataFrame. Supports multiple input formats:
- String column names
- Expression objects
- Lists of column names or expressions
- Keyword arguments for renaming/computed columns
Example:
df.select("a", "b") # By name
df.select(col("a"), col("b")) # By expression
df.select("a", doubled=col("a") * 2) # Mix: select + compute
df.select(["a", "b"]) # List of names
with_column
def with_column(
self,
name: str,
expr: Union[Expression, Callable[[DataFrame], Expression]]
) -> DataFrame
Add a new column or replace an existing column.
Example:
df.with_column("total", col("price") * col("quantity"))
df.with_column("total", lambda df: df["price"] * df["quantity"])
with_columns
def with_columns(self, *exprs: Expression, **named_exprs: Expression) -> DataFrame
Add multiple columns in one call.
Example:
df.with_columns(
total=col("price") * col("quantity"),
discounted=col("price") * 0.9,
)
drop_columns / drop
def drop_columns(self, *columns: Union[str, Expression], strict: bool = True) -> DataFrame
Remove columns from the DataFrame.
Parameters:
*columns— Column names or expressions to dropstrict— IfTrue, raise error on non-existent columns; ifFalse, silently ignore
Example:
df.drop_columns("temp_col", "debug_col")
df.drop("temp_col", strict=False) # alias, no error if missing
rename_columns / rename
def rename_columns(
self,
*args,
mapping: Union[Dict[str, str], Callable[[str], str]] = None
) -> DataFrame
Rename columns. Supports:
- Dictionary mapping:
{"old_name": "new_name"} - Callable: applied to each column name
- Positional pairs:
"old1", "new1", "old2", "new2"
Example:
df.rename({"user_id": "uid", "event_time": "ts"})
df.rename(str.upper) # ALL CAPS
df.rename("old_name", "new_name") # Positional pairs
5. DataFrame — Filtering & Ordering
filter / where
def filter(
self,
*predicate: Union[Expression, str, Callable[[DataFrame], Expression]],
**constraints
) -> DataFrame
Filter rows based on one or more conditions. Multiple predicates and keyword equality constraints are ANDed together. At least one predicate or constraint must be provided. Supports:
- Expression predicates
- SQL string predicates
- Callable predicates (lambda taking DataFrame)
- Keyword argument equality constraints (ANDed together and with the predicate)
Example:
df.filter(col("age") > 18)
df.filter("age > 18") # SQL string
df.filter(lambda df: df.age > 18) # Callable
df.filter(status="active") # Equality constraint
df.filter(col("age") > 18, city="NYC") # Combined
df.filter(col("age") > 18, col("score") >= 0.8) # Multiple conditions
df.filter(col("age") > 18, col("score") >= 0.8, city="NYC") # Multiple conditions and constraint
subscript filtering
df[col("age") > 18] # Same as df.filter(col("age") > 18)
sort
def sort(
self,
by: Union[str, Expression, List[Union[str, Expression]]],
*,
descending: Union[bool, List[bool]] = False,
nulls_first: Union[bool, List[bool]] = None,
) -> "DataFrame"
Sort rows by one or more columns.
by— a column name orExpression, or a list of them.descending— abool, or a list ofboolaligned withby. Defaults to ascending order.nulls_first— abool, or a list ofboolaligned withby. When omitted, Flink's default null ordering applies: NULL is treated as the smallest value, so nulls come first under ascending order and last under descending order.
Example:
# Ascending by a single column
df.sort("ts")
# Descending
df.sort("amount", descending=True)
# Multiple columns, with a per-column direction
df.sort(["category", "amount"], descending=[False, True])
# Control null placement per column
df.sort(["category", "amount"], descending=[False, True], nulls_first=[True, False])
top_n
def top_n(
self,
n: int,
*,
partition_by: Union[str, List[str]] = None,
order_by: Union[str, Expression, List[Union[str, Expression]]],
descending: Union[bool, List[bool]] = False,
nulls_first: Union[bool, List[bool]] = None,
) -> "DataFrame"
Keep only the top n rows by an ordering. When partition_by is given, Top-N is computed within each group; when it is omitted, a single global Top-N over the whole input is computed. By design, top_n only filters which rows are kept: it returns the selected input rows and does not append a rank/rownum column to the output schema. This mirrors top_k/nlargest in other DataFrame libraries while adding first-class per-group support, which is a common streaming pattern.
n— the number of rows to keep (per group whenpartition_byis set, otherwise overall).partition_by— optional column name or list of column names defining the groups. When omitted, a single global Top-N is computed.order_by— a column name or Expression (or a list of them) used to rank rows.descending— a bool, or a list of bool aligned withorder_by. Defaults to ascending order.nulls_first— abool, or a list ofboolaligned withorder_by. When omitted, Flink's default null ordering applies: nulls come first under ascending order and last under descending.
Example:
# Global: the 10 highest-value orders overall
df.top_n(10, order_by="amount", descending=True)
# Grouped: top 3 products by sales within each category
df.top_n(3, partition_by="category", order_by="sales", descending=True)
# Latest record per device (deduplicate by keeping the newest row)
df.top_n(1, partition_by="device_id", order_by="event_time", descending=True)
# Rank descending but place NULLs first instead of the default last
df.top_n(10, order_by="amount", descending=True, nulls_first=True)
drop_duplicates / distinct / unique
def drop_duplicates(
self,
subset: Union[str, List[str]] = None,
*,
keep: str = "first",
order_by: Union[str, Expression, List[Union[str, Expression]]] = None,
nulls_first: Union[bool, List[bool]] = None,
) -> "DataFrame"
Remove duplicate rows. When subset is omitted, fully identical rows are dropped; when subset is given, rows are deduplicated by those key columns, keeping one row per key. distinct and unique are provided as aliases of this method, matching the common naming convention used by other DataFrame libraries.
subset— a column name or list of column names that define a duplicate. When omitted (default), all columns are considered (whole-row distinct).keep—"first"keeps the earliest row,"last"keeps the latest row within each duplicate group.order_by— a column name or Expression (or a list of them) that defines the order in whichkeepselects the surviving row. When omitted, processing time is used, sokeep="first"/"last"keep the first/last row to arrive. Ignored whensubsetis omitted.nulls_first— abool, or a list ofboolaligned withorder_by, controlling where NULLs rank whenkeepselects the surviving row. When omitted, Flink's default null ordering applies. Ignored whenorder_byis omitted.
Example:
# Whole-row deduplication: drop fully identical rows
df.drop_duplicates()
# Keep the earliest row per device by arrival (defaults to processing time)
df.drop_duplicates(subset="device_id")
# Keep the earliest event per order, ordered by event time
df.drop_duplicates(subset=["order_id"], order_by="event_time")
# Keep the latest record per user, ordered by event time
df.drop_duplicates(subset="user_id", order_by="event_time", keep="last")
limit / offset / head
def limit(self, n: int) -> "DataFrame"
def offset(self, n: int) -> "DataFrame"
def head(self, n: int) -> "DataFrame"
Restrict the DataFrame to a contiguous slice of rows. All three are lazy transformations returning a new DataFrame.
limit(n)— keep at most the firstnrows (n >= 0).offset(n)— skip the firstnrows (n >= 0).head(n)— alias forlimit(n).
Combine offset and limit for paging. The "first n" rows are only well-defined relative to an order, so apply sort first when you need a deterministic slice. In streaming mode the result updates as new rows arrive (a retracting stream).
Example:
df.limit(10) # first 10 rows
df.head(10) # same as limit(10)
df.offset(5).limit(10) # rows 6..15 (paging)
# Deterministic top slice: order first
df.sort("ts", descending=True).limit(100)
6. DataFrame — Aggregation
group_by
def group_by(self, *columns: Union[str, Expression]) -> GroupedDataFrame
Group the DataFrame by one or more columns. The grouping keys are automatically emitted as the leading columns of subsequent agg() results.
Example:
df.group_by("department").agg(avg_salary=df.salary.avg())
agg (on DataFrame — global aggregation)
def agg(self, *aggs: Expression, **named_aggs: Expression) -> DataFrame
Perform global aggregation without grouping. Aggregate expressions may be passed positionally (and named with .alias(...)) or as keyword arguments whose names become output column names.
Example:
df.agg(total=df.id.count())
GroupedDataFrame.agg
class GroupedDataFrame:
def agg(self, *aggs: Expression, **named_aggs: Expression) -> DataFrame
Apply aggregate functions to each group. The group keys are automatically emitted as the leading columns of the result, followed by the aggregation outputs, so you do not repeat the keys inside agg(). Aggregates may be passed positionally (and named with .alias(...)) or as keyword arguments whose names become output column names.
Example:
df.group_by("dept").agg(
avg_salary=df.salary.avg(),
headcount=df.id.count(),
)
Aggregation expressions are created by calling aggregate methods on column expressions, such as df.salary.avg(), pf.col("id").count(), col(...).sum(), col(...).min(), and col(...).max(). For named aggregates, the keyword becomes the output name, so .alias(...) is optional.
Custom aggregation: agg also accepts user-defined aggregate functions created with @udaf (see §18). They are called exactly like built-in aggregates, e.g. df.group_by("dept").agg(wavg=weighted_avg(df.salary, df.weight)).
7. DataFrame — Joins
join
def join(
self,
other: DataFrame,
*,
on: Union[str, Expression, List[str]] = None,
how: str = "inner",
left_on: Union[str, Expression, List[str]] = None,
right_on: Union[str, Expression, List[str]] = None,
) -> DataFrame
Join two DataFrames.
Parameters:
other— The right DataFrame to join withon— Join key(s) when both sides share the same column name(s)how— Join type:"inner","left","right","full"/"outer","semi","anti","cross"."semi"and"anti"keep only the left columns —"semi"emits each left row that has a match,"anti"each left row that has none;"cross"is a Cartesian product and takes noon.left_on/right_on— Join keys when column names differ between sides
Example:
# Equi-join on shared column
orders.join(customers, on="customer_id", how="inner")
# Join on different column names
orders.join(products, left_on="product_id", right_on="id", how="left")
# Multi-column join
df1.join(df2, on=["key1", "key2"])
# Non-equi join: pass a boolean Expression as the full join predicate
# (here an equi key combined with a range condition)
orders.join(
discounts,
on=(pf.col("category") == pf.col("d_category")) &
(pf.col("amount") >= pf.col("min_amount")) &
(pf.col("amount") < pf.col("max_amount")),
how="left",
)
# Semi-join: keep orders that have at least one matching payment
orders.join(payments, on="order_id", how="semi")
# Anti-join: keep orders that have no matching payment
orders.join(payments, on="order_id", how="anti")
# Cross join: Cartesian product, no join key
colors.join(sizes, how="cross")
join_asof
def join_asof(
self,
other: "DataFrame",
*,
how: str = "inner",
on: Union[str, Expression] = None,
by: Union[str, Expression, List[Union[str, Expression]]] = None,
left_by: Union[str, Expression, List[Union[str, Expression]]] = None,
right_by: Union[str, Expression, List[Union[str, Expression]]] = None,
) -> "DataFrame"
Perform an ASOF join with a dimension table at a time attribute. For each left row, the matching dimension row is selected by key as of the row's time attribute.
other— the right DataFrame (the dimension table).how—"inner"or"left".on— the ASOF time attribute. Provide it aspf.proctime()(or a proctime column on the left DataFrame) for a processing-time lookup, or as a rowtime (event-time / watermark) column for an event-time temporal join. The time-attribute column must not also be used as a join key.by— join key(s) shared by both sides. Accepts the same shapes asjoin: a column name, anExpression, or a list thereof. The resulting condition must contain at least one equi-predicate (AND-combined); additional non-equality conditions may be added, but a purely non-equi orOR-based condition is rejected.left_by/right_by— join keys when the key columns have different names on each side; supply both together instead ofby.
Example:
# Lookup join on an equality key with explicit processing time
enriched = probe_df.join_asof(
dim_df,
on=pf.proctime(),
by=pf.col("id") == pf.col("d_id"),
)
# Explicit processing-time attribute, left outer join
enriched = probe_df.join_asof(
dim_df,
on=pf.proctime(),
by=pf.col("id") == pf.col("d_id"),
how="left",
)
# Event-time temporal join: match the dimension version as of the
# left row's rowtime (watermark) attribute
enriched = probe_df.join_asof(
dim_df,
on=pf.col("event_time"),
by=pf.col("id") == pf.col("d_id"),
)
# Time attribute given as a proctime column, with differing key names
enriched = probe_df.join_asof(
dim_df,
on=pf.col("proc_time"),
left_by="id",
right_by="d_id",
)
join_lateral
def join_lateral(
self,
table_function_call: Union[DataFrameUDTFCall, Expression],
*,
on: Expression = None,
ignore_empty: bool = True,
) -> "DataFrame"
Join each input row with the rows a table function (UDTF) emits for it — a lateral (correlated) join. Where explode unnests a built-in collection column and flat_map applies a whole-row UDTF, join_lateral joins against a UDTF invoked with explicit column arguments, keeping the original columns alongside the UDTF output.
table_function_call— a UDTF call built by invoking a@udtffunction with column expressions, e.g.chars(pf.col("text")). Name the output field(s) with.alias(...); names may instead be inferred from a namedTypedDict/ structreturn_dtype. A raw Expression must name its outputs with.alias.on— optional boolean join predicate, matching the Table API lateral-join predicate.ignore_empty—True(default) is inner lateral-join semantics: input rows whose UDTF emits no rows are dropped.Falseis left-outer lateral-join semantics: such rows are kept with NULL UDTF output.
Example:
from typing import Iterator, TypedDict
import pyflink.dataframe as pf
@udtf
def chars(text: str) -> Iterator[str]:
for ch in text:
yield ch
# Inner lateral join: rows with empty text are dropped
df.join_lateral(chars(pf.col("text")).alias("ch"))
# Left-outer lateral join: rows with empty text are kept with NULL ch
df.join_lateral(chars(pf.col("text")).alias("ch"), ignore_empty=False)
# With an extra join predicate
df.join_lateral(chars(pf.col("text")).alias("ch"), on=pf.col("id") > 0)
# Multi-field output via a TypedDict return type (names inferred)
class Token(TypedDict):
word: str
length: int
@udtf
def tokenize(text: str) -> Iterator[Token]:
for word in text.split():
yield {"word": word, "length": len(word)}
df.join_lateral(tokenize(pf.col("text")))
8. DataFrame — Windowing
Window operations split a stream into finite buckets over a time attribute — a rowtime or proctime column assumed to already exist on the DataFrame. tumble/hop/cumulate/session does one thing: it assigns each row to a window and appends three columns, window_start, window_end, and window_time, returning an ordinary DataFrame. Everything downstream — aggregation, Top-N, deduplication, join — is then expressed with the regular operators already introduced; the "window" flavor of each simply carries window_start/window_end in its grouping or join keys. This mirrors how Flink recognizes Window aggregation / Window Top-N / Window Join from the windowing-TVF columns, and keeps the API surface minimal.
window
def tumble(
self,
*,
on: Union[str, Expression],
size: Union[str, Expression]
) -> "DataFrame"
# fixed-size, non-overlapping windows
Example:
df.tumble(on=col("rowtime"), size=lit(10).minutes)
def hop(
self,
*,
on: Union[str, Expression],
size: Union[str, Expression],
slide: Union[str, Expression]
) -> "DataFrame"
# sliding (hopping) windows
Example:
df.hop(on=col("rowtime"), size=lit(10).minutes, slide=lit(2).minutes)
def cumulate(
self,
*,
on: Union[str, Expression],
size: Union[str, Expression],
step: Union[str, Expression],
) -> "DataFrame"
# cumulating windows that grow by `step` up to `size`
Example:
df.cumulate(on=col("rowtime"), size=lit(10).minutes, step=lit(2).minutes)
def session(self, *, on: Union[str, Expression], gap: Union[str, Expression], partition_by: Optional[Union[str, Expression, List[Union[str, Expression]]]] = None) -> "DataFrame"
# activity-based windows closed after `gap` of inactivityExample:
df.session(on=col("rowtime"), gap=lit(10).minutes, partition_by="id")
Assign rows to windows and append window_start, window_end, window_time. Returns an ordinary DataFrame, so all subsequent steps use the regular operators.
windowed = df.tumble(on=col("ts"), size=lit(10).minutes)
# `windowed` has every original column plus window_start / window_end / window_time
Window aggregation
Group by window_start, window_end (plus any business keys) and aggregate with the regular group_by().agg():
df.tumble(on=col("ts"), size=lit(10).minutes) \
.group_by("window_start", "window_end", "user_id") \
.agg(col("amount").sum().alias("total"))
Window Top-N
Reuse top_n with window_start, window_end leading partition_by. Each window emits its Top-N once it fires, so the result is insert-only:
# Top 3 orders by amount within each 10-minute window, per region
(df.tumble(on=col("ts"), size=lit(10).minutes))
.top_n(
3,
partition_by=["window_start", "window_end", "region"],
order_by="amount",
descending=True,
))
Window Deduplication
Reuse drop_duplicates with window_start, window_end in subset; keep + order_by pick the first/last row per window per key (also insert-only):
# Keep the first event per user within each 10-minute window
df.tumble(on=col("ts"), size=lit(10).minutes) \
.drop_duplicates(
subset=["window_start", "window_end", "user_id"],
order_by="ts",
keep="first",
)
Window Join
Window both inputs with identical specs, then join on window_start, window_end plus the business key. The matching window columns make it a Window Join rather than a regular join:
lw = left.tumble(on=col("ts"), size=lit(10).minutes)
rw = right.tumble(on=col("ts"), size=lit(10).minutes)
result = lw.join(
rw,
on=["window_start", "window_end", "k"],
how="inner",
)
Over aggregation (OVER windows)
Unlike the windowing TVF above, an OVER window does not bucket rows — it keeps every row and, for each one, aggregates over a sliding frame relative to that row. Use it for running totals and "last N" / "last interval" rolling metrics.
It supports the following method on aggregate expression:
def over(
self,
order_by: Union[str, Expression],
*,
partition_by: Optional[Union[str, Expression, Sequence[Union[str, Expression]]]] = None,
rows=None,
range=None,
) -> Expression
Each of rows / range accepts a scalar shorthand or a two-sided (start, end) tuple:
- Scalar — "from that far back up to the current row" (the common streaming case):
rows=10— the 10 preceding rows through the current row.range="1 hour"— all rows within the last hour (a duration string ortimedelta).rows=pf.UNBOUNDED/range=pf.UNBOUNDED— cumulative from the partition start.
- Two-sided tuple — explicit bounds built from
pf.preceding(x),pf.following(x),pf.CURRENT_ROW,pf.UNBOUNDED_PRECEDING,pf.UNBOUNDED_FOLLOWING. Forrows,xis a row count; forrange,xis a duration string /timedelta.rows=(pf.preceding(2), pf.CURRENT_ROW)— 2 preceding through the current row.rows=(pf.preceding(2), pf.following(1))— 2 preceding through 1 following (batch only, see below).
Streaming constraint: Flink's streaming OVER only supports frames that end at the current row, so in streaming mode the upper bound must be pf.CURRENT_ROW; FOLLOWING bounds are batch-only. The order_by must be a single time attribute in ascending order.
Example:
df.select(
col("*"),
# Running total per product from the start of the stream
col("amount").sum().over(
partition_by="product", order_by="ts", rows=pf.UNBOUNDED
).alias("running_total"),
# Average amount over the last hour per product
col("amount").avg().over(
partition_by="product", order_by="ts", range="1 hour"
).alias("avg_1h"),
# Average of the 10 most recent rows per product
col("amount").avg().over(
partition_by="product", order_by="ts", rows=10
).alias("avg_last_10"),
)
For a single derived column, with_column reads more cleanly:
df.with_column(
"running_total",
col("amount").sum().over(
partition_by="product", order_by="ts", rows=pf.UNBOUNDED
),
)
9. DataFrame — Set Operations
def union(self, other: "DataFrame") -> "DataFrame" # distinct rows from both (batch only)
def union_all(self, other: "DataFrame") -> "DataFrame" # all rows from both, keeps duplicates
def intersect(self, other: "DataFrame") -> "DataFrame" # distinct rows in both (batch only)
def intersect_all(self, other: "DataFrame") -> "DataFrame" # rows in both, keeps duplicates (batch only)
def minus(self, other: "DataFrame") -> "DataFrame" # distinct rows only in the left (batch only)
def minus_all(self, other: "DataFrame") -> "DataFrame" # rows only in the left, EXCEPT ALL (batch only)
Combine two DataFrames by set semantics. Schema compatibility is checked by column position (not by name); each column pair must be castable to a common type, and the result uses this DataFrame's column names and the common types.
Example:
a = pf.from_records([(1,), (2,), (2,)], schema=["x"])
b = pf.from_records([(2,), (3,)], schema=["x"])
a.union(b) # 1, 2, 3
a.union_all(b) # 1, 2, 2, 2, 3
a.intersect(b) # 2
a.minus(b) # 1
Only union_all is supported in streaming mode; the other set operations require batch mode, since they must deduplicate or match against the complete input.
10. DataFrame — Row Transformations (Map Operations)
map
def map(
self,
func: Union[Callable[[Dict[str, Any]], Dict[str, Any]], DataFrameUDFWrapper],
*,
return_dtype: DataType = None,
concurrency: int = None,
) -> DataFrame
Apply a function to each row. The function receives a dict (column→value) and returns a dict.
Parameters:
func— A callableDict[str, Any] -> Dict[str, Any], or a UDFreturn_dtype— Output schema specificationconcurrency— Degree of concurrency for async / I/O-bound UDFs
Example:
def transform(row):
return {"name": row["name"].upper(), "age_group": "adult" if row["age"] >= 18 else "minor"}
result = df.map(transform, return_dtype=DataType.struct({"name": DataType.string(), "age_group": DataType.string()}))
Class-based example:
class NormalizeUser:
def __init__(self, prefix: str):
self._prefix = prefix
def __call__(self, row):
return {
"user_key": f"{self._prefix}{row['user_id']}",
"age_group": "adult" if row["age"] >= 18 else "minor",
}
result = df.map(
NormalizeUser("user-"),
return_dtype=DataType.struct({
"user_key": DataType.string(),
"age_group": DataType.string(),
}),
)
map_batches
def map_batches(
self,
func: Union[
Callable[[Dict[str, pandas.Series]], Dict[str, pandas.Series]],
Callable[[Dict[str, pyarrow.Array]], Dict[str, pyarrow.Array]],
DataFrameUDFWrapper,
],
*,
return_dtype: DataType = None,
batch_format: Literal["pandas", "arrow"],
concurrency: int = None,
batch_size: int = None,
) -> DataFrame
Apply a function to batches of rows. In pandas mode, the function receives and returns dict[str, pandas.Series]. In Arrow mode, the function receives and returns dict[str, pyarrow.Array]. This is useful for vectorized operations, ML inference, Arrow-native processing, or batch API calls.
Parameters:
func— A callabledict[str, pandas.Series] -> dict[str, pandas.Series]in pandas mode, ordict[str, pyarrow.Array] -> dict[str, pyarrow.Array]in Arrow modereturn_dtype— Output schema specification. Required for Arrow mode.batch_format— Batch transport format, either"pandas"or"arrow"batch_size— Number of rows per batchconcurrency— Degree of concurrency for this transform, especially for async or I/O-bound work
Example:
# pandas mode
from typing import Dict
import pandas as pd
def batch_predict(batch: Dict[str, pd.Series]) -> Dict[str, pd.Series]:
batch["prediction"] = model.predict(batch["features"])
return batch
result = df.map_batches(batch_predict, batch_format="pandas", batch_size=1024)
# Arrow mode
import pyarrow as pa
# Column "image" is DataType.tensor(DataType.float32(), (3, 224, 224)).
def classify_images(batch: Dict[str, pa.Array]) -> Dict[str, pa.Array]:
images = batch["image"].to_numpy()
probs = model.predict(images)
return {"label": pa.array(probs.argmax(axis=1))}
result = df.map_batches(
classify_images,
batch_format="arrow",
return_dtype=DataType.struct({"label": DataType.int64()}),
batch_size=256,
)
Class-based example:
from typing import Dict
import pandas as pd
class BatchScorer:
def __init__(self, model):
self._model = model
def __call__(self, batch: Dict[str, pd.Series]) -> Dict[str, pd.Series]:
return {
"prediction": pd.Series(self._model.predict(batch["features"]))
}
result = df.map_batches(
BatchScorer(model),
batch_format="pandas",
return_dtype=DataType.struct({"prediction": DataType.float64()}),
batch_size=1024,
)
explode
def explode(
self,
column: Union[str, Expression, List[Union[str, Expression]]],
*,
output_column: Union[str, List[str]] = None,
ignore_empty_and_null: bool = False,
) -> "DataFrame"
Expand one ARRAY, MAP, or MULTISET column into multiple rows — a 1-to-N row transformation. The exploded input column is removed from the result. ARRAY values produce one row per element, MULTISET values one row per element occurrence, and MAP values one row per entry. The number of output fields depends on the element type: a scalar element yields a single field, a MAP yields key and value fields, and a ROW element (e.g. ARRAY<ROW<...>>) yields one field per ROW field. Pass output_column as a single name for single-field output, or as a list of names for multi-field output. output_column may be omitted only when the output has a single field, in which case the result reuses the exploded column name. By default, rows whose input is empty or NULL are preserved with NULL output; set ignore_empty_and_null=True to drop them.
Example:
df = pf.from_dict({"id": [1, 2], "tags": [["a", "b"], [ ]]})
# Explode an ARRAY column (output reuses the name "tags")
df.explode("tags")
# (1, "a"), (1, "b"), (2, NULL)
# Rename the single output field
df.explode("tags", "tag")
# Explode a MAP column into key/value fields
attrs = pf.from_dict({"id": [1], "props": [{"color": "red", "size": "M"}]})
attrs.explode("props", ["prop_key", "prop_value"])
# (1, "color", "red"), (1, "size", "M")
# Explode ARRAY<ROW<name STRING, qty INT>> into one field per ROW field.
# Multi-field output requires a list of output names.
events.explode("items", ["name", "qty"])
# (1, "a", 2), (1, "b", 3)
# Drop rows whose collection is empty or NULL
df.explode("tags", "tag", ignore_empty_and_null=True)
# Expand multiple ARRAYs together, matching their elements by position::
df = pf.from_dict({"items": [["apple", "pear"]], "counts": [[2, 3]]})
df.explode(["items", "counts"])
flat_map
def flat_map(
self,
func: Union[Callable[[Dict[str, Any]], Any], DataFrameUDTFWrapper],
*,
return_dtype: DataType = None,
concurrency: int = None,
) -> "DataFrame"
Apply a row-based UDTF to each row, producing zero, one, or many output rows. Where explode covers the built-in case of unnesting a collection column, flat_map covers arbitrary custom row expansion. func is either a plain Python callable that receives the whole row as a dict keyed by column name, or a @udtf-decorated DataFrameUDTFWrapper whose function takes the row. Output column names come from a named TypedDict / struct return type, or from return_dtype; when func is a DataFrameUDTFWrapper, return_dtype must not be set because the wrapper already carries its return type.
Example:
from typing import Any, Dict, Iterator, TypedDict
import pyflink.dataframe as pf
from pyflink.dataframe import DataType
# Type-hint inference: output field names/types come from the TypedDict.
class Token(TypedDict):
token: str
length: int
def split(row: Dict[str, Any]) -> Iterator[Token]:
for tok in row["line"].split():
yield {"token": tok, "length": len(tok)}
df = pf.from_dict({"line": ["hello world", "flink"]})
df.flat_map(split)
# ("hello", 5), ("world", 5), ("flink", 5)
# Or declare the output schema explicitly with return_dtype.
def split_untyped(row: Dict[str, Any]):
for tok in row["line"].split():
yield {"token": tok, "length": len(tok)}
df.flat_map(
split_untyped,
return_dtype=DataType.struct({"token": DataType.string(), "length": DataType.int32()}),
)
11. DataFrame — Null/NaN Handling
drop_null
def drop_null(self, subset: Optional[List[str]]) -> DataFrame
Remove rows containing NULL values.
Parameters:
subset— Column names to check. If None, checks all columns.
Example:
df.drop_null() # Drop rows with any NULL
df.drop_null(subset=["age"]) # Drop rows where "age" is NULL
drop_nan
def drop_nan(self, subset: Optional[List[str]]) -> DataFrame
Remove rows containing NaN values (for float/double columns).
fill_null
def fill_null(self, value: Any, subset: Optional[List[str]]) -> DataFrame
Replace NULL values with a specified value.
Example:
df.fill_null(0, subset=["quantity"])
df.fill_null("unknown", subset=["name"])
fill_nan
def fill_nan(self, value: Any, subset: Optional[List[str]]) -> DataFrame
Replace NaN values with a specified value (for float/double columns).
12. DataFrame — Composition
pipe
def pipe(self, func: Callable[..., T], *args: Any, **kwargs: Any) -> T
Apply an arbitrary function to the DataFrame. Enables functional composition and reusable transformation pipelines.
Example:
def add_features(df, prefix="feat"):
return df.with_columns(
**{f"{prefix}_sum": col("a") + col("b")},
**{f"{prefix}_diff": col("a") - col("b")},
)
result = df.pipe(add_features, prefix="my")
13. DataFrame — Conversion & Execution
to_table
def to_table(self) -> Table
Get the underlying PyFlink Table for advanced operations or interop with the Table API.
to_pandas
def to_pandas(self) -> pandas.DataFrame
Collect all results and convert to a pandas DataFrame. Triggers job execution.
collect
def collect(self) -> List
Collect all results as a list of Row objects. Triggers job execution.
iter_rows
def iter_rows(
*,
include_row_kind: bool = False,
row_kind_field: str = "__row_kind__",
) -> CloseableIterator[Dict[str, Any]]
Return a closable iterator over rows of the DataFrame. Triggers job execution.iter_batches
def iter_batches(
*,
batch_size: int = 1000,
batch_format: Literal["pandas", "pyarrow"] = "pandas",
include_row_kind: bool = False,
row_kind_field: str = "__row_kind__",
) -> CloseableIterator[pandas.DataFrame | pyarrow.Table]
Return a closable iterator of pandas DataFrames or arrow table, each containing up to batch_size rows.take
def take(
n: int,
*,
timeout: int | None = None,
include_row_kind: bool = False,
row_kind_field: str = "__row_kind__",
) -> List[Dict[str, Any]]
Return up to ``n`` rows within the specified timeout in seconds.
take_batch
def take_batch(
self,
n: int,
*,
timeout: int | None = None,
batch_format: Literal["pandas", "pyarrow"] = "pandas",
include_row_kind: bool = False,
row_kind_field: str = "__row_kind__",
) -> pandas.DataFrame | pyarrow.Table
Return up to ``n`` rows in a batch within the specified timeout in seconds.describe
def describe(self, *columns: str) -> DataFrame
Compute descriptive statistics for the selected columns, or for all columns when none are specified. Returns a small DataFrame of summary rows such as count, null_count, mean, min and max (the supported statistics may change over time) where applicable. This is intended primarily for bounded / batch exploration and so only works for bounded streams.
Example:
df.describe()
df.describe("price", "quantity")
show
def show(
self,
n: int = 10,
*,
format: Literal["tableau", "changelog", "table"] = "tableau",
max_width: int = 30
) -> None
Pretty-print up to n rows for local inspection. Triggers job execution. format="tableau" prints rows directly in a fixed-width table, format="changelog" prints change events with row kinds (for continuous / updating results), and format="table" materializes up to n rows and prints a stable snapshot-style table. max_width truncates variable-length values for readability.
Example:
df.show()
df.show(20, format="table")
df.sort("ts", descending=True).show(10, format="changelog", timeout=5.0)
__repr__ / _repr_html_ / _repr_mimebundle_
def __repr__(self) -> str
def _repr_html_(self) -> str
def _repr_mimebundle_(self, include=None, exclude=None) -> Dict[str, str]These rich-display hooks let a DataFrame render itself in REPLs and notebooks, triggering bounded execution (a limited number of rows, like show()) so users get inline previews without calling show() explicitly. __repr__ returns a plain-text preview (used by print() and bare expressions); _repr_html_ returns an HTML table that Jupyter renders; _repr_mimebundle_ returns a dict of MIME representations (text/plain plus text/html) so notebook front-ends can choose the best one. This is also why there is no separate display() method: display() is an IPython/Jupyter builtin, and these hooks are the idiomatic way a DataFrame library integrates with it.
explain
def explain(
self, *,
show_estimated_cost: bool = False,
show_physical_execution_plan: bool = False
) -> None
Print the logical/physical execution plan.
14. DataFrame — Properties
schema
@property
def schema(self) -> TableSchema
Returns the schema of the DataFrame.
columns
@property
def columns(self) -> List[str]
Returns the list of column names.
15. DataFrame — Column Access
df["col_name"] # Returns Expression (column reference)
df.col_name # Same, when the name is a valid identifier and does not conflict
df[["a", "b", "c"]] # Returns DataFrame (select columns)
df[expr] # Returns DataFrame (filter by boolean expression)
Attribute access is a shorthand for column references when the column name is a valid Python identifier and does not conflict with an existing DataFrame property or method; use df["..."] or pf.col(...) otherwise.
16. Expression Helpers
col
def col(name: str) -> Expression
Create a column reference expression. This remains the fully explicit form, especially when a column name is not a valid identifier or would collide with an existing DataFrame attribute.
Example:
pf.col("age") > 18
pf.col("price") * pf.col("quantity")
lit
def lit(value: Any, data_type: DataType = None) -> Expression
Create a literal value expression.
Example:
pf.lit(42)
pf.lit("hello")
pf.lit(3.14, DataType.float64())
The expression system supports standard arithmetic (+, -, *, /, %), comparison (>, >=, <, <=, ==, !=), logical (&, |, ~), and method-based operations (.alias(), .cast(), .is_null, .is_not_null, etc.) inherited from the Table API expression system.
17. Type System — DataType
The DataType class provides a Pythonic type definition system, mapping to Flink's type system.
class DataType:
# Numeric types
@classmethod def int8(cls) -> DataType # TINYINT
@classmethod def int16(cls) -> DataType # SMALLINT
@classmethod def int32(cls) -> DataType # INT
@classmethod def int64(cls) -> DataType # BIGINT
@classmethod def float32(cls) -> DataType # FLOAT
@classmethod def float64(cls) -> DataType # DOUBLE
@classmethod def decimal(cls, precision: int, scale: int) -> DataType
# String/Binary types
@classmethod def string(cls) -> DataType # VARCHAR
@classmethod def fixed_size_string(cls, length: int) -> DataType # CHAR(n)
@classmethod def binary(cls) -> DataType # BYTES
@classmethod def fixed_size_binary(cls, length: int) -> DataType # BINARY(n)
# Boolean & Null
@classmethod def bool(cls) -> DataType # BOOLEAN
@classmethod def null(cls) -> DataType # NULL
# Temporal types
@classmethod def date(cls) -> DataType
@classmethod def time(cls, precision: int = 0) -> DataType
@classmethod def timestamp(cls, precision: int = 6) -> DataType
@classmethod def timestamp_ltz(cls, precision: int = 6) -> DataType
# Complex types
@classmethod def list(cls, dtype: DataType) -> DataType
@classmethod def map(cls, key_type: DataType, value_type: DataType) -> DataType
@classmethod def struct(cls, fields: Union[Dict[str, DataType], List[tuple]]) -> DataType
# Modifiers
def not_null(self) -> DataType
def nullable(self) -> DataType
Example:
DataType.int64()
DataType.string().not_null()
DataType.list(DataType.float64())
DataType.struct({"name": DataType.string(), "age": DataType.int32()})
DataType.decimal(10, 2)
Note: This FLIP defines the standard scalar and composite types listed above. Multimodal data types such as DataType.tensor and DataType.image are out of scope here and will be introduced in a follow-up once the dedicated multimodal data types FLIP is accepted (if the multimodal data types FLIP is accepted before this one, we can also update this FLIP to reflect it).
18. User-Defined Functions (UDF)
udf decorator
def udf(
func=None,
*,
return_dtype: DataType = None,
deterministic: bool = True,
name: str = None,
concurrency: Optional[int] = None,
batch_size: Optional[int] = None,
) -> DataFrameUDFWrapper
Register a Python function as a Flink UDF. Supports:
- Type inference from Python type hints (no
return_dtypeneeded) - Async UDFs with configurable
concurrencyfor I/O-bound operations - Batch UDFs with batch_size for pandas or Arrow vectorized processing
Example:
# Simple UDF with type inference
@pf.udf
def double(x: int) -> int:
return x * 2
# UDF with explicit return type
@pf.udf(return_dtype=DataType.string())
def categorize(age):
return "adult" if age >= 18 else "minor"
# Async UDF for API calls
@pf.udf(concurrency=32)
async def enrich(user_id: int) -> str:
return await api_client.get_user_name(user_id)
# Usage in DataFrame operations
result = df.with_columns(
doubled=double(col("value")),
category=categorize(col("age")),
)
udtf decorator
def udtf(
func=None,
*,
return_dtype: DataType = None,
deterministic: bool = True,
name: str = None,
concurrency: Optional[int] = None,
) -> DataFrameUDTFWrapper
Register a Python table function (UDTF) — a function that emits zero, one, or many rows per call. Use it with join_lateral (invoked with column arguments) or flat_map (applied to the whole row). The function emits rows by yielding or returning an iterable of scalars, tuples, or dicts (when fields are named).
- Type inference from the return hint (
Iterator[T],Iterator[Tuple[...]], orIterator[TypedDict]); otherwise passreturn_dtype. - Output field names come from a
TypedDict/ named struct return type, or from.alias(...)at the call site. - Wraps plain functions/lambdas,
TableFunctionsubclasses or instances, and callable class instances. - Concurrency:
concurrencyconfigures the UDTF's degree of concurrency, as withudf.
Example:
from typing import Iterator, Tuple
import pyflink.dataframe as pf
from pyflink.dataframe import DataType
# Type-hint inference
@pf.udtf
def chars(text: str) -> Iterator[str]:
for ch in text:
yield ch
# Explicit return_dtype (no type hint)
@pf.udtf(return_dtype=DataType.string())
def split_words(text):
for word in text.split():
yield word
# Multi-field tuple output; name the fields at the call site
@pf.udtf
def pair(x: int) -> Iterator[Tuple[int, str]]:
yield x, str(x)
df.join_lateral(pair(pf.col("a")).alias("value", "text"))
udaf decorator
def udaf(
func=None,
*,
return_dtype: DataType = None,
accumulator_type: DataType = None,
func_type: str = "general",
deterministic: bool = True,
name: str = None,
) -> DataFrameUDAFWrapper
Define an aggregate function (UDAF) that maps the scalar values of multiple rows to a single scalar value. Use it inside agg / group_by().agg(), mixed freely with built-in aggregates such as avg / sum / count.
Two implementation styles:
- Incremental (
func_type="general", the default): decorate anAggregateFunctionsubclass implementingcreate_accumulator(),accumulate(acc, *args), andget_value(acc). The accumulator is updated incrementally, which suits streaming aggregation. Implementretract(acc, *args)to support updating/retracting input (streaming with updates), andmerge(acc, others)for session windows or bounded over-windows. - Vectorized (
func_type="pandas"): decorate a plain function or lambda; each group's input column arrives as a whole PandasSeriesand the function returns a single scalar. Suited to batch and bounded windows; it is not applicable to an unbounded streaminggroup_by, which would have to buffer every row.
The result type comes from the return type hint, or pass return_dtype. For incremental UDAFs, declare accumulator_type when the accumulator type cannot be inferred.
Example:
from pyflink.table.udf import AggregateFunction
import pyflink.dataframe as pf
from pyflink.dataframe import DataType
# Incremental UDAF: weighted average
class WeightedAvg(AggregateFunction):
def create_accumulator(self):
return [0.0, 0.0] # [weighted_sum, weight_sum]
def accumulate(self, acc, value, weight):
if value is not None:
acc[0] += value * weight
acc[1] += weight
def retract(self, acc, value, weight):
if value is not None:
acc[0] -= value * weight
acc[1] -= weight
def get_value(self, acc):
return acc[0] / acc[1] if acc[1] != 0 else None
weighted_avg = pf.udaf(
WeightedAvg(),
return_dtype=DataType.float64(),
accumulator_type=DataType.list(DataType.float64()),
)
df.group_by("dept").agg(
weighted_avg(pf.col("salary"), pf.col("weight")).alias("wavg")
)
# Vectorized (pandas) UDAF: median per group
@pf.udaf(func_type="pandas")
def median(v: float) -> float:
return v.median()
df.group_by("dept").agg(median(pf.col("salary")).alias("median_salary"))
19. DataFrame — SQL
sql
def sql(
query: str,
*,
auto_bind: bool = True,
**bindings,
) -> DataFrame
Run a SQL SELECT query and return its result as a DataFrame, so SQL and the DataFrame API mix freely. DataFrames referenced in the query are exposed as temporary views, and @pf.udf / @pf.udtf functions as temporary functions; both are registered only for the duration of the call and dropped afterwards.
There are two ways to make Python objects visible to the query:
- Auto-bind (default,
auto_bind=True):sqlscans the caller's local and global variables forDataFrameand UDF/UDTF objects and registers each under its Python variable name. Auto-bind is best-effort — it warns and skips names that are not valid SQL identifiers or that collide with an existing table/view/function, and it never shadows permanent catalog objects or built-in functions. - Explicit bindings: pass keyword arguments to choose the SQL name yourself, e.g.
pf.sql("SELECT * FROM s", s=df). Explicit bindings are strict (conflicts raiseValueError), take precedence over auto-bind on name collisions, and are required to intentionally shadow a catalog table/view or a built-in function.
Only SELECT queries are supported (no INSERT / DDL). The returned DataFrame can be further transformed with the DataFrame API.
Example:
import pyflink.dataframe as pf
df1 = pf.from_dict({"a": [1, 2, 3], "b": ["x", "y", "z"]})
df2 = pf.from_dict({"a": [1, 2, 3], "c": ["p", "q", "r"]})
# Auto-bind: df1 / df2 are registered under their variable names
joined = pf.sql("SELECT df1.a, b, c FROM df1 JOIN df2 ON df1.a = df2.a")
# UDFs are auto-bound too
@pf.udf
def add_one(x: int) -> int:
return x + 1
incremented = pf.sql("SELECT add_one(a) AS a1 FROM df1")
# Explicit bindings: pick the SQL names, turn off scanning
result = pf.sql(
"SELECT * FROM src WHERE a > 1",
auto_bind=False,
src=df1,
)
# Mix SQL and the DataFrame API
pf.sql("SELECT a, b FROM df1").filter(pf.col("a") > 1).to_pandas()
20. Configuration
Flink exposes configuration in more than one place. The StreamExecutionEnvironment carries DataStream-level runtime settings such as default parallelism, checkpointing, and the restart strategy, while the TableEnvironment carries table/SQL settings through its TableConfig. Used directly, this requires creating the environments in the right order and knowing which option belongs to which environment before any job is built.
The DataFrame API hides this behind a single entry point. pf.config accepts any Flink configuration key and buffers it, so configuration can be set at any time — even before an environment exists. Buffered values are applied automatically once the underlying TableEnvironment is created or injected, so users no longer manage environment creation order or choose between environment objects for the common case.
DataFrameConfig
class DataFrameConfig:
def set(self, key: str, value: str) -> DataFrameConfig
def get(self, key: str, default: Optional[str] = None) -> Optional[str]
A singleton config object for setting runtime configuration.
Example:
import pyflink.dataframe as pf
pf.config.set("parallelism.default", "4")
pf.config.set("execution.runtime-mode", "batch")
Context Management
# Inject an existing environment -- e.g. when mixing with the
# DataStream / Table API, or to reuse one across tests.
pf.set_table_environment(t_env)
# Inspect the current environment (None if not yet created).
t_env = pf.get_table_environment()
# Get the current environment, lazily creating one (with buffered
# pf.config applied) if none has been set.
t_env = pf.get_or_create_table_environment()
When no TableEnvironment has been set, the DataFrame API lazily creates a StreamExecutionEnvironment and a StreamTableEnvironment with sensible defaults on first use, and applies any buffered pf.config values to it. To integrate with an existing pipeline — for example one that already configures a StreamExecutionEnvironment for DataStream operations — inject that environment with set_table_environment, and the buffered DataFrame config is applied to it as well.
21. AI/LLM Integration
The DataFrame API includes an AI accessor for integrating Large Language Models into data pipelines.
set_model_provider
def set_model_provider(
name: str,
provider: ModelProvider,
) -> None
Register a model provider used by df.llm under a lookup name you choose. The name is how you refer to this provider later — via provider= on a call, or via set_default_model_provider(name) — and it is what list_model_providers() returns, so pick something memorable (e.g. "chat", "embed"). Registering several providers, or several instances of the same type (one for chat, one for embeddings), simply means giving each a distinct name. With a single provider registered, df.llm selects it automatically, so the name only needs to be referenced once more than one is registered.
Parameters:
name: the lookup name to register the provider under; must be unique.provider: aModelProviderinstance.
Two providers ship built in: `OpenAIProvider`, which wraps Flink's built-in `openai` model provider (usable with OpenAI-compatible chat or embeddings endpoints such as OpenAI, DeepSeek, or Bailian), and `TritonProvider`, which wraps Flink's built-in `triton` model provider for NVIDIA Triton Inference Server. Each exposes typed constructor arguments — endpoint, credentials, generation options, and streaming-oriented controls such as `error_handling_strategy` and retry / circuit-breaker settings — with IDE auto-complete and validation.
For a provider without a dedicated class, use `GenericProvider`, whose first argument is the raw Flink provider identifier and whose options are forwarded to the Java side unchanged; for a reusable strongly-typed integration, subclass `ModelProvider` and implement `provider_identifier()` (returning that Flink identifier) and `to_options()` (optionally `model_option_key()`).
Example:
from pyflink.dataframe import (
set_model_provider, OpenAIProvider, GenericProvider, ModelProvider)
# Register a provider under a name you choose.
set_model_provider("openai", OpenAIProvider(
endpoint="https://api.openai.com/v1",
api_key="sk-...",
model="gpt-4o",
))
# Several instances of the same type, each under a distinct name.
set_model_provider("chat", OpenAIProvider(
endpoint="https://api.openai.com/v1/chat/completions", api_key="sk-..."))
set_model_provider("embed", OpenAIProvider(
endpoint="https://api.openai.com/v1/embeddings", api_key="sk-..."))
# Generic form: GenericProvider's first argument is the Flink provider
# identifier; its options are forwarded to the Java side unchanged.
set_model_provider("my-provider", GenericProvider(
"some-flink-provider", **{"endpoint": "https://...", "api-key": "sk-..."}))
# A reusable, strongly-typed custom provider.
class MyProvider(ModelProvider):
def __init__(self, endpoint, api_key):
self._endpoint, self._api_key = endpoint, api_key
def provider_identifier(self) -> str: # Flink provider identifier
return "some-flink-provider"
def to_options(self) -> dict: # Java-side option keys
return {"endpoint": self._endpoint, "api-key": self._api_key}
set_model_provider("custom", MyProvider(endpoint="https://...", api_key="sk-..."))
set_default_model_provider
def set_default_model_provider(name: str) -> None
Choose which registered provider df.llm uses when a call does not pass provider=. This matters only when more than one provider is registered; with a single provider it is selected automatically. The name must already be registered via set_model_provider, and any individual call can still override the default with provider=.
Parameters:
name: the name of an already-registered provider.
Example:
from pyflink.dataframe import set_model_provider, set_default_model_provider, OpenAIProvider
set_model_provider("chat", OpenAIProvider(
endpoint="https://api.openai.com/v1", api_key="sk-..."))
set_model_provider("embed", OpenAIProvider(
endpoint="https://api.openai.com/v1", api_key="sk-..."))
# With several providers registered, pick the one used by default.
set_default_model_provider("chat")
list_model_providers
def list_model_providers() -> List[str]
Return the names of all registered providers, in registration order.
Example:
from pyflink.dataframe import set_model_provider, list_model_providers, OpenAIProvider
set_model_provider("chat", OpenAIProvider(
endpoint="https://api.openai.com/v1", api_key="sk-..."))
set_model_provider("embed", OpenAIProvider(
endpoint="https://api.openai.com/v1", api_key="sk-..."))
list_model_providers() # -> ["chat", "embed"]
df.llm.predict
def predict(
self,
*input_cols: str,
provider: str = None,
model: str = None,
output_type: Union[str, DataType] = None,
config: Dict[str, str] = None,
) -> "DataFrame"
Run model inference over one or more input columns and append the model output to the DataFrame. It runs on top of Flink's model inference, so it benefits from distributed execution for parallel requests. A provider must be configured (see set_model_provider); a temporary model is created from the input columns and the declared output_type, and the model is invoked per row.
Parameters:
*input_cols: one or more column names used as model input.provider: the name of a registered provider (seeset_model_provider); uses the default when omitted, and the single registered provider is selected automatically.model: the model id for the configured provider, e.g."gpt-4o".output_type: the output schema. A scalar type (the default"STRING", or"VARIANT"for free-form JSON) appends a single column namedoutput. ADataType.struct(...)declares a structured output: the structure is pushed to the model as a decoding constraint (schema-guided / strict JSON-schema decoding) and the response is expanded into strongly-typed columns named after the struct fields, with no manual JSON parsing or casting. Nesting is expressed by nestingstruct.config: optional provider-specific runtime options.
Example:
from pyflink.dataframe import set_model_provider, OpenAIProvider
# Register a provider; with a single provider, df.llm selects it automatically.
set_model_provider("openai", OpenAIProvider(
endpoint="https://api.openai.com/v1", api_key="sk-..."))
# Default: append a single STRING column "output".
df.llm.predict("question", model="gpt-4o")
# Free-form JSON in a single VARIANT column.
df.llm.predict("question", model="gpt-4o", output_type="VARIANT")
# Structured output: the model is constrained to the declared struct and
# the result is expanded into typed columns.
df.llm.predict(
"review",
model="gpt-4o",
output_type=DataType.struct({
"sentiment": DataType.string(), # positive / negative / neutral
"score": DataType.float64(),
"aspects": DataType.list(DataType.string()),
}),
)
# Appends columns: sentiment (STRING), score (DOUBLE), aspects (ARRAY<STRING>)
# Nested structures are supported.
df.llm.predict(
"doc",
model="gpt-4o",
output_type=DataType.struct({
"user": DataType.struct({"name": DataType.string(), "age": DataType.int32()}),
"orders": DataType.list(DataType.struct({
"item": DataType.string(), "price": DataType.float64(),
})),
}),
)
Design Decisions
Why a Wrapper over Table API?
- Leverage existing optimizer — Flink's query optimizer already handles the Table API expressions
- Minimal maintenance burden — No new SQL planner rules or execution operators needed
- Consistent semantics — DataFrame operations produce the same execution plans as equivalent Table API code
- Easy interop — Users can freely mix DataFrame and Table API code via
to_table()/from_table() - Single bridge to DataStream — DataFrame does not add a second, direct conversion surface to DataStream for now; users can convert through Table instead. Reusing Table as the only bridge avoids duplicating semantics around changelog vs append-only streams, rowtime/proctime, schema and type mapping, and connector boundaries in yet another API layer.
Why Not Extend an Existing DataFrame API?
While some projects attempt to provide a compatibility layer over an existing DataFrame API, our approach differs because:
- Flink supports streaming semantics (unbounded data) which existing in-memory DataFrame libraries cannot express
- Flink's distributed execution requires a declarative API that can be optimized and distributed
- We need access to Flink's connector ecosystem (Kafka, filesystem, etc.)
- We borrow widely-adopted DataFrame ergonomics but follow Flink's semantics
Expression Reuse
The DataFrame API reuses the Table API's Expression type directly rather than defining its own expression DSL. This:
- Avoids maintaining a parallel expression system
- Allows advanced users to use the full power of Table API expressions
- Makes
col()andlit()simple delegates
import pyflink.dataframe as pf
from pyflink.dataframe import DataType
# col() / lit() are thin delegates to the Table API's expression builders;
# arithmetic, .cast(), and .alias() are the Table API's Expression methods.
gross = (pf.col("price") * pf.lit(1.1)).cast(DataType.float64()).alias("gross")
df.select(pf.col("id"), gross) # DataFrame API
Typed Connector Parameters over Descriptor Options
In the Table API, a source or sink is described with a TableDescriptor (or SQL DDL) whose connector and format settings are untyped string options, e.g. TableDescriptor.for_connector("kafka").option("scan.startup.mode", "earliest-offset"). The keys are discoverable only by consulting connector documentation, and a typo or an out-of-domain value surfaces only at job-build or run time.
The DataFrame API instead gives each common connector a dedicated reader/writer (read_kafka, read_parquet, read_json, and their write_* counterparts) whose parameters are explicit, typed Python keyword arguments — startup_mode: Literal[...], delivery_guarantee: Literal[...], monitor_interval, and so on — that map one-to-one onto the underlying Flink option keys.
This yields IDE auto-completion, inline documentation, and early validation (an illegal startup_mode is a Literal violation, not a runtime surprise), at the cost of one wrapper per connector. To bound that cost and avoid lagging behind connector evolution, the typed wrappers cover only commonly used options and are backed by read_generic / write_generic, which accept the raw connector identifier plus an arbitrary options dict — the same escape-hatch philosophy as GenericProvider in §21. Less common connectors, or advanced options not yet surfaced as typed parameters, stay fully reachable without waiting for a dedicated wrapper.
# Table API: untyped option strings
t_env.from_descriptor(
TableDescriptor.for_connector("kafka")
.option("properties.bootstrap.servers", "localhost:9092")
.option("topic", "events")
.option("scan.startup.mode", "earliest-offset")
.schema(...).build()
)
# DataFrame API: typed keyword arguments
pf.read_kafka(
"localhost:9092",
topic="events",
startup_mode="earliest-offset",
schema={"user_id": DataType.int64()}
)
Eager Writes, Opt-in Statement Sets
The Table API is explicit about execution: building a pipeline is lazy, and a sink runs only when execute_insert or a StatementSet is explicitly executed. The DataFrame API makes the common case — "I have a result, write it out" — eager: each write_* call compiles its DataFrame into a Flink job and submits it immediately (waiting for completion in local execution). This matches the imperative mental model users bring from pandas / Spark .write, where a write is an action, not a deferred declaration. The trade-off is that calling several write_* methods produces several independent jobs, each re-reading the source and re-computing shared operators — in streaming, the same Kafka topic would be consumed once per sink.
Rather than make every write lazy (which would bring the Table API's explicit-execution ceremony back into the simple case), the API keeps eager writes as the default and offers an opt-in create_statement_set() plus a statement_set= argument on every write_*: staged writes compile into a single job whose shared sources and sub-plans are read and computed once and fanned out to all sinks, under one unified set of checkpoint barriers. This preserves Flink's source-reuse and consistent-checkpointing benefits exactly when the user asks for them, while keeping the default path a single, obvious action. Coupled backpressure and shared failover across sinks are the corresponding cost of the statement-set path, so sinks that must stay isolated are left as separate eager writes.
# Single sink --
t_env.from_path("events").execute_insert("sink") # Table API: lazy, runs on execute_insert
df.write_parquet("s3:///lake/events/") # DataFrame API: eager, submitted at once
# Multiple sinks, one job --
# Table API: stage each insert on a StatementSet, then execute once.
events = t_env.from_path("events")
sset = t_env.create_statement_set()
sset.add_insert("lake_sink", events)
sset.add_insert("clean_topic", events)
sset.execute() # one job: the source is read once and fanned out to both sinks
# DataFrame API: opt in with create_statement_set(), pass statement_set= to each write.
sset = pf.create_statement_set()
df.write_parquet("s3:///lake/events/", statement_set=sset)
df.write_kafka("localhost:9092", topic="events-clean", statement_set=sset)
sset.execute() # the same single fanned-out job
First-Class Streaming Patterns
Several operations that are idiomatic in DataFrame libraries correspond, in Flink, to verbose and easy-to-get-wrong SQL patterns rather than to a single operator:
- Per-group Top-N is
ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)wrapped in an outer filter on the rank; - Deduplication / "latest row per key" is the same
ROW_NUMBERidiom withrownum = 1; - A lookup against a dimension table is a
FOR SYSTEM_TIME AS OFtemporal join; - Unnesting a collection is
CROSS JOIN UNNEST(...).
The DataFrame API promotes each of these to a named method — top_n, drop_duplicates (aliased distinct / unique), join_asof, explode — that reads the way the corresponding pandas / Spark / Polars operation reads, while compiling to the same Flink plan as the hand-written SQL.
Users express intent directly ("top 3 per category", "keep the latest per device") instead of reconstructing a windowed-rank idiom and recalling its streaming caveats, and the methods encode the streaming-correct defaults (e.g. drop_duplicates(order_by=..., keep=...) maps to the deduplication operator rather than a batch-only DISTINCT). The cost is a larger surface of named methods than the Table API exposes, which we accept because these patterns are common enough that hiding the boilerplate is a primary ergonomic win of the API.
# Flink SQL pattern for per-group Top-N:
# SELECT * FROM (
# SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC) AS rn
# FROM t) WHERE rn <= 3
# DataFrame API
df.top_n(3, partition_by="category", order_by="sales", descending=True)
Windowing as a Column-Appending TVF with Operator Reuse
Flink offers two windowing models: the legacy grouped-window (window(Tumble.over(...).on(...).alias("w")), producing a GroupWindowedTable that must then be grouped on the window alias), and the newer Windowing TVF, where a window assigns each row window_start / window_end / window_time columns and every downstream operation — aggregation, Top-N, deduplication, join — is recognized as its "window" variant purely from the presence of those columns.
The DataFrame API adopts the TVF model but exposes the common window kinds as flattened DataFrame methods: tumble, hop, cumulate, and session. Each method appends window_start, window_end, and window_time, then returns an ordinary DataFrame. There are deliberately no separate window-aggregate, window-top-n, window-join, or window-dedup operators; users reuse group_by().agg(), top_n, drop_duplicates, and join, carrying window_start/window_end explicitly. This adds a few named entry points compared with a single window(spec) method, but removes a wrapper object from the user-facing API and reads closer to Python DataFrame libraries such as Ibis.
Pandas/Arrow-Native Naming and Types
The target audience is Python data engineers, data scientists, and ML practitioners who already know pandas, Polars, or Spark, but not Flink's Table/SQL vocabulary. Where a name does not change semantics, the API borrows the spelling that audience already knows:
DataTypeuses Arrow/NumPy-style width-explicit names (int32/int64/float32/float64) instead of the SQL spellings (INT/BIGINT/FLOAT/DOUBLE).- Column operations are
with_column/with_columns/rename/droprather thanadd_or_replace_columns/rename_columns/drop_columns; - Row filtering uses subscripting (
df[expr]), column projection uses subscripting (df[["a", "b"]]), column references may also use attribute access when valid (df.name), andfilteradditionally accepts SQL strings and equality kwargs; - Metadata is exposed as the
schema/columnsproperties rather than getter methods;
The goal is not pandas compatibility — that is an explicit Non-Goal — but discoverability: the method a user reaches for by muscle memory exists and does the analogous thing. The trade-off is divergence from Table API naming, which we accept because the two APIs interoperate explicitly through to_table() / from_table() rather than by sharing a vocabulary, and because the underlying Expression and type system are reused unchanged (see Expression Reuse) — the divergence is skin-deep, in the surface names rather than the semantics.
Python-Native and ML-Oriented Row Transforms
The Table API's row-level extension point is the scalar UDF plus table.map(func), oriented around single typed values. The DataFrame API adds two transforms shaped for Python data and ML workloads:
maptakes aDict[str, Any] -> Dict[str, Any]function, so a transform reads and writes columns by name and can add or drop columns without a positional schema dance — the natural shape for record-at-a-time Python logic.map_batchesexposes vectorized processing directly: the function receives and returns a batch asdict[str, pandas.Series]ordict[str, pyarrow.Array], the idiom for ML inference, Arrow-native compute, and batched remote API calls.
Both transforms carry the resource and concurrency knobs those workloads need — concurrency for async / I/O-bound work and batch_size for vectorization — surfaced as per-transform parameters rather than buried in configuration.
This borrows the map / map_batches split popularized by Ray Data, which the target audience already associates with scalable batch and ML pipelines, while still compiling to Flink's existing (vectorized) Python UDF runtime, so distributed execution, backpressure, and checkpointing are unchanged. The trade-off is more entry points than the Table API's single map, justified by the distinct execution profiles — row-at-a-time and vectorized — that they make explicit.
from typing import Any, Dict
import pyarrow as pa
from pyflink.dataframe import DataType
# Table API: a scalar UDF takes one typed value, wired in positionally; you
# re-select the columns to keep alongside the UDF's output.
@udf(result_type=DataTypes.STRING())
def age_group(age):
return "adult" if age >= 18 else "minor"
t.select(col("name"), age_group(col("age")).alias("age_group"))
# DataFrame API -- map: one function sees the whole row as a Dict[str, Any]
# keyed by column name and returns the new row, adding or dropping columns.
def add_group(row: Dict[str, Any]) -> Dict[str, Any]:
return {"name": row["name"],
"age_group": "adult" if row["age"] >= 18 else "minor"}
df.map(add_group, return_dtype=DataType.struct(
{"name": DataType.string(), "age_group": DataType.string()}))
# DataFrame API -- map_batches: the function gets a vectorized batch, the idiom
# for ML inference and Arrow compute. batch_size sets the vectorization width;
# concurrency controls the async / I/O-bound degree of concurrency.
def classify(batch: Dict[str, pa.Array]) -> Dict[str, pa.Array]:
return {"label": pa.array(model.predict(batch["image"]))}
df.map_batches(classify, batch_format="arrow",
return_dtype=DataType.struct({"label": DataType.int64()}),
batch_size=256, concurrency=4)
Arrow and Pandas Batch Formats
map_batches transports each batch in one of two formats, chosen with batch_format:
"arrow"hands the function adict[str, pyarrow.Array]: this is the batch format Flink's vectorized Python UDF runtime already uses, so it usually avoids extra conversions and keeps Flink logical types closer to their native representation than pandas or NumPy. In particular, nullability, nestedARRAY/ROW/MAP, decimals, and timestamps remain first-class instead of degrading into NumPy-style object / float workarounds."pandas"hands the function adict[str, pandas.Series], a conversion on top of Arrow that trades some type/directness and conversion overhead for the familiarity and ecosystem of pandas. Together they span the two common needs of vectorized work: closer-to-runtime type representation and lower conversion overhead (arrow) and ergonomics (pandas).
There is deliberately no numpy batch format, even though Ray Data — whose map / map_batches split this API borrows — defaults to it. Two reasons:
- First, NumPy is one call away inside the function (
arr.to_numpy()on an Arrow array, orseries.to_numpy()on a pandas Series), zero-copy for numeric columns, which is exactly where ML inference needs it — so a NumPy format would add no capability. - Second, as a column transport NumPy cannot faithfully carry Flink's logical types: it has no native null (nullable integers degrade to
float64+NaN or object arrays), no string type (strings become object arrays), and no representation for nestedARRAY/ROW/MAP— precisely the types Arrow and pandas carry cleanly. Ray defaults to NumPy because its block model is tensor-oriented; Flink's column model is Arrow/SQL-typed, where nullability and nested types are first-class, so a NumPy default would trade away fidelity for no real gain. If a strong need appears, NumPy could be added later. Happy to see the community's options.
# NumPy is an in-function detail, not a transport format: convert the columns
# you actually need, zero-copy for numeric data.
def classify(batch: dict[str, pyarrow.Array]):
images = batch["image"].to_numpy()
return {"label": pa.array(model.predict(images))}
df.map_batches(
classify,
batch_format="arrow",
return_dtype=DataType.struct({"label": DataType.int64()})
)
Concurrency Configuration
`map`, `map_batches`, and `@udf` / `@udtf` all accept a `concurrency` argument. It controls the degree of concurrency of the Python stage that runs *that* transform: by default the stage follows the surrounding execution settings, and `concurrency` overrides them for that stage alone. Transforms with different `concurrency` values are placed in separate operators, so each Python stage can run at its own concurrency independently of the rest of the pipeline.
The reason to expose this per transform — rather than relying only on the job-wide `parallelism.default` — is that Python transforms are usually far more expensive per record than the relational operators around them. ML inference, remote API / LLM calls, and GPU compute can dominate the cost of a pipeline whose other operators are cheap projections and filters. Scaling such a stage through the global knob would force every operator up with it, over-provisioning the cheap ones and inflating their state and shuffles. `concurrency` scales only the stage that needs it. For async / I/O-bound UDFs it is also the lever that raises the number of in-flight invocations, hiding remote latency.
# parallelism.default applies to every operator in the job alike -- raising it
# to scale one costly Python UDF also over-provisions the cheap relational
# operators around it, inflating their state and shuffles.
pf.config.set("parallelism.default", "4")
# concurrency scales only the Python stage that needs it. This map operator
# runs with concurrency 32 for the remote / GPU inference call while the rest
# of the job stays at the default; async / I/O-bound UDFs use it to hide
# remote latency.
df.map_batches(
classify,
batch_format="arrow",
return_dtype=DataType.struct({"label": DataType.int64()}),
concurrency=32,
)
Unified Configuration and SQL Interop
Two friction points when dropping into Flink from Python are configuration and mixing in SQL, and the DataFrame API smooths both. Configuration in Flink lives in more than one place — StreamExecutionEnvironment carries DataStream-level runtime settings (parallelism, checkpointing, restart strategy) while TableEnvironment carries table/SQL settings via TableConfig — and using them directly requires creating the environments in the right order and knowing which option belongs to which.
The DataFrame API replaces this with a single pf.config entry point that accepts any Flink configuration key and buffers it, even before any environment exists; buffered values are applied automatically once the underlying TableEnvironment is created lazily or injected via set_table_environment. Users therefore neither manage environment-creation order nor choose between environment objects for the common case, while retaining the ability to inject and reuse an existing environment for interop.
For SQL, the Table API requires registering each table or view in a catalog before a sql_query can reference it; pf.sql instead auto-binds — it scans the caller's local and global variables for DataFrame and @udf / @udtf objects and registers each under its Python variable name as a temporary view / function for the duration of the call, dropping them afterward. This makes pf.sql("SELECT ... FROM df1 JOIN df2 ...") work with no explicit registration, so users can reach for SQL exactly where it is more natural than method chaining and return to the DataFrame world for the rest. Auto-bind is deliberately best-effort and safe — it skips names that are not valid SQL identifiers or that collide with existing objects, never shadows permanent catalog objects, and is overridable by explicit keyword bindings (and disabled with auto_bind=False) when the user wants full control. The trade-off — a small amount of implicit, variable-name-based magic — is contained by these guardrails and the explicit-binding path.
import pyflink.dataframe as pf
# Configuration --
# Table API: create the environments in order, then set config on the right
# object (StreamExecutionEnvironment for runtime, TableConfig for table/SQL).
env = StreamExecutionEnvironment.get_execution_environment()
t_env = StreamTableEnvironment.create(env)
t_env.get_config().set("parallelism.default", "4")
# SQL interop --
# Table API: register every table as a view before it can be referenced.
t_env.create_temporary_view("df1", table1)
t_env.create_temporary_view("df2", table2)
joined = t_env.sql_query(
"SELECT df1.a, b, c FROM df1 JOIN df2 ON df1.a = df2.a")
# DataFrame API: one entry point, buffered -- set keys before any env exists.
pf.config.set("parallelism.default", "4")
# DataFrame API: pf.sql auto-binds df1 / df2 from local variables by name.
joined = pf.sql("SELECT df1.a, b, c FROM df1 JOIN df2 ON df1.a = df2.a")
Implicit Model Registration
In the Table API, model inference requires a model to exist before it can be used: it is declared up front via `CREATE MODEL` (or a `ModelDescriptor`) and then referenced by name in `ML_PREDICT`. In the DataFrame API, `df.llm.predict` removes this two-step ceremony. From the configured provider, the call's input columns, and the declared `output_type`, it builds a `ModelDescriptor` and registers a temporary model on the fly (under an internal generated name) for the duration of the call, then runs inference against it. Users never write `CREATE MODEL`, manage a model catalog, or hand-construct a `ModelDescriptor` — a model is described inline in Python at the call site, so a single `predict(...)` call expresses both which model to run and how to shape its output. Because the temporary model is built on Flink's standard model-inference machinery, this convenience costs nothing at runtime: it still benefits from distributed execution and provider runtime options.
from pyflink.dataframe import set_model_provider, OpenAIProvider
# Table API: a model must be declared up front, then referenced by name --
# two steps, plus a catalog object to manage.
# CREATE MODEL my_model
# INPUT (question STRING)
# OUTPUT (output STRING)
# WITH ('provider' = 'openai', 'endpoint' = '...', 'model' = 'gpt-4o');
#
# SELECT * FROM ML_PREDICT(TABLE questions, MODEL my_model, DESCRIPTOR(question));
# DataFrame API: configure the provider once, then describe the model inline at
# the call site -- predict builds and registers a temporary model on the fly.
set_model_provider("openai", OpenAIProvider(
endpoint="https://api.openai.com/v1", api_key="sk-..."))
df.llm.predict("question", model="gpt-4o")
Why df.llm.predict instead of a top-level predict?
The llm inference related API is intentionally namespace-based: inference is invoked through df.llm.predict(...). This groups DataFrame-level inference calls under a single llm entry point. A top-level predict would give a very general name to one specific class of AI inference, make the top-level API surface harder to keep focused, and blur the boundary between relational DataFrame operators and AI-oriented helpers. Keeping predict under llm also leaves a consistent namespace for additional built-in AI inference capabilities in the future. The tradeoff is a slightly longer call site, but the API structure is clearer and easier to extend.
Example: End-to-End Pipeline
import pyflink.dataframe as pf
# Replace the connector endpoints / paths below with real values from your environment.
# Read streaming data from Kafka
events = pf.read_kafka(
"kafka:9092",
topic="user-events",
format="json",
schema={
"user_id": pf.DataType.int64(),
"event_type": pf.DataType.string(),
"timestamp": pf.DataType.timestamp_ltz(),
"amount": pf.DataType.float64(),
},
startup_mode="latest-offset",
)
# Define a UDF
@pf.udf
def categorize_amount(amount: float) -> str:
if amount > 1000:
return "high"
elif amount > 100:
return "medium"
else:
return "low"
# Transform
result = (
events
.filter(pf.col("event_type") == "purchase")
.with_column("category", categorize_amount(pf.col("amount")))
.drop("event_type")
.rename({"user_id": "uid"})
)
# Write results
result.write_parquet("s3://output/purchases/", rolling_policy_file_size="256mb")
Compatibility, Deprecation, and Migration Plan
- No breaking changes to the existing Table API or DataStream API
- The DataFrame API is a new addition (new package
pyflink.dataframe) - Users can incrementally adopt the DataFrame API while continuing to use the Table API
from_table()/to_table()provide bidirectional interop- Existing Table API users do not need to migrate
Test Plan
All changes will be covered by unit tests, integration tests, and end-to-end tests.
Future Work
The following capabilities are valuable but out of scope for this FLIP, and are expected to be addressed by follow-up work:
- Keyed group processing (
key_by().map_groups()) — apply a user function to all rows of a key as a group. - Explicit shuffle / repartition API — let users control partitioning (e.g. repartition by key) instead of relying only on planner-decided distribution; this must define how explicit shuffles interact with optimizer decisions and streaming semantics.
- GPU support — expose GPU resources (e.g.
num_gpus/gpu_type) formap_batchesinference stages or user defined functions. - NumPy batch format — an additional
map_batchestransport alongsidearrow/pandas; lightweight to add incrementally if a strong need appears (see "Arrow and Pandas Batch Formats").
Rejected Alternatives
Alternative 1: Extend an Existing DataFrame API
Rejected because existing DataFrame APIs assume bounded, in-memory data. Flink's streaming semantics (event time, watermarks, windows) cannot be naturally expressed through a compatibility layer without confusing deviations.
Alternative 2: Build on top of DataStream API
Rejected because the Table API already provides the relational abstraction needed (schema, expressions, optimizer). The DataStream API is too low-level for a DataFrame-style interface and would require reimplementing optimization logic.