Python DataFrame API reference

更新时间:
复制 MD 格式

The Python DataFrame API lets you write Flink jobs using familiar DataFrame-style operations such as filter, projection, join, and aggregation. It also supports Python user-defined functions (UDFs) and built-in AI/LLM functions for tasks like classification, extraction, and summarization. For the complete API reference, see  PyFlink DataFrame.

Basic DataFrame operations

The following table lists the core operations on a DataFrame.

API type

API details

Construction / creation

from_table, from_pandas, from_dict, from_records

Attributes

schema, columns

Projection / column operations

select, with_column, with_columns, drop_columns, rename_columns

Filter

filter

Aggregation

group_by, agg

Join / merge

join, join_asof, join_lateral

Row mapping

map, map_batches, flat_map

Explode

explode

Set operations

union, union_all, minus, minus_all, intersect, intersect_all

Limit / pagination

limit, offset

Null value handling

drop_null, drop_nan, fill_null, fill_nan

Output / collection

to_table, to_pandas, collect, iter_rows, iter_batches

Debug / execution plan

explain

SQL

sql

Expression helper functions

Function

Description

col

Returns a column reference expression.

lit

Returns a literal expression.

Data types

DataType represents the data type of a DataFrame column.

Category

Method

Boolean

DataType.bool

Integer

DataType.int8, DataType.int16, DataType.int32, DataType.int64

Floating-point

DataType.float32, DataType.float64, DataType.decimal

String

DataType.string, DataType.fixed_size_string

Binary

DataType.binary, DataType.fixed_size_binary

Date / Time

DataType.date, DataType.time, DataType.timestamp, DataType.timestamp_ltz

Composite

DataType.list, DataType.map, DataType.struct

Special

DataType.null, DataType.variant

Multimodal

DataType.tensor, DataType.image

Nullability modifier

DataType.not_null, DataType.nullable

Use DataType to specify a schema for a data source and to define the output type of a user-defined function (UDF). For example, the following code defines the schema for a Kafka data source:

import pyflink.dataframe as pf
from pyflink.dataframe import DataType

df = pf.read_kafka(
    "localhost:9092",
    topic="user_events",
    schema={
        "user_id": DataType.string(),
        "event_type": DataType.string(),
        "amount": DataType.decimal(10, 2),
        "tags": DataType.list(DataType.string()),
        "event_time": DataType.timestamp_ltz(3),
    },
    format="json",
    startup_mode="earliest-offset",
)

I/O

DataFrame provides I/O APIs to read from and write to common data sources. The read_custom and write_custom functions let you use other supported connectors or custom connectors.

Reading

Data source

API

Parquet file

read_parquet

Kafka

read_kafka

MaxCompute (ODPS)

read_odps

Paimon

read_paimon

SLS (Log Service)

read_sls

Hologres

read_hologres

Milvus

read_milvus

Custom connector

read_custom

Writing

Destination

API

Parquet file

write_parquet

Kafka

write_kafka

MaxCompute (ODPS)

write_odps

Paimon

write_paimon

SLS (Log Service)

write_sls

Hologres

write_hologres

Milvus

write_milvus

Custom connector

write_custom

Using Catalog

The DataFrame API supports Catalog integration for reading from and writing to Catalog tables.

API

Description

create_catalog

Creates a Catalog.

use_catalog

Switches the current Catalog.

get_current_catalog

Gets the current Catalog.

list_catalogs

Lists all Catalogs.

use_database

Switches the current database.

get_current_database

Gets the current database.

list_databases

Lists databases in the current Catalog.

read_catalog_table

Reads a Catalog table into a DataFrame.

write_catalog_table

Writes a DataFrame to a Catalog table.

User-defined functions

The udf decorator registers a Python function as a scalar UDF for use in DataFrames. UDFs fall into four categories based on execution mode:

  • Synchronous row-based: A regular Python function that processes one row at a time.

  • Asynchronous row-based: Suitable for calling external services or executing I/O-intensive logic. This allows concurrent I/O operations across multiple rows, which improves throughput.

  • Synchronous vectorized: Receives and returns data in batches, reducing the overhead of row-by-row calls between Python and the Flink runtime. Ideal for purely computational logic.

  • Asynchronous vectorized: Combines the high throughput of batch processing with the concurrency of asynchronous I/O.


udf

  • API Name: udf.

    udf(
        func=None,
        *,
        return_dtype=None,
        deterministic=True,
        name=None,
        func_type=None,
        concurrency=None,
        batch_size=None
    )
  • Description: Registers a Python function as a scalar user-defined function (UDF) for use in DataFrames. Supports registering regular functions, async functions, subclasses of ScalarFunction or AsyncScalarFunction, and callable classes.

  • Parameters

    Parameter

    Type

    Required

    Description

    func

    Callable / Class

    No

    The Python function, ScalarFunction instance/subclass, or callable class to wrap. If omitted, this method returns the decorator itself.

    return_dtype

    DataType / str / type

    No

    The return type of the UDF. Can be a DataType instance (e.g., DataType.int64()), a Python type (e.g., int), or a SQL type string (e.g., 'BIGINT'). If omitted, the type is inferred from the function's return type hint.

    deterministic

    Boolean

    No

    Specifies whether the function is deterministic. Defaults to True.

    name

    String

    No

    The name of the UDF. If not specified, the function name is used.

    func_type

    String

    No

    The execution format. Options include "general", "pandas", and "arrow". If not specified, the format is detected from the function's parameter type hints.

    concurrency

    int

    No

    The parallelism of the UDF operator.

    batch_size

    int

    No

    The maximum number of elements per batch. Applies only to vectorized UDFs (pandas or arrow mode).

    num_gpus

    float

    No

    The number of GPUs to request for this UDF (e.g., 0.5 or 1). When set, this UDF runs in a standalone operator and is not fused with other UDFs (including other GPU UDFs).

    gpu_type

    String

    No

    The GPU type.

  • Return value

    A DataFrameUDFWrapper object for use in operations like with_column, with_columns, map, and map_batches.

Synchronous row-based UDFs

Use in with_column or with_columns

A scalar UDF takes one or more columns and returns a single column. Use Python type hints for automatic return type inference, or specify the type explicitly with return_dtype. You can also set the operator's parallelism with the concurrency parameter.

orders = pf.from_records(
    [
        (1001, 1, 99.9, "PAID"),
        (1002, 2, 35.5, "CREATED"),
        (1003, 1, 188.0, "PAID"),
        (1004, 3, 88.8, None),
    ],
    schema=["order_id", "user_id", "amount", "status"],
)

@udf
def normalize_status(status: str) -> str:
    if status is None:
        return "UNKNOWN"
    return status.strip().upper()

@udf(concurrency=32)
def order_tag(amount: float, status: str) -> str:
    """Takes multiple columns as input"""
    if status == "PAID" and amount is not None and amount >= 100:
        return "high_value_paid"
    return "normal"

# with_column adds a single column
orders_with_status = orders.with_column(
    "status_norm", normalize_status(col("status"))
)

# with_columns adds multiple columns at once
orders_with_flags = orders.with_columns(
    status_norm=normalize_status(col("status")),
    tag=order_tag(col("amount"), col("status")),
)

Use in map

The map function takes an entire row and returns a new row. The input row can be accessed by column name in the function. The return type can be explicitly declared with DataType.struct or automatically inferred from a TypedDict return type annotation.

Explicitly declare with return_dtype

def build_order_feature(row):
    amount = row["amount"] or 0.0
    return {
        "order_id": row["order_id"],
        "user_id": row["user_id"],
        "feature": f"{row['status']}:{'large' if amount >= 100 else 'normal'}",
    }

order_features = orders.map(
    build_order_feature,
    return_dtype=DataType.struct({
        "order_id": DataType.int64(),
        "user_id": DataType.int64(),
        "feature": DataType.string(),
    }),
)

Automatically infer type with TypedDict

from typing import TypedDict

class OrderFeature(TypedDict):
    order_id: int
    user_id: int
    feature: str

def build_order_feature_typed(row) -> OrderFeature:
    amount = row["amount"] or 0.0
    return {
        "order_id": row["order_id"],
        "user_id": row["user_id"],
        "feature": f"{row['status']}:{'large' if amount >= 100 else 'normal'}",
    }

order_features_typed = orders.map(build_order_feature_typed)

Synchronous vectorized UDFs

Use in with_column or with_columns

Vectorized UDFs receive and return data in batches, reducing the overhead of row-by-row calls between Python and the Flink runtime. They support both Pandas (pandas.Series) and Arrow (pyarrow.Array) formats. Use batch_size to control the batch size.

Pandas format

@udf(return_dtype=DataType.float64(), concurrency=32, batch_size=64)
def scale_amount_pandas(amounts: pd.Series) -> pd.Series:
    return amounts * 100.0

orders_scaled_pandas = orders.with_column(
    "amount_scaled", scale_amount_pandas(col("amount")),
)

Arrow format

import pyarrow as pa
import pyarrow.compute as pc

@udf(return_dtype=DataType.float64(), concurrency=32, batch_size=64)
def scale_amount_arrow(amounts: pa.Array) -> pa.Array:
    return pc.multiply(amounts, 100.0)

orders_scaled_arrow = orders.with_column(
    "amount_scaled", scale_amount_arrow(col("amount")),
)

Use in map_batches

map_batches performs vectorized processing on entire rows. When batch_format="pandas", the input and output are dict[str, pandas.Series]. When batch_format="arrow", the input and output are dict[str, pyarrow.Array].

Pandas format

def score_batch_pandas(batch: dict[str, pd.Series]) -> dict[str, pd.Series]:
    amount = batch["amount"].fillna(0.0)
    return {
        "order_id": batch["order_id"],
        "score": (amount / 100.0).clip(0.0, 1.0),
    }

order_scores_pandas = orders.map_batches(
    score_batch_pandas,
    batch_format="pandas",
    batch_size=1024,
    return_dtype=DataType.struct(
        {
            "order_id": DataType.int64(),
            "score": DataType.float64(),
        }
    ),
)

Arrow format

import pyarrow as pa
import pyarrow.compute as pc

def score_batch_arrow(batch: dict[str, pa.Array]) -> dict[str, pa.Array]:
    amount = pc.if_else(pc.is_null(batch["amount"]), 0.0, batch["amount"])
    raw_score = pc.divide(pc.cast(amount, pa.float64()), 100.0)
    score = pc.if_else(
        pc.less(raw_score, 0.0),
        0.0,
        pc.if_else(pc.greater(raw_score, 1.0), 1.0, raw_score),
    )
    return {
        "order_id": batch["order_id"],
        "score": score,
    }

order_scores_arrow = orders.map_batches(
    score_batch_arrow,
    batch_format="arrow",
    batch_size=1024,
    return_dtype=DataType.struct(
        {
            "order_id": DataType.int64(),
            "score": DataType.float64(),
        }
    ),
)

Asynchronous row-based UDFs

Asynchronous UDFs enable concurrent I/O across multiple rows, improving throughput for logic that calls external services. Use them with with_column or with_columns.

import asyncio

@udf(concurrency=32)
async def query_region(user_id: int) -> str:
    await asyncio.sleep(0.01)  # simulate async I/O
    return f"region_for_{user_id}"

orders_with_region = orders.with_column(
    "region", query_region(col("user_id")),
)

Asynchronous vectorized UDFs

Asynchronous vectorized UDFs combine batch processing throughput with asynchronous I/O concurrency. Use batch_size to control the batch size. Use them with with_column or with_columns.

import asyncio

@udf(return_dtype=DataType.string(), concurrency=32, batch_size=64)
async def batch_enrich(statuses: pd.Series) -> pd.Series:
    async def enrich_one(s):
        await asyncio.sleep(0.01)  # simulate async API call
        return f"enriched_{s}"
    tasks = [enrich_one(s) for s in statuses]
    results = await asyncio.gather(*tasks)
    return pd.Series(results)

orders_enriched = orders.with_column(
    "status_enriched", batch_enrich(col("status")),
)

User-defined table-valued functions

Custom table-valued function udtf

The udtf decorator registers a Python function as a table-valued function (UDTF). A UDTF can return zero or more rows for each input row.

  • Parameters

    Parameter

    Type

    Required

    Description

    func

    Callable / Class

    No

    The Python function to wrap. If omitted, the method returns the decorator itself.

    return_dtype

    DataType / str / type

    No

    The type of each output row. For multi-column output, use DataType.struct({...}) or TypedDict.

    deterministic

    Boolean

    No

    Whether the function is deterministic. Defaults to True.

    name

    String

    No

    The name of the UDTF. If not specified, the function name is used.

    concurrency

    int

    No

    The parallelism of the UDTF operator.

    num_gpus

    float

    No

    The number of GPUs to request for this UDTF (e.g., 0.5 or 1). When set, this UDTF runs in a standalone operator and is not fused with other UDFs (including other GPU UDFs).

    gpu_type

    String

    No

    The GPU type.

  • Return value

    A DataFrameUDTFWrapper object for use in flat_map or join_lateral.

Use in join_lateral

join_lateral appends UDTF results to the original input row. By default, input rows with no UDTF output are dropped. Set ignore_empty=False to keep input rows even when the UDTF produces no output.

from typing import Iterator, Tuple
from pyflink.dataframe import DataType

# Use type hint and .alias() to specify return types and column names
@udtf
def split_words(text: str) -> Iterator[Tuple[str, int]]:
    for word in text.split():
        yield word, len(word)

words_with_source = texts.join_lateral(
    split_words(col("text")).alias("word", "word_length"),
    ignore_empty=False,
)

# Or use return_dtype
@udtf(return_dtype=DataType.struct({
    "word": DataType.string(),
    "word_length": DataType.int32(),
}))
def split_words_with_length(text):
    for word in text.split():
        yield {"word": word, "word_length": len(word)}

words_with_detail = texts.join_lateral(
    split_words_with_length(col("text")),
)

Use in flat_map

flat_map calls the UDTF on each row and returns only the UDTF output columns, discarding the original input columns. You can pass a plain Python function to flat_map without using the udtf decorator.

from typing import Any, Dict, Iterator, TypedDict
from pyflink.dataframe import DataType

# Use type hint with TypedDict to specify return types and column names
class Word(TypedDict):
    word: str
    length: int

def split_row(row: Dict[str, Any]) -> Iterator[Word]:
    for word in row["text"].split():
        yield {"word": word, "length": len(word)}

words = texts.flat_map(split_row)

# Or use return_dtype
def split_row_with_dtype(row):
    for word in row["text"].split():
        yield {"word": word}

words_with_dtype = texts.flat_map(
    split_row_with_dtype,
    return_dtype=DataType.struct({"word": DataType.string()}),
)

AI / LLM functions

DataFrame exposes built-in AI functions through the df.llm accessor. For the full API reference, see AI/LLM.

Provider configuration

To use AI functions, you must first register a model provider.

API

Description

set_provider

Registers a model provider.

set_default_provider

Sets the default provider for multi-provider scenarios.

list_providers

Lists registered providers.

Supported provider types:

Provider

Use case

OpenAICompatProvider

All OpenAI-compatible APIs, including OpenAI, DeepSeek, and DashScope (Model Studio).

DashScopeProvider

Alibaba Cloud DashScope, which supports multimodal embedding.

TritonProvider

NVIDIA Triton Inference Server.

GenericProvider

A generic provider that lets you configure any backend with key-value pairs.

set_provider

  • API name: set_provider.

    set_provider(
        name_or_provider,
        provider=None,
        **options
    )
  • Description: Registers a global model provider configuration. This function supports three calling conventions: passing a provider instance, passing a name and a provider instance, or passing a name and keyword arguments.

  • Parameters

    Parameter

    Type

    Required

    Description

    name_or_provider

    Provider / String

    Yes

    A provider instance (automatically registered with its default name) or a custom name string.

    provider

    Provider

    No

    A provider instance. This parameter is used only when the first parameter is a name string.

    **options

    key=value

    No

    Configuration options, such as endpoint and api_key, for creating a GenericProvider. Use these options only when the first parameter is a name string and provider is omitted.

  • Returns

    None.

  • Example

    import pyflink.dataframe as pf
    
    # Option 1: pass a Provider instance directly
    pf.set_provider(pf.OpenAICompatProvider(
        endpoint="https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
        api_key="sk-..."
    ))
    
    # Option 2: custom name + Provider instance (register multiple)
    pf.set_provider("chat", pf.OpenAICompatProvider(
        endpoint="https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
        api_key="sk-..."
    ))
    pf.set_provider("embedding", pf.OpenAICompatProvider(
        endpoint="https://dashscope.aliyuncs.com/compatible-mode/v1/embeddings",
        api_key="sk-..."
    ))
    
    # Option 3: name + keyword arguments (creates GenericProvider)
    pf.set_provider("openai-compat",
        endpoint="https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
        api_key="sk-..."
    )

Generic call

  • API name: predict.

    DataFrame.llm.predict(
        *input_cols,
        provider=None,
        model=None,
        output_type=None,
        config=None
    )
    
  • Performs generic model inference. This function sends input columns to a model and adds the model's output to the DataFrame as new columns. You can customize the output schema.

  • Parameters

    Parameter

    Type

    Required

    Description

    *input_cols

    String

    Yes

    The names of the columns to use as model input. You can provide multiple columns.

    provider

    String

    No

    The provider name. If omitted, the default provider is used. If no provider is configured, the system treats model as a Catalog Model name.

    model

    String

    No

    The model name (e.g., "qwen-plus") or a Catalog Model name.

    output_type

    Dict

    No

    The schema of the output columns, in the format {column_name: type}. The type can be a SQL type string or a DataType object. The default value is {"output": "STRING"}.

    config

    Dict

    No

    Runtime configuration options.

  • Returns

    A DataFrame containing the original columns and the model output columns.

  • Example

    import pyflink.dataframe as pf
    
    pf.set_provider(pf.OpenAICompatProvider(
        endpoint="https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
        api_key="sk-..."
    ))
    
    df = pf.from_dict({"question": ["What is Flink?", "What is stream processing?"]})
    
    # default output column: output (STRING)
    df = df.llm.predict("question", provider="chat", model="qwen-plus")
    
    # custom output schema
    df = df.llm.predict("question", provider="chat", model="qwen-plus",
                        output_type={"answer": "STRING", "score": "DOUBLE"})
    

Text functions

Text classification

  • API name: ai_classify.

    DataFrame.llm.ai_classify(
        input_col,
        labels,
        *,
        provider=None,
        model=None,
        config=None
    )
  • Description: Classifies text into one of the specified labels.

  • Parameters

    Parameter

    Type

    Required

    Description

    input_col

    String / Expression

    Yes

    The input text column name or a column expression.

    labels

    List[String]

    Yes

    A list of classification labels, e.g., ["positive", "negative", "neutral"].

    provider

    String

    No

    The provider name.

    model

    String

    No

    The model name.

    config

    Dict

    No

    Runtime configuration options.

  • Returns

    A DataFrame with the category (STRING) and confidence (DOUBLE) columns added, which contain the classification result and the confidence score.

  • Example

    df = pf.from_dict({"review": ["Great product", "Terrible, do not buy", "It is okay"]})
    df = df.llm.ai_classify("review",
                            labels=["positive", "negative", "neutral"],
                            provider="chat", model="qwen-plus")

Sentiment analysis

  • API name: ai_sentiment.

    DataFrame.llm.ai_sentiment(
        input_col,
        *,
        provider=None,
        model=None,
        config=None
    )
  • Description: Performs sentiment analysis on the input text.

  • Parameters

    Parameter

    Type

    Required

    Description

    input_col

    String / Expression

    Yes

    The input text column name or a column expression.

    provider

    String

    No

    The provider name.

    model

    String

    No

    The model name.

    config

    Dict

    No

    Runtime configuration options.

  • Returns

    A DataFrame with the following columns added:

    • score (DOUBLE): The sentiment analysis score, ranging from -1.0 to 1.0.

    • label (STRING): One of "positive", "negative", or "neutral".

    • confidence (DOUBLE): The confidence score.

  • Example

    df = pf.from_dict({"comment": ["This feature is amazing!", "Broke after one month"]})
    df = df.llm.ai_sentiment("comment", provider="chat", model="qwen-plus")

Information extraction

  • API name: ai_extract.

    DataFrame.llm.ai_extract(
        input_col,
        schema,
        *,
        provider=None,
        model=None,
        config=None
    )
    
  • Description: Extracts structured information from text based on a given JSON Schema.

  • Parameters

    Parameter

    Type

    Required

    Description

    input_col

    String / Expression

    Yes

    The input text column name or a column expression.

    schema

    String

    Yes

    A JSON Schema string describing the fields to extract, e.g., '{"name":"STRING", "phone":"STRING"}'.

    provider

    String

    No

    The provider name.

    model

    String

    No

    The model name.

    config

    Dict

    No

    Runtime configuration options.

  • Returns

    A DataFrame with the extracted_json (STRING) column added, which contains the extracted structured information.

  • Example

    df = pf.from_dict({"text": ["John Smith, male, 28 years old, phone ***-****"]})
    schema = '{"name": "STRING", "age": "INTEGER", "phone": "STRING"}'
    df = df.llm.ai_extract("text", schema=schema,
                           provider="chat", model="qwen-plus")

Text translation

  • API name: ai_translate.

    DataFrame.llm.ai_translate(
        input_col,
        source_lang,
        target_lang,
        *,
        provider=None,
        model=None,
        config=None
    )
    
  • Description: Translates text from a source language to a target language.

  • Parameters

    Parameter

    Type

    Required

    Description

    input_col

    String / Expression

    Yes

    The input text column name or a column expression.

    source_lang

    String

    Yes

    The source language code, such as "zh", "en", or "auto" (for automatic detection). Supported values: auto, zh, en, ja, ko, fr, de, es, ru, ar, pt.

    target_lang

    String

    Yes

    The target language code. This value cannot be "auto".

    provider

    String

    No

    The provider name.

    model

    String

    No

    The model name.

    config

    Dict

    No

    Runtime configuration options.

  • Returns

    A DataFrame with the translated_text (STRING) and detected_language (STRING) columns added, which contain the translated text and the detected source language, respectively.

  • Example

    df = pf.from_dict({"text": ["Hello World", "How are you?"]})
    df = df.llm.ai_translate("text", source_lang="en", target_lang="zh",
                             provider="chat", model="qwen-plus")

Text summarization

  • API name: ai_summarize.

    DataFrame.llm.ai_summarize(
        input_col,
        max_length,
        *,
        provider=None,
        model=None,
        config=None
    )
    
  • Description: Summarizes text to a specified maximum length.

  • Parameters

    Parameter

    Type

    Required

    Description

    input_col

    String / Expression

    Yes

    The input text column name or a column expression.

    max_length

    int

    Yes

    The maximum number of characters in the summary. This value must be greater than 0.

    provider

    String

    No

    The provider name.

    model

    String

    No

    The model name.

    config

    Dict

    No

    Runtime configuration options.

  • Returns

    A DataFrame with the summary (STRING) column added, which contains the summary text.

  • Example

    df = pf.from_dict({"article": ["This is a long article with lots of content..."]})
    df = df.llm.ai_summarize("article", max_length=100,
                             provider="chat", model="qwen-plus")
    

Data masking

  • API name: ai_mask.

    DataFrame.llm.ai_mask(
        input_col,
        entities,
        *,
        provider=None,
        model=None,
        config=None
    )
    
  • Description: Masks sensitive information in text.

  • Parameters

    Parameter

    Type

    Required

    Description

    input_col

    String / Expression

    Yes

    The input text column name or a column expression.

    entities

    List[String]

    Yes

    A list of entity types to mask, e.g., ["name", "phone"].

    provider

    String

    No

    The provider name.

    model

    String

    No

    The model name.

    config

    Dict

    No

    Runtime configuration options.

  • Returns

    A DataFrame with the masked_text (STRING) and detected_entities (ARRAY<STRING>) columns added, which contain the masked text and the detected entities, respectively.

  • Example

    df = pf.from_dict({"text": ["Please contact John Smith at 555-0123"]})
    df = df.llm.ai_mask("text", entities=["name", "phone"],
                        provider="chat", model="qwen-plus")
    

Vector functions

Vector search

  • API name: vector_search.

    DataFrame.llm.vector_search(
        search_source,
        column_to_search,
        column_to_query,
        top_k,
        *,
        agg=False,
        output_columns=None,
        config=None,
        ignore_empty_and_null=False
    )
    
  • Description: Searches the vector search source for the most similar records using query vectors from the current DataFrame, and appends the results to the current DataFrame.

  • Parameters

    Parameter

    Type

    Required

    Description

    search_source

    DataFrame

    Yes

    The vector search source DataFrame, for example, a vector collection loaded via read_milvus.

    column_to_search

    String

    Yes

    The name of the vector column in the search source.

    column_to_query

    String / Expression

    Yes

    The query vector column name or column expression in the current DataFrame.

    top_k

    int

    Yes

    The number of most similar results to return per input record.

    agg

    Boolean

    No

    Whether to aggregate the top-K results into an array column. Defaults to False.

    output_columns

    String / List[String]

    No

    The output column names. When agg=False, provide names for each search-source output column and the score column. When agg=True, provide a single array column name.

    config

    Dict

    No

    Runtime vector search configuration.

    ignore_empty_and_null

    Boolean

    No

    Whether to drop input rows that have no search results. Defaults to False.

  • Return value

    A DataFrame containing the original columns plus the appended vector search result columns. Assume the search source search_source has N columns:

    • When agg=False, each input row corresponds to at most top_k output rows. N + 1 columns are appended: the N columns from search_source retain their original types, plus a DOUBLE-typed score column. If output_columns is specified, provide N + 1 column names in order.

    • When agg=True, each input row corresponds to one output row with an appended array column. Each array element is a row with N + 1 nested fields: the first N fields come from search_source and retain their original types, and the last field is a DOUBLE-typed score. If output_columns is specified, provide a single column name for the array column.

  • Example

    query_df = pf.from_dict({
        "query_id": [1],
        "query_embedding": [[0.1, 0.2, 0.3]],
    })
    
    documents = pf.read_milvus(
        endpoint="http://milvus.example.com",
        username="${secret_values.milvus_user}",
        password="${secret_values.milvus_password}",
        database_name="commerce",
        collection_name="support_docs",
        schema={
            "doc_id": DataType.int64(),
            "embedding": DataType.list(DataType.float32()),
            "title": DataType.string(),
        },
        columns=["doc_id", "embedding", "title"],
        search_metric="COSINE",
    )
    
    matched_docs = query_df.llm.vector_search(
        documents,
        column_to_search="embedding",
        column_to_query="query_embedding",
        top_k=3,
        output_columns=["doc_id", "doc_embedding", "doc_title", "score"],
    )

Text embedding

  • API name: ai_embed.

    DataFrame.llm.ai_embed(
        input_col,
        dimension=1024,
        *,
        provider=None,
        model=None,
        config=None
    )
    
  • Description: Generates a vector embedding for text.

  • Parameters

    Parameter

    Type

    Required

    Description

    input_col

    String / Expression

    Yes

    The input text column name or a column expression.

    dimension

    int

    No

    The dimension of the embedding vector. Defaults to 1024.

    provider

    String

    No

    The provider name.

    model

    String

    No

    The model name.

    config

    Dict

    No

    Runtime configuration options.

  • Returns

    A DataFrame with the embedding (ARRAY<FLOAT>) column added, which contains the generated vector embedding.

  • Example

    df = pf.from_dict({"text": ["stream processing with Flink", "real-time analytics"]})
    df = df.llm.ai_embed("text", dimension=1024,
                         provider="embedding", model="text-embedding-v4")
    

Environment and configuration

API

Description

Reference

set_table_environment

Sets the global TableEnvironment.

Config

get_table_environment

Gets the current TableEnvironment.

Config

get_or_create_table_environment

Gets or automatically creates a TableEnvironment.

Config

config.set(key, value)

Sets a DataFrame configuration item.

DataFrameConfig

config.get(key)

Gets a DataFrame configuration item.

DataFrameConfig

Modify runtime parameters

  • API name: DataFrameConfig.set.

    DataFrameConfig.set(
        key, value
    )
  • Function description: Sets runtime parameters for a DataFrame API job. You can configure Python job parameters and Table API parameters as shown in the example below. These parameters apply to the default TableEnvironment and override any parameters with the same name in the job's runtime parameter configuration.

  • Input parameters

    Parameter

    Type

    Required

    Description

    key

    String

    Yes

    The key of the configuration item.

    value

    String

    Yes

    The value of the configuration item.

  • Return value

    None.

  • Examples

    import pyflink.dataframe as pf
    
    pf.config.set("python.fn-execution.arrow.batch.size", "256")
    pf.config.set("table.exec.async-scalar.buffer-capacity", "10")
    pf.config.set("table.exec.async-lookup.timeout", "1 min")
    Note

    Configure parameters before defining the job logic to ensure they take effect as expected.