功能视图 API 参考

访问控制

功能是可管理的 Unity 目录对象。 对功能的访问权限由 CREATE FEATUREREAD FEATUREMANAGE Unity 目录权限控制。 有关完整说明,请参阅 Unity 目录特权参考。

  • CREATE FEATURE:在模式中创建特征所必需。 create_feature 并且 register_feature 在父模式中要求 CREATE FEATURE 。 遵循最低特权原则,在架构级别授予 CREATE FEATURE ;还可以在目录中授予它,以允许在该目录中的任何架构中创建功能。
  • READ FEATURE:读取特征元数据必须。 get_feature, create_training_set, , list_materialized_features 以及 需要 READ FEATURE 在该功能上。 该权限不允许访问源或实体化输出表中的特征数据。 要阅读这些数据用于培训或服务,你还必须在相关表格中。SELECT READ FEATURE 在模式或目录上授予适用于其包含的所有当前和未来功能。
  • MANAGE:管理功能生命周期和资助所必需。 删除带有 delete_feature的特征并实现具有 materialize_features的特征需要 MANAGE 在该特征上实现。 删除具有 delete_materialized_feature 实体化特征的行为不受 MANAGE:仅有实体化特征的创建者才能删除。

所有功能操作还需要 USE CATALOG 父目录和 USE SCHEMA 父架构。 MANAGE有关如何应用READ FEATURE具体化,请参阅“权限”。

功能视图 API

Feature 构造者和 register_feature()

建议的方法是在本地构造对象 Feature ,并将其 register_feature 保存到 Unity 目录。 通过此双重工作流,可以在注册功能之前试用功能(包括 create_training_set)。

Feature(
    source: DataSource,                                    # Required: DeltaTableSource, StreamSource, RequestSource, or FeatureViewSource
    function: Union[AggregationFunction, ColumnSelection, CustomUDF], # Required for all features
    entity: Optional[List[str]] = None,                    # Required for DeltaTableSource and StreamSource
    timeseries_column: Optional[str] = None,               # Required for DeltaTableSource and StreamSource
    name: Optional[str] = None,                            # Optional: Feature name (auto-generated if omitted)
    description: Optional[str] = None,                     # Optional: Feature description
)

FeatureEngineeringClient.register_feature()在Unity Catalog中注册本地构建的。Feature

FeatureEngineeringClient.register_feature(
    feature: Feature,       # Required: A Feature instance (not already registered)
    catalog_name: str,      # Required: UC catalog name
    schema_name: str,       # Required: UC schema name
) -> Feature
from databricks.feature_engineering.entities import Feature, DeltaTableSource, AggregationFunction, Sum, RollingWindow
from datetime import timedelta

# Step 1: Construct the feature locally
feature = Feature(
    source=DeltaTableSource(catalog_name="main", schema_name="store", table_name="transactions"),
    entity=["user_id"],
    timeseries_column="transaction_time",
    function=AggregationFunction(Sum(input="amount"), RollingWindow(window_duration=timedelta(days=7))),
)

# Step 2: Register in Unity Catalog
fe = FeatureEngineeringClient()
registered_feature = fe.register_feature(
    feature=feature,
    catalog_name="main",
    schema_name="store",
)

create_feature()

FeatureEngineeringClient.create_feature() 验证、构造并立即注册Unity Catalog中的功能,只需一步。 如果不需要先在本地试验该功能,请使用此功能。

FeatureEngineeringClient.create_feature(
    source: DataSource,                                    # Required: DeltaTableSource, StreamSource, RequestSource, or FeatureViewSource
    function: Union[AggregationFunction, ColumnSelection, CustomUDF], # Required for all features
    catalog_name: str,                                     # Required: The catalog name for the feature
    schema_name: str,                                      # Required: The schema name for the feature
    entity: Optional[List[str]] = None,                    # Required for DeltaTableSource and StreamSource
    timeseries_column: Optional[str] = None,               # Required for DeltaTableSource and StreamSource
    name: Optional[str] = None,                            # Optional: Feature name (auto-generated if omitted)
    description: Optional[str] = None,                     # Optional: Feature description
) -> Feature

参数:

  • source:特征计算中使用的数据源(DeltaTableSource, StreamSource, RequestSource, , 或 FeatureViewSource)。
  • function:一个 AggregationFunction 将算符和时间窗口捆绑在一起的函数,用于 ColumnSelection("column_name") 通透特征或 CustomUDF 逐行变换。 兼容源类型请参见 支持函数 。
  • catalog_name:Unity 目录中该功能的名称。
  • schema_name:Unity 目录中该功能的模式名称。
  • entity: 定义聚合或查找键(主键)的列名列表。 这是 DeltaTableSource 和 StreamSource 所必需的。 例如, ["user_id"] 聚合或查找每个用户。 省略 RequestSource 和 FeatureViewSource。
  • timeseries_column:用于时间窗口聚合或最新值选择的时间戳列。 这是 DeltaTableSource 和 StreamSource 所必需的。 省略 RequestSource 和 FeatureViewSource。
  • name:可选功能名称。 如果省略,则从输入列、函数和窗口(例如, amount_avg_rolling_7d)自动生成。
  • description:功能描述的可选内容。

返回: 一个经过验证的功能实例

提高: 如果任何验证失败,则为ValueError。

delete_feature()

通过 Unity 目录的完全限定名称删除某个功能。

FeatureEngineeringClient.delete_feature(
    full_name: str,  # Required: '<catalog>.<schema>.<feature_name>'
) -> None
fe.delete_feature(full_name="main.store.amount_sum_rolling_7d")

在删除功能之前,请删除或更新引用该功能的任何模型或功能规格。 只要一个功能仍然具备实体化功能,就不能被删除。 先删除实体化的特征,然后再删除该特征。 请参阅 如何删除具体化功能。

自动生成的名称

省略时 name ,将自动生成名称。 生成的名称遵循模式: {column}_{function}_{window}. 例如:

  • price_avg_rolling_1h (1小时平均价格)
  • transaction_count_rolling_30d_1d (交易计时30天,事件时间戳延迟1天)

支持的功能

聚合函数

注释

聚合函数与时间窗口一起包装 AggregationFunction ,如 时间窗口中所述。 每个函数采用一个 input 参数来指定要聚合的源列。

功能 Description 示例用例
Sum(input="column") 数值总和 每用户每日应用使用情况(以分钟为单位)
Avg(input="column") 值的平均值 平均交易金额
Count(input="column") 记录数 每个用户的登录次数
Min(input="column") 最小值 可穿戴设备记录的最低心率
Max(input="column") 最大值 每个会话的最大事务量
StddevPop(input="column") 总体标准偏差 所有客户的每日交易金额可变性
StddevSamp(input="column") 样本标准偏差 广告市场点击率的可变性
VarPop(input="column") 总体方差 工厂中 IoT 设备的传感器读数分布
VarSamp(input="column") 样本方差 电影收视率在采样组的分布
ApproxCountDistinct(input="column", relativeSD=0.05) 近似唯一计数 购买项目的去重计数
ApproxPercentile(input="column", percentile=0.95, accuracy=100) 近似百分位数 p95 响应延迟
First(input="column") 第一个值 第一个登录时间戳
Last(input="column") 最后一个值 最新购买金额
FirstN(input="column", n=3) 第一个 n 数组的值 前三个在会话中展示的产品
LastN(input="column", n=3) 最后 n 的数值作为数组 最近的三个支持案件状态
FirstDistinct(input="column", n=3) 第一个 n 不同的数组数值 前三个不同的产品类别
LastDistinct(input="column", n=3) 最后 n 一个不同的数值作为数组 最近出现的三个不同商人类别

注释

First、Last、LastDistinctFirstDistinctFirstNLastN接受支持的标量值和ARRAY、、 MAP,STRUCT以及包含嵌套组合的值。 它们默认包含空值。 若要跳过 null,请添加一个 filter_condition 显式排除为 null 的输入列。

FirstN, LastN, FirstDistinct, ,并 LastDistinct 使用特征 timeseries_column 排序输入行,返回包含最多 数 n 值的数组。 参数 n 必须是正整数。 FirstN 并从 FirstDistinct 最早到最新选择数值。 LastN 并 LastDistinct 从最晚到最早选择值,然后按时间戳顺序返回所选值。 FirstDistinct 并在 LastDistinct 选择该方向的值时删除重复值。

例如,如果一个实体的源行按 为 event_time["A", "A", "B", "C", "B", "B"]排序,以下函数返回:

功能 Result
FirstN(input="event_type", n=3) ["A", "A", "B"]
LastN(input="event_type", n=3) ["C", "B", "B"]
FirstDistinct(input="event_type", n=3) ["A", "B", "C"]
LastDistinct(input="event_type", n=3) ["A", "C", "B"]

FirstN LastN, , , FirstDistinct, 并LastDistinct要求databricks-feature-engineering版本为0.17.0或更高版本。

CustomUDF

CustomUDF对每一行应用注册的 Unity Catalog Python 用户自定义函数(UDF)。 用它来转换请求输入或组合功能值。 它不聚合行数或定义时间窗口。

CustomUDF(
    function_name="main.ecommerce.log_amount_udf",
    input_bindings={"amount": "transaction_amount"},
)

input_bindings 将每个UDF参数名称映射到一个输入。 对于 RequestSource,输入是源列名称。 对于 FeatureViewSource,它是上游特征引用。 绑定所有UDF参数,包括带有默认值的参数。 输入类型必须与UDF参数类型完全匹配,不能隐含数字铸造。 你可以使用标量类型和复杂(ARRAY、 MAP和 STRUCT)输入和返回类型,包括嵌套组合。

来源 Behavior
RequestSource 从训练数据帧或推理请求中转换列。
FeatureViewSource 将上游特征值合并。 参见 FeatureViewSource。

Delta支持 CustomUDF 的功能不能在线实现或提供。 要转换表支持特征值用于训练和服务,定义一个Delta支持的聚合或列选择特征,并通过 引用。FeatureViewSource

CustomUDF 不支持 StreamSource。 要转换流功能输出,请通过 引用该功能 FeatureViewSource。

CustomUDF RequestSource需要databricks-feature-engineering版本 0.17.0 或更高版本。

要使用 , CustomUDF你需要对 UDF 拥有 EXECUTE 权限,对其父目录有 USE CATALOG 权限,并且 USE SCHEMA 对父模式有权限。

以下示例使用 NumPy 计算 log(1 + amount),减少大额交易金额的规模。 在无服务器计算上运行,并启用 自定义UDF依赖 。 main.ecommerce这个模式必须存在。

spark.sql("""
CREATE OR REPLACE FUNCTION main.ecommerce.log_amount_udf(amount DOUBLE)
RETURNS DOUBLE
LANGUAGE PYTHON
ENVIRONMENT (
  dependencies = '["numpy==1.26.4"]',
  environment_version = '6'
)
AS $$
import numpy as np

if amount is None or not np.isfinite(amount) or amount < 0:
    return None
return float(np.log1p(amount))
$$
""")

注册一个将请求列 transaction_amount 绑定到 UDF 参数 amount的功能:

from databricks.feature_engineering import FeatureEngineeringClient
from databricks.feature_engineering.entities import (
    CustomUDF, FieldDefinition, RequestSource, ScalarDataType,
)

fe = FeatureEngineeringClient()

log_transaction_amount = fe.create_feature(
    source=RequestSource(
        schema=[
            FieldDefinition(name="transaction_amount", data_type=ScalarDataType.DOUBLE),
        ]
    ),
    function=CustomUDF(
        function_name="main.ecommerce.log_amount_udf",
        input_bindings={"amount": "transaction_amount"},
    ),
    catalog_name="main",
    schema_name="ecommerce",
    name="log_transaction_amount",
)

UDF ENVIRONMENT 配置依赖以实现离线计算。 对于在线服务,也请将包裹申报为 create_feature_spec(extra_pip_requirements=...) 或 log_model(extra_pip_requirements=...)。 它们不会自动从UDF复制。 参见 特征服务依赖 关系和 模型依赖关系。

CustomUDF 特征无法被具象化。 请求支持和功能支持的UDF在培训和服务期间按需运行。 依赖链中的每个UDF都会增加计算量,因此保持函数和链较小。 UDF必须处理缺失的输入,这些输入可以是离线的,也可以NaN是None在线的。

关于处理缺失值的指导,请参见 《如何处理缺失特征值》。

ColumnSelection (穿透声)

ColumnSelection 从源中选择单一列,无需应用任何聚合。 它直接包装在参数中 function (不在内部 AggregationFunction)。 返回类型(包括嵌套 ARRAY、 MAP和 STRUCT 类型)是在创建特征时从源模式推断出来的。 创建功能后不支持更改源列的类型。

功能 Description 示例用例
ColumnSelection("col") 列的最新值(无聚合) 最新的供应商类别,请求字段的传递

ColumnSelection 支持以下数据来源:

  • DeltaTableSource: 通过点点连接返回每个实体键的最新值(无回溯窗口聚合)。
  • SdpSource返回管道输出表中每个实体键的最新值,与 DeltaTableSource相同。
  • StreamSource: 返回流中每个实体键的最新值(无回溯窗口聚合)。
  • RequestSource: 通过推理时提供的值(或训练时从标记数据帧中提取)。

对于 DeltaTableSource, ColumnSelection 支持 filter_condition 和 transformation_sql,在最新值选择前应用,这与聚合特征相同。

from databricks.feature_engineering.entities import (
    ColumnSelection, DeltaTableSource, Feature, FieldDefinition,
    RequestSource, ScalarDataType,
)

delta_source = DeltaTableSource(
    catalog_name="main", schema_name="feature_store", table_name="transactions",
)

request_source = RequestSource(
    schema=[
        FieldDefinition(name="session_duration", data_type=ScalarDataType.DOUBLE),
    ]
)

# ColumnSelection from a Delta table
latest_amount = Feature(
    source=delta_source,
    function=ColumnSelection("amount"),
    entity=["user_id"],
    timeseries_column="transaction_time",
    name="latest_transaction_amount",
)

# ColumnSelection from a RequestSource
session_feature = Feature(
    source=request_source,
    function=ColumnSelection("session_duration"),
    name="session_duration",
)

示例:聚合和列选择功能

以下示例显示了在同一数据源上定义的功能。

from databricks.feature_engineering.entities import (
    AggregationFunction, Feature, Sum, Avg, ApproxCountDistinct,
    ColumnSelection, RollingWindow,
)
from datetime import timedelta

window = RollingWindow(window_duration=timedelta(days=7))

sum_feature = Feature(
    source=source,
    entity=["user_id"],
    timeseries_column="event_time",
    function=AggregationFunction(Sum(input="amount"), window),
)

avg_feature = Feature(
    source=source,
    entity=["user_id"],
    timeseries_column="event_time",
    function=AggregationFunction(Avg(input="amount"), window),
)

distinct_count = Feature(
    source=source,
    entity=["user_id"],
    timeseries_column="event_time",
    function=AggregationFunction(ApproxCountDistinct(input="product_id", relativeSD=0.01), window),
)

# Column selection (no aggregation, no time window)
latest_amount = Feature(
    source=source,
    function=ColumnSelection("amount"),
    entity=["user_id"],
    timeseries_column="event_time",
    name="latest_amount",
)

具有筛选条件的功能

该 filter_condition 参数允许你在计算聚合或选择最新列值 之前 ,从源表中筛选行。 此函数充当在对数据进行分组和聚合之前应用的 SQL WHERE 子句。

注释

对于聚合功能,会 filter_condition 在聚合前过滤行,就像 SQL WHERE 子句在聚合之前 GROUP BY应用。 它不会更改始终在 entity 功能定义上定义的粒度。

使用包含特征计算所需的超集数据的大型源表时,筛选器非常有用,并最大程度地减少在这些表之上创建单独的视图的需求。

from databricks.feature_engineering.entities import AggregationFunction, Sum, Count, RollingWindow, DeltaTableSource
from datetime import timedelta

# Source with filter applied at the source level
high_value_transactions = DeltaTableSource(
    catalog_name="main",
    schema_name="ecommerce",
    table_name="transactions",
    filter_condition="amount > 100",  # Only transactions over $100
)

high_value_sales = Feature(
    source=high_value_transactions,
    entity=["user_id"],
    timeseries_column="transaction_time",
    function=AggregationFunction(Sum(input="amount"), RollingWindow(window_duration=timedelta(days=30))),
)

# Multiple conditions
completed_orders_source = DeltaTableSource(
    catalog_name="main",
    schema_name="ecommerce",
    table_name="orders",
    filter_condition="status = 'completed' AND payment_method = 'credit_card'",
)

completed_orders = Feature(
    source=completed_orders_source,
    entity=["user_id"],
    timeseries_column="order_time",
    function=AggregationFunction(Count(input="order_id"), RollingWindow(window_duration=timedelta(days=7))),
)

# Filter on a StreamSource
from databricks.feature_engineering.entities import StreamSource

purchase_stream = StreamSource(
    full_name="main.ecommerce.transactions_stream",
    filter_condition="value.event_type = 'purchase'",
)

purchase_total = Feature(
    source=purchase_stream,
    entity=["value.user_id"],
    timeseries_column="value.event_time",
    function=AggregationFunction(Sum(input="value.amount"), RollingWindow(window_duration=timedelta(hours=1))),
)

数据来源

DeltaTableSource

DeltaTableSource是一个短暂的 Python 对象,用于定义如何从源表计算特征。 它不会创建新表。 它指定用于读取数据和聚合功能的配置。

DeltaTableSource(
    catalog_name: str,                              # Required: Catalog name
    schema_name: str,                               # Required: Schema name
    table_name: str,                                # Required: Table name
    filter_condition: Optional[str] = None,         # Optional: SQL WHERE clause to filter source data
    transformation_sql: Optional[str] = None,       # Optional: SQL SELECT expression for column transformations
    dataframe_schema: Optional[str] = None,         # Required if transformation_sql is set: schema of the resulting DataFrame
    lateness: Optional[SourceLateness] = None,       # Optional: Expected source settling time
)

参数:

  • catalog_name, schema_name, : table_name在 Unity 目录中识别源 Delta 表。
  • filter_condition:在聚合或列选择前应用的SQL WHERE 子句。 示例:"status = 'completed'"。
  • transformation_sql: 一个应用到源表上的SQL SELECT 表达式。 利用该方法重命名列、铸造类型,或在聚合或列选择前计算派生列。 如果省略,则选择所有列(*)。 示例:"user_id, CAST(amount AS DOUBLE) AS amount, event_time"。
  • dataframe_schema:经过转换后生成的数据框架模式,采用Spark StructType JSON格式(来自 df.schema.json())。 如果 transformation_sql 提供 ,则为 必需。 这会告知系统转换产生的列名和类型。
  • lateness:描述 SourceLateness 源在事件时间内通常完成所需的时间的对象。 如果省略,该源立即被视为完整。

当同时 filter_condition 设置和 transformation_sql 设置时,生成的查询为: SELECT {transformation_sql} FROM {table} WHERE {filter_condition}。

SourceLateness.settling_delay 是训练期间推荐的模拟ETL持续延迟的方法,这会影响在线物质化。 Azure Databricks会将合格的培训评估时间向后推移,使得培训示例不会使用仍在在线传输的数据。 在实现过程中,Azure Databricks 会等待相同时间才发布已完成的窗口,并在中间期间服务最后一个已完成的窗口。

例如,假设一个每日ETL任务在当地时区午夜后8小时完成,而午夜对应于协调世界时07:00。 使用8小时的稳定延迟和7小时的窗口偏移:

from datetime import timedelta
from databricks.feature_engineering.entities import (
    DeltaTableSource,
    SourceLateness,
    TumblingWindow,
)

source = DeltaTableSource(
    catalog_name="main",
    schema_name="analytics",
    table_name="events",
    lateness=SourceLateness(settling_delay=timedelta(hours=8)),
)

window = TumblingWindow(
    window_duration=timedelta(days=1),
    offset=timedelta(hours=7),
)

注释

必须 timeseries_column 类型为 TimestampType 或 TimestampNTZType。 DateType 不支持时间序列;将列铸造为 TimestampType 第一(例如,为 transformation_sql)。

示例:用于 transformation_sql 列变换

source = DeltaTableSource(
    catalog_name="main",
    schema_name="analytics",
    table_name="raw_events",
    transformation_sql="user_id, CAST(price_cents AS DOUBLE) / 100 AS price, event_time",
    filter_condition="event_type = 'purchase'",
    dataframe_schema=spark.sql(
        "SELECT user_id, CAST(price_cents AS DOUBLE) / 100 AS price, event_time FROM main.analytics.raw_events LIMIT 0"
    ).schema.json(),
)

示例:从 PySpark 数据帧导出 transformation_sql 和 dataframe_schema 导出

可以将转换编写为 PySpark 查询,然后从生成的 DataFrame 中提取架构:

df = spark.sql(f"""
  SELECT user_id, CAST(amount AS DOUBLE) / 100 AS amount_dollars, event_time
  FROM main.analytics.events
  WHERE event_date >= date_sub(current_date(), 7)
  LIMIT 0
""")

# Use df.schema.json() as the dataframe_schema
source = DeltaTableSource(
    catalog_name="main",
    schema_name="analytics",
    table_name="events",
    transformation_sql="user_id, CAST(amount AS DOUBLE) / 100 AS amount_dollars, event_time",
    filter_condition="event_date >= date_sub(current_date(), 7)",
    dataframe_schema=df.schema.json(),
)

支持表达式transformation_sql

同样的规则也适用于 transformation_sql 和 DeltaTableSourceStreamSource。

transformation_sql 支持任意行表达式;对每一行独立计算的操作。 它们不会改变行数或与源的一一对应关系。 按行的表达式包括列重命名、铸造、算术运算等。

不支持改变形状或行数的操作,如聚合SUM()COUNT(),如 或 。 请 AggregationFunction 改用功能定义。

DeltaTableSource.from_sql()

为方便起见,可以从 SQL 查询创建。DeltaTableSource 该方法分析查询以自动提取表名, transformation_sql以及 filter_condition。

DeltaTableSource.from_sql(
    sql: str,                           # Required: SQL SELECT query
    spark: SparkSession,                # Required: active SparkSession (for schema inference)
) -> DeltaTableSource

仅支持简单的 SELECT ... FROM ... [WHERE ...] 查询。 复杂的 SQL(JOIN、子查询、CTE、UNION)被拒绝。 对于复杂查询, DeltaTableSource 请直接使用 transformation_sql 和 filter_condition.

from databricks.feature_engineering.entities import (
    AggregationFunction,
    DeltaTableSource,
    Feature,
    Sum,
    TumblingWindow,
)

source = DeltaTableSource.from_sql(
    spark=spark,
    sql=f"SELECT customer_id, event_ts, amount * 2 AS doubled_amount, amount FROM {CATALOG}.{SCHEMA}.{TABLE}",
)

feature = Feature(
    source=source,
    function=AggregationFunction(Sum(input="doubled_amount"), time_window=TumblingWindow(window_duration=timedelta(days=7))),
    entity=["customer_id"], timeseries_column="event_ts",
)

循环访问 to_dataframe()

用于 source.to_dataframe() 预览将用于特征计算的数据。 这对于循环访问 filter_condition 以及 transformation_sql 直到生成预期结果很有用。

source = DeltaTableSource(
    catalog_name="main",
    schema_name="analytics",
    table_name="events",
    filter_condition="event_type = 'purchase'",
)

# Preview the filtered source data
source.to_dataframe().display()

了解实体

实体列定义特征的聚合级别。 它们在定义上指定,而不是在定义中FeatureDeltaTableSource指定。 实体确定:

  • 数据分组方式:特征按独特的实体值组合进行聚合(类似于 GROUP BY SQL中的情况)
  • 主键结构:每个唯一实体组合对应一行计算出的特征

示例:客户级功能

以下代码聚合客户级别的功能(每个客户一行):

from databricks.feature_engineering.entities import DeltaTableSource

source = DeltaTableSource(
    catalog_name="main",
    schema_name="analytics",
    table_name="user_events",
)

Feature(
    source=source,
    entity=["user_id"],                # Features aggregated per user
    timeseries_column="event_time",    # Timestamp for time windows
    function=AggregationFunction(Sum(input="amount"), RollingWindow(window_duration=timedelta(days=7))),
)

示例:客户-门店级功能

若要在更详细的级别聚合特征(每个客户存储组合一行),请使用多个实体列:

source = DeltaTableSource(
    catalog_name="main",
    schema_name="retail",
    table_name="transactions",
)

Feature(
    source=source,
    entity=["user_id", "store_id"],  # Features aggregated per user-store pair
    timeseries_column="transaction_time",
    function=AggregationFunction(Sum(input="amount"), RollingWindow(window_duration=timedelta(days=7))),
)

如果需要不同级别的聚合功能(例如客户级别和客户存储级别),请在功能定义中使用不同的 entity 值。 可以在具有不同实体配置的功能之间共享相同 DeltaTableSource 。

StreamSource

StreamSource 提到一条 溪流。 流包含流源的连接、身份验证、架构和引入配置。 对于 Kafka,功能定义中的列引用必须带有 value. 前缀或 key. 指示要读取的消息的哪个部分。

StreamSource(
    full_name: str,                       # Required: Three-part Stream name (catalog.schema.stream)
    filter_condition: Optional[str] = None,      # Optional: SQL WHERE clause applied before aggregation
    transformation_sql: Optional[str] = None,    # Optional: SQL SELECT expression for column transformations
    dataframe_schema: Optional[str] = None,      # Required if transformation_sql is set: schema of the resulting DataFrame
    lateness: Optional[SourceLateness] = None,    # Optional: Expected source settling time
)

参数:

  • full_name:流的完整三部分名称(例如, "my_catalog.my_schema.my_stream")。
  • filter_condition (可选):在聚合前应用于流数据的SQL WHERE 子句,使用带点前缀的列引用(例如, "value.event_type = 'purchase'")。
  • transformation_sql(可选):在聚合或列选择前应用的SQLSELECT表达式,使用带点前缀的引用和keyvalue结构。 支持与 DeltaTableSource相同的行表达式。 如果省略,源将使用所有列(*)。
  • dataframe_schema: 投影输出的 Spark StructType JSON 模式。 如果你设置 transformation_sql了,必须。
  • lateness:描述 SourceLateness 流在事件时间内通常完成所需的时间的对象。 请参阅 SourceLateness.settling_delay。
from databricks.feature_engineering.entities import StreamSource

stream_source = StreamSource(
    full_name="my_catalog.my_schema.my_stream",
    filter_condition="value.event_type = 'purchase'",
)

通过将投影与流的摄取表对比,从而导出keydataframe_schemavalue和结构体。

transformation_sql = (
    "value.amount * value.conversion_rate AS converted_amount, "
    "struct(value.user_id AS user_id, value.event_time AS time) AS event"
)

ingestion_table = "my_catalog.my_schema.events_ingestion"
dataframe_schema = spark.sql(
    f"SELECT {transformation_sql} FROM {ingestion_table} LIMIT 0"
).schema.json()

stream_source = StreamSource(
    full_name="my_catalog.my_schema.my_stream",
    transformation_sql=transformation_sql,
    dataframe_schema=dataframe_schema,
)

SdpSource

SdpSource 在触发的Lakeflow管道的输出表上定义特征。 功能库在每次物质化和回填前运行流水线,然后像读取 DeltaTableSource。 关于端到端工作流程,请参见 “使用湖流管道作为功能源”。

SdpSource(
    pipeline_id: str,                            # Required: ID of the pipeline that produces the output table
    output_table: str,                           # Required: Three-part name of the pipeline output table to read
    input_tables: Optional[List[str]] = None,    # Optional: Three-part names of the tables the pipeline reads from
    filter_condition: Optional[str] = None,      # Optional: SQL WHERE clause to filter the output table
    transformation_sql: Optional[str] = None,    # Optional: SQL SELECT expression for column transformations
    dataframe_schema: Optional[str] = None,      # Required if transformation_sql is set: schema of the resulting DataFrame
)

参数:

  • pipeline_id:已触发管道的ID。 管道不必已经运行完毕。 你需要CAN RUN、CAN MANAGE,或IS拥有者权限。 连续管道被拒绝。
  • output_table:要读取的流水线输出表的三部分名称(catalog.schema.table)。 表格在流水线首次运行之前不需要存在。 如果有,它必须是流水线的输出,并且你需要 SELECT 在它上。
  • input_tables:管道读取的表格的三部分名称。 需要通过 TableTrigger实现 ,当这些表更新时,该运行开始。 ColumnSelection 特征在表格触发器上显现,因此它们需要 input_tables。 你可以列出最多25个表,且不能重复,每个表在创建功能时都必须存在。 只有当每个被监视表都启用了文件事件时,A TableTrigger 才会监控超过 10 个表。
  • filter_condition, transformation_sql, : dataframe_schema以与在 上相同的 DeltaTableSource方式应用到输出表。 dataframe_schema 如果你设置 transformation_sql,则是必需的。

SdpSource 具备支持 ColumnSelection 和 聚合功能。 他们不支持 CustomUDF。

创建功能后,其源端会报告只 pipeline_state读:

  • PENDING:流水线尚未运行,因此输出表不存在。
  • RESOLVED:输出表存在,功能列对其进行了验证。
  • ERROR:流水线运行或输出表验证失败。

以下示例定义了 :SdpSource

from databricks.feature_engineering.entities import SdpSource

source = SdpSource(
    pipeline_id="1234abcd-5678-90ef-1234-567890abcdef",
    output_table="main.features.tutor_review_stats",
    input_tables=["main.raw.reviews", "main.raw.tutors"],
)

refresh_sdp_source()

refresh_sdp_source 运行这些功能背后的管道。 它会为每个流水线启动一个更新,或者附加到已经运行中的更新。

FeatureEngineeringClient.refresh_sdp_source(
    *,                                  # Arguments are keyword-only
    features: List[Feature],            # Features with an SdpSource
    wait: bool = True,                  # Wait for the updates to finish
) -> Dict[str, str]                     # Pipeline ID to update ID

使用 wait=True,调用等待每次更新完成且无超时,然后解决功能。 pipeline_state 如果更新失败、被取消,或者某个功能保持未解决,它就会 ValueError 升高。 当 wait=False,调用在更新开始时立即返回。

要在训练前运行某个功能的流水线,请运行以下操作:

fe.refresh_sdp_source(features=[fe.get_feature(full_name="main.features.tutor_avg_score_7d")], wait=True)

RequestSource

RequestSource 定义了一个在请求有效载荷推理时提供的数据模式,而非从预设的表中查找。 在训练期间,这些列是从传递给的带标签的数据帧中提取的 create_training_set。 在模型服务期间,调用方必须在 HTTP 请求有效负载中包含它们。

RequestSource 可以与 CustomUDF 或 ColumnSelection 功能视图一起使用。 它不支持聚合函数或时间窗口。

定义架构

将架构定义为对象列表 FieldDefinition ,每个对象都指定列名和 ScalarDataType:

from databricks.feature_engineering.entities import (
    FieldDefinition, RequestSource, ScalarDataType,
)

request_source = RequestSource(
    schema=[
        FieldDefinition(name="transaction_amount", data_type=ScalarDataType.DOUBLE),
        FieldDefinition(name="vendor_id", data_type=ScalarDataType.STRING),
        FieldDefinition(name="transaction_id", data_type=ScalarDataType.STRING),
        FieldDefinition(name="transaction_time", data_type=ScalarDataType.DATE),
    ]
)

对于包含数组、映射或结构的模式, dataframe_schema 传递(Spark StructType JSON from df.schema.json())代替 schema,或从数据帧推导出模式,满足 RequestSource.from_dataframe:

from databricks.feature_engineering.entities import RequestSource

request_source = RequestSource.from_dataframe(dataframe=labeled_df.select("cart_items", "device_info"))

支持的数据类型

RequestSource支持定义在 ScalarDataType的标量类型:INTEGER, FLOAT, LONGBOOLEANDATESTRINGBINARYDOUBLETIMESTAMPSHORT。 当你用或 定义模式dataframe_schema时,它还支持 ARRAY, MAP, 以及STRUCT由这些类型构建的列。from_dataframe MAP 密钥必须是 STRING。

请求数据如何冻结

背景 Behavior
培训(create_training_set) 列是从标记的数据帧中提取的。 类型将根据已声明的架构进行验证。 不匹配引发错误(无隐式强制转换)。
服务 (模型端点) 从 HTTP 请求或 dataframe_records HTTP 请求中拉取dataframe_split列。 JSON 值被强制转换为声明的类型(例如 JSON 数字→ DOUBLE)。

模型签名

使用包含log_model特征的训练集记录RequestSource模型时,这些RequestSource列将作为所需的输入添加到 MLflow 模型签名中。 这意味着服务终结点的 API 架构反映了调用方在推理时必须提供的字段。

FeatureViewSource

FeatureViewSource使用其他特征视图的输出作为输入。CustomUDF 特征链化会生成有向无环图(DAG)。 例如,利润率特征可以合并收入和成本总量,另一个特征可以转换利润率。

使用databricks-feature-engineering版本 0.18.0 或更高版本。FeatureViewSource

传递一个对象列表 Feature 到 features,而不是功能名字符串。 检索注册特征。get_feature 在 input_bindings中,使用每个注册特征的 full_name。 对于本地未注册的功能,就用它 name 。

以下示例假设两个注册特征和 revenue_sum_7dcost_sum_7d,它们 DOUBLE 返回的值由 和 customer_id 用于 event_time 时间点计算:

from databricks.feature_engineering import FeatureEngineeringClient
from databricks.feature_engineering.entities import CustomUDF, FeatureViewSource

fe = FeatureEngineeringClient()
revenue = fe.get_feature(full_name="main.ecommerce.revenue_sum_7d")
cost = fe.get_feature(full_name="main.ecommerce.cost_sum_7d")

spark.sql("""
CREATE OR REPLACE FUNCTION main.ecommerce.margin_udf(revenue DOUBLE, cost DOUBLE)
RETURNS DOUBLE
LANGUAGE PYTHON
AS $$
import math

if revenue is None or cost is None:
    return None
if not math.isfinite(revenue) or not math.isfinite(cost) or revenue <= 0:
    return None
return (revenue - cost) / revenue
$$
""")

margin = fe.create_feature(
    source=FeatureViewSource(features=[revenue, cost]),
    function=CustomUDF(
        function_name="main.ecommerce.margin_udf",
        input_bindings={"revenue": revenue.full_name, "cost": cost.full_name},
    ),
    catalog_name="main",
    schema_name="ecommerce",
    name="margin",
)

存在以下限制:

  • 仅 CustomUDF 支持函数。 上游特征可以是聚合、列选择或其他 CustomUDF 特征。
  • 省略 entity , timeseries_column 关于衍生特征。 每个上游特征保留自己的实体、时间戳和窗口定义。
  • 一个特征只有一个来源。 要将请求值与表支持的功能结合,定义一个RequestSource功能并通过 来引用。FeatureViewSource
  • 每个声明的上游特征都必须在 中使用 input_bindings。 不允许骑自行车。
  • 在注册衍生特征之前,先注册上游特征。 局部未注册图可用于 create_training_set 实验。
  • 对于训练或服务,你需要对派生特征及其传递上游特征拥有 READ FEATURE OR MANAGE 权限。 在图中使用不同的特征名称进行注册和服务,甚至跨目录或模式。
  • 一个特征最多可引用20个直接上游特征。 注册图支持沿依赖路径最多五个特征深度,包括基础特征。
  • 训练查询的 每次查询最多可调用五次 Unity Catalog UDF 调用,且在整个依赖图中计数。 要超越它,请使用运行 Databricks Runtime 18.1 或更高版本的经典计算。 在无服务器计算以及专业和无服务器SQL仓库中,每个UDF定义都设置为environment_version6或更高。
  • FeatureViewSource特征不能用 实现或评估。compute_features 用 create_training_set 来离线评估。 对于在线服务,可以实现支持的表支持的上游功能。

关于依赖评估和输出选择,请参见 “使用FeatureViewSource功能训练”。 关于部署,请参见 “服务衍生功能”。

训练和推理 API

create_training_set 并 score_batch 根据源数据按需计算该点的正确特征值。 对于支持脱机具体化的功能(如增量表源上的滑动窗口聚合),首先将功能具体化到脱机存储可以提高这两种操作的性能。 当具体化脱机功能可用时,操作将读取预计算的脱机数据,而不是从源重新计算特征值。 请参阅 具体化功能视图 ,将功能具体化到脱机存储。

create_training_set()

使用时间点正确的特征计算创建训练数据集。 有关详细信息,请参阅 使用功能视图训练模型。

FeatureEngineeringClient.create_training_set(
    df: DataFrame,                                # DataFrame with training data
    features: Optional[List[Feature]],            # List of Feature objects
    label: Union[str, List[str], None],           # Label column name(s)
    exclude_columns: Optional[List[str]] = None,  # Optional: columns to exclude
) -> TrainingSet

log_model()

在推理期间,使用特征元数据记录一个模型,用于世系跟踪和自动特征查找。 有关详细信息,请参阅 使用功能视图训练模型。

FeatureEngineeringClient.log_model(
    model,                                    # Trained model object
    artifact_path: str,                       # Path to store model artifact
    flavor: ModuleType,                       # MLflow flavor module (e.g., mlflow.sklearn)
    training_set: TrainingSet,                # TrainingSet used for training
    registered_model_name: Optional[str],     # Optional: register model in Unity Catalog
)

score_batch()

使用自动功能查找执行脱机批处理推理。 使用与模型一起存储的功能元数据来计算时间点正确的特征,确保与训练保持一致。

FeatureEngineeringClient.score_batch(
    model_uri: str,                           # URI of logged model (e.g., "models:/catalog.schema.model/1")
    df: DataFrame,                            # DataFrame with entity keys and timestamps
) -> DataFrame

输入数据帧必须包含训练期间使用的实体列和时间序列列。 从源数据自动计算特征。

fe = FeatureEngineeringClient()

# Batch scoring with automatic feature lookup
predictions = fe.score_batch(
    model_uri="models:/main.ecommerce.fraud_model/1",
    df=inference_df,
)
predictions.display()

时间范围

特征视图支持四种窗口类型,用于控制基于时间窗口聚合的回查行为。 可用的窗口类型取决于功能的源:流源功能可以使用滚动窗口和锯齿窗,批处理源功能可以使用滚动、滚动和滑动窗口。

  • 滚动窗口从事件时间回溯。 显式定义了持续时间和延迟。
  • 翻转窗口是固定的、不重叠的时间窗口。 每个数据点只属于一个窗口。
  • 滑动窗口是重叠的、连续滚动的时间窗口,具有可配置的滑动间隔。
  • Sawtooth 窗口通过混合批处理和流式路径,在流源上保持长时间的回查窗口是新鲜的。 参见 锯齿窗。

下图展示了翻滚窗、滑动窗、滚动窗和锯齿窗类型。

翻滚、滑动、滚动和锯齿形回视窗。

时间窗口时间

用来 delay 评估较早分析时间点的窗口。 例如,一个30天窗口但延迟7天,计算出评估前一周的30天值。 delay 与源到来时间无关。 要模拟源数据到达所需的时间,可以改为配置 SourceLateness.settling_delay 。

当两种环境同时存在时,他们就会作曲。 Azure Databricks 在源 settleling delay 后将窗口视为完整,并使用分析延迟进行评估。

用于 offset 更改固定窗口边界的对齐。 默认情况下,翻滚窗口和滑动窗口对齐于午夜UTC。 例如,22小时的偏移将每日边界对齐于协调世界时22:00。 要近似当地时区的边界,可以配置一个相对于UTC的静态偏移量。 偏移不调整夏令时、调整评估时间或建模晚到数据。

下表总结了对这些字段的支持情况:

领域 支持的窗口 约束
delay 滚动、翻滚和滑行 必须是非负数 datetime.timedelta
offset 翻滚与滑行 必须非负且时间短于周期*。
SourceLateness.settling_delay 滚动、翻滚和滑动特征 必须是非负数 datetime.timedelta
start_time 滚动、翻滚、滑行和锯齿波 必须是一个 datetime.datetime。 对于锯齿牙,必须不晚于特征创建时间。

*周期:对于翻滚窗口,偏移量必须小于 window_duration。 对于滑动窗口,它必须比 短 slide_duration。

开始时间

用于 start_time 设置UTC中特征可以输出的最早事件时间边界。 边界是包容性的。 start_time 门输出。 它不限制窗口可读取的历史源行,也不改变窗口的对齐。 如果 start_time 位于两个对齐边界之间,第一个符合条件的固定窗口输出就是下一个边界。

在 start_time的情况下,固定时长窗口可以在源中完整窗口时长结束前发出。 这些早期输出使用可用的源历史。 例如,考虑一个滑动窗口,其 window_duration 数据从2024年1月1日开始,数据为一年, slide_duration为一天:

  • 没有 start_time,该特征将在2025年1月1日首次发布,届时可以形成完整的一年窗口。
  • start_time该专题定于2024年8月21日播出,首播日期为2024年8月21日。 该输出仅涵盖截至2024年1月1日的原始历史。 该窗口于2025年1月1日达到完整的一年期,并从此产生完整的输出。

由于 start_time 不改变窗口对齐,两个对齐边界之间的值不会生成新的边界。 对于带有每日边界的翻滚窗口,UTC午夜时,06:00 UTC的a start_time 会在下一个午夜边界首次发射。 start_time一个恰好落在边界上的粒子会在该边界发射,因为该边界是包容的。

如果 start_time 未被设置,滚动窗口和固定时长滑动窗口会在形成完整窗口后,先在对齐边界处发射。 终身滑动窗口和滚动窗口一旦有合格源数据就会发出。

注释

start_time 支持锯齿窗,以及批量 DeltaTableSource特征上的滚动、翻滚和滑动窗口。 在 的情况下StreamSource不支持RollingWindow。 参见 锯齿窗。

例如:

from datetime import datetime, timedelta
from databricks.feature_engineering.entities import SlidingWindow

window = SlidingWindow(
    window_duration=timedelta(days=365),
    slide_duration=timedelta(days=1),
    start_time=datetime(2024, 8, 21),
)

卷帘窗

注释

RollingWindow 之前被命名为 ContinuousWindow。 如果要从早期 SDK 版本迁移,请相应地更新导入。

滚动窗口 up-to-date 和实时聚合,通常用于流数据。 在流式处理管道中,滚动窗口仅在固定长度窗口的内容发生更改时(例如事件进入或离开时)发出新行。 在训练管道中使用滚动窗口功能时,将使用紧邻特定事件的时间戳之前的固定长度窗口持续时间对源数据执行准确的时间点特征计算。 这有助于防止联机与脱机数据不一致或数据泄露。 在时间 T 时,以 [T - 持续时间, T) 区间的聚合事件为特征。

class RollingWindow(TimeWindow):
    window_duration: datetime.timedelta
    delay: Optional[datetime.timedelta] = None
    start_time: Optional[datetime.datetime] = None

下表列出了滚动窗口的参数。 窗口开始和结束时间基于以下参数:

  • 开始时间: evaluation_time - window_duration - delay (含)
  • 结束时间: evaluation_time - delay (独占)
参数 限制条件
delay (可选) 一定是≥0。 将分析窗口从评估时间戳倒推。 用 SourceLateness.settling_delay 来建模流中源到达延迟的一致基线。
window_duration 必须为 > 0
start_time (可选) 特征可以输出的最早事件时间边界。
from databricks.feature_engineering.entities import RollingWindow
from datetime import timedelta

# Look back 7 days from evaluation time
window = RollingWindow(window_duration=timedelta(days=7))

使用以下代码定义延迟滚动窗口。

# Compute a 7-day value as of one day before the evaluation time
window = RollingWindow(
    window_duration=timedelta(days=7),
    delay=timedelta(days=1)
)

滚动窗口示例

  • window_duration=timedelta(days=7):这会创建一个7天的回溯窗口,直到当前评估时间结束。 对于第 7 天下午 2:00 的活动,这包括从第 0 天下午 2:00 到第 7 天下午 2:00 之前的所有活动。

  • window_duration=timedelta(hours=1), delay=timedelta(minutes=30):这会在评估时间前30分钟结束时生成一个1小时的回溯窗口。 对于下午 3:00 的事件,这包括从下午 1:30 到(但不包括)下午 2:30 的所有事件。

用于 Last 绑定最新值的新鲜度

Last RollingWindow结合当最新值仅在有限时间内有效时。 在评估时,特征返回该区间内时间戳最晚的行的值:

[evaluation_time - delay - window_duration, evaluation_time - delay)

如果区间中最新的行包含空值,特征返回空值。 如果你想排除空输入值,可以在源端设置 a filter_condition 。

该组合与 ColumnSelection不同。 ColumnSelection 返回最新观察到的非空值,且不会根据年龄过期。

对于批量特征,这种组合有一个特殊的在线化模式。 它只 DeltaTableSource支持、 Last、、 RollingWindow和 TableTrigger。 参见 Materialize新鲜度受限的最新数值。

滑动窗口

对于使用滚动窗口定义的特性,聚合是通过预先确定的固定长度窗口计算的,该窗口按滑动间隔推进,生成完全划分时间的非重叠窗口。 因此,源中的每个事件都只贡献一个窗口。 在时间 t 的功能会聚合从时间窗口结束于或早于(但不包括)t 的数据。 Windows 从 Unix 时代开始。

class TumblingWindow(TimeWindow):
    window_duration: datetime.timedelta
    delay: Optional[datetime.timedelta] = None
    offset: Optional[datetime.timedelta] = None
    start_time: Optional[datetime.datetime] = None

下表列出了翻转窗口的参数。

参数 限制条件
window_duration 必须为 > 0
delay (可选) 一定是≥0。 将分析窗口从评估时间戳倒推。
offset (可选) 必须是≥0且小于 window_duration。 从UTC午夜开始调整窗口边界。
start_time (可选) 特征可以输出的最早事件时间边界。
from databricks.feature_engineering.entities import TumblingWindow
from datetime import timedelta

window = TumblingWindow(
    window_duration=timedelta(days=1),
    delay=timedelta(hours=2),
    offset=timedelta(hours=22),
)

滚动窗口示例

  • window_duration=timedelta(days=5):这会预设固定长度的窗口,每个窗口5天。 示例:窗口 #1 跨越第 0 天到第 4 天、窗口 #2 跨越第 5 天到第 9 天、窗口 #3 跨越第 10 天到第 14 天等。 具体而言,Window #1 包括所有在第 0 天从00:00:00.00开始且早于第 5 天00:00:00.00时间戳的事件(不包括第 5 天的事件)。 每个事件只属于一个窗口。

滑动窗口

对于使用滑动窗口定义的特征,聚合计算在一个按滑动间隔推进的窗口上。 滑动窗口可以是固定时长或终身时长。 固定时长窗口会重叠,因此每个源事件都可以为多个窗口的功能聚合做出贡献。 生命周期窗口包含窗口结束前的所有源事件。 在时间 t 的功能会聚合从时间窗口结束于或早于(但不包括)t 的数据。 Windows 与 Unix 时代保持一致。

class SlidingWindow(TimeWindow):
    window_duration: Optional[datetime.timedelta]
    slide_duration: datetime.timedelta
    delay: Optional[datetime.timedelta] = None
    offset: Optional[datetime.timedelta] = None
    start_time: Optional[datetime.datetime] = None

下表列出了滑动窗口的参数。

参数 限制条件
window_duration 必须是固定期限窗口的阳性。 设置为 None 终身窗口。
slide_duration 必须是正的。 对于固定时长的窗口,它也必须短于 window_duration。
delay (可选) 一定是≥0。 将分析窗口从评估时间戳倒推。
offset (可选) 必须是≥0且小于 slide_duration。 从UTC午夜开始调整窗口边界。
start_time (可选) 特征可以输出的最早事件时间边界。
from databricks.feature_engineering.entities import SlidingWindow
from datetime import timedelta

window = SlidingWindow(
    window_duration=timedelta(days=7),
    slide_duration=timedelta(days=1),
    delay=timedelta(hours=2),
    offset=timedelta(hours=22),
)

滑动窗口示例

  • window_duration=timedelta(days=5), slide_duration=timedelta(days=1):这会形成重叠的5天窗口,每次提前1天。 示例:窗口 #1 跨越第 0 天到第 4 天,窗口 #2 跨越第 1 天到第 5 天,窗口 #3 跨越第 2 天到第 6 天,依依如此。 每个窗口包括从00:00:00.00 开始日到(但不包括)结束日00:00:00.00的事件。 由于窗口重叠,单个事件可以属于多个窗口(在此示例中,每个事件最多属于 5 个不同的窗口)。

终身窗口

设置为 window_duration=None 创建一个终身窗口。 在每个幻灯片边界处,特征汇总该实体的所有源事件,时间戳早于该边界。 例如,一天的幻灯片每天产生一次累积值。

生命周期窗口仅支持。SlidingWindow RollingWindow并且TumblingWindow需要一个有限的。window_duration

注释

Lifetime 窗口需要客户端版本 databricks-feature-engineering 支持 window_duration=None 并启用工作区。 早期客户端版本不支持这种语法。

from datetime import timedelta
from databricks.feature_engineering.entities import (
    AggregationFunction,
    DeltaTableSource,
    Feature,
    SlidingWindow,
    Sum,
)

lifetime_spend = Feature(
    source=DeltaTableSource(
        catalog_name="main",
        schema_name="store",
        table_name="transactions",
    ),
    entity=["user_id"],
    timeseries_column="transaction_time",
    function=AggregationFunction(
        Sum(input="amount"),
        SlidingWindow(
            window_duration=None,
            slide_duration=timedelta(days=1),
        ),
    ),
    name="lifetime_spend",
)

锯齿窗

锯齿窗口是一种汇总,支持近期事件的高度更新,并每日压缩历史数据。 其后缘(较旧)沿以固定的每日步进方式推进,而前沿(近期)沿则保持最新事件,因此有效窗口长度在每天内“锯切”。 大部分时间窗口来自流的摄取表中的数据,只有最近两天的数据来自直播流。 这是一种高效计算长期窗口(可扩展至数年)的折中方案,同时保持对新更新的响应。

锯齿窗:前缘追踪最新事件,后缘按每日步进,因此覆盖窗户“锯”了每一天。

锯齿窗通过混合批次和流式路径实现。 批处理流水线维护窗口的大部分内容,而流式流水线则实时保持最新数据的新鲜性。 两者在读时合并,因此对模型或服务用户来说,这只是一个功能。

由于窗口的历史部分由批处理流程计算,锯齿形特征在物质化开始后不久即可投入使用,即使窗口跨越数月或数年。 滚动窗口只有在其完整窗口持续时间结束后才算完整。 最低 window_duration 限度必须超过两天(强制下限)。 Databricks建议在持续时间超过7天时使用锯齿形窗口。 对于超过两天甚至最多七天的窗户,可以在固定长度的 卷帘窗 和锯齿窗的快速生产准备之间选择。

注释

锯齿形特征依赖于已有的历史。 流的摄取表必须包含至少覆盖整个窗口时长的数据,否则计算出的窗口不完整。 如果不行,就设置 start_time 到你希望该功能最早提供价值的时间,最晚不要等于你创建该功能时。 以后数值 start_time 涵盖当时可用的历史。 不到两天,该特征仅反映迄今为止出现的数据。 在制作过程中,直到两整天过去才开始提供该功能。 在空窗口上的聚合对 和 返回 0Sum,对于 Avg, Min, Last,StddevSampMaxFirstVarPopVarSampStddevPopCount

要判断锯齿形特征是否已准备好,请在目录资源管理器中打开特征视图。 在 “物质化特征”部分,当特征的最后一次实现时间提前且状态显示成功时,批次回填即告完成。 流质部分通过Lakeflow声明式管道实现。 在功能视图通过验证后,实体化的功能会链接到该管道,你可以在那里监控其运行状态。

锯齿窗需要 和 StreamSource ,并以 StreamingMode实现。

class SawtoothWindow(TimeWindow):
    window_duration: datetime.timedelta
    start_time: Optional[datetime.datetime] = None

锯齿窗的边缘移动方式与滚动窗不同:前缘跟踪最新事件,而后缘每天前进一次,而非连续推进。 每天在固定的18:00 UTC截止点,后缘向前移动至当天UTC-午夜边界。 因此,有效窗口略长 window_duration ,并在一天中增长,然后在下一个截止日又会恢复。 培训和服务使用相同的18:00 UTC截止时间,因此离线培训和在线服务保持一致。

参数 限制条件
window_duration 必须超过两天。 允许的持续时间不是整数天(例如), timedelta(days=3, minutes=15)但窗口仍会以每日细度更新。
start_time (可选) 不能晚于功能创建时间。

设置 start_time 在Stream的摄取表中历史记录少 window_duration于时。 没有它,批处理流程会等待完整的历史窗口。 把它设置在你希望该功能最早提供价值的时间。 这个数值并不依赖于窗口中已有的数据。 该功能从此提供部分窗口值 start_time ,积累足够历史后达到完整窗口时长。

你不能把锯齿窗 start_time 设置在创建该功能之后。 start_time 门控窗口的批处理部分,因此后续的值允许流部分在 之前服务 start_time。

锯齿窗支持Sum, ,VarPopFirstDistinctLastDistinctLastNVarSampStddevPopCountMaxStddevSampMinFirstLastFirstNAvg

锯齿窗示例

以下示例展示了用户交易的7天计数。 前缘跟踪当前事件,后缘则一天一天地前进。 对于3月10日的活动,时间窗口可以追溯到大约3月3日。 随着3月10日的推进,前缘继续前进,而后端保持不动,因此覆盖跨度不断扩大。 然后,在3月11日初,尾缘逐渐过渡到大约3月4日。 有效窗口期总是略长于七天。 最近两天的日期由直播流提供,较早的天数则由直播的摄取表提供。

from databricks.feature_engineering.entities import SawtoothWindow
from datetime import timedelta

# 7-day window kept continuously fresh with streaming data
window = SawtoothWindow(window_duration=timedelta(days=7))

以下示例是一个数据从2026年1月1日开始的摄取表的365天总和。 start_time该功能自2026年1月1日起,提供部分窗口值,涵盖2027年1月1日起整整一年:

from datetime import datetime, timedelta
from databricks.feature_engineering.entities import SawtoothWindow

window = SawtoothWindow(
    window_duration=timedelta(days=365),
    start_time=datetime(2026, 1, 1),
)

锯齿窗的限制

  • 不支持此参数 delay 。
  • SourceLateness.settling_delay 不支持。
  • 你不能设置 start_time 比创建该功能的时间晚。
  • 除 、 、 、ApproxPercentileApproxCountDistinctStddevSampFirstDistinctVarPopVarSampLastDistinctStddevPopLastNFirstNCountLastMinFirstMaxAvgSum
  • 锯齿窗需要一个 StreamSource. DeltaTableSource A不支持。

具体化触发器

触发具体化管道运行时的控制。 触发器类型取决于功能类型。

CronSchedule

用于 CronSchedule 批处理聚合功能。 默认情况下,Azure Databricks 会从聚合窗口中派生一个排程。 派生计划考虑窗口期间、窗口 delay 和 offset,以及源 settling_delay 代码,确保运行在源数据预计完成前发布窗口。 派生时刻表支持翻滚和滑动窗口。

要请求派生调度,省略cron表达式。 CronSchedule() 和显式 CronSchedule(mode=CronScheduleMode.DERIVED) 形式是等价的:

from databricks.feature_engineering.entities import (
    CronSchedule,
    CronScheduleMode,
)

trigger = CronSchedule(mode=CronScheduleMode.DERIVED)

不要设置 quartz_cron_expression 。CronScheduleMode.DERIVED 当你检索到实体化的特性时,返回的计划可以包含 Azure Databricks 计算的 cron 表达式。

要直接控制时间表,提供Quartz cron表达式。 CronScheduleMode.MANUAL 当你给出表达式时,可以推断出:

from databricks.feature_engineering.entities import CronSchedule

trigger = CronSchedule(
    quartz_cron_expression="0 0 * * * ?",  # Hourly
    timezone_id="UTC",
)

TableTrigger

用于TableTriggerColumnSelection特征或聚合特征(),AggregationFunction由aDeltaTableSource或aSdpSource支持。 对于 DeltaTableSource,每当上游 Delta 表收到新的提交时,流水线就会运行。

对于聚合功能,流水线会限流,这样每次提交都不会运行。 默认情况下,运行间隔至少为该特征窗口长度的一半(滑 slide_duration 动窗口或 window_duration 翻滚窗口),保持在5分钟到1小时之间。 例如,一个1小时滚动窗口的长片最多每30分钟运行一次,而一个8小时窗口的长片最多每小时一次。 若要更改此项,请设置 min_time_between_triggers。 当半个窗口小于5分钟时,5分钟的最低时间段适用,所以10分钟或更短的窗口最多每5分钟运行一次。 时间窗口不到5分钟的聚合功能不能使用 TableTrigger,建议使用流媒体触发器。

from databricks.feature_engineering.entities import TableTrigger

trigger = TableTrigger()

对于由 支持的SdpSourceTableTrigger特征,则会监控源input_tables表而非输出表。 同一个输出表和触发器上的功能,你在一次调用中实现的,共享一个作业,该作业监控 input_tables 所有这些功能,最多可达25个表。 要监视超过10个表,请在每个被监视的表上启用文件事件。 参见 表格如何计入触发限制。 每次运行都会更新流水线,然后才实现功能。

要控制运行开始时间,请设置以下可选参数:

TableTrigger(
    min_time_between_triggers: Optional[timedelta] = None,     # Optional: Shortest gap between two runs
    wait_after_last_change: Optional[timedelta] = None,        # Optional: Quiet period after the last update before a run starts
    condition: Optional[TableTriggerCondition] = None,         # Optional: Which table updates start a run
)
  • min_time_between_triggers:两次得分之间允许的最短时间。 至少要等5分钟。 如果未设置,滑动窗口功能会消耗一半 slide_duration,滚动窗口功能则使用一半 window_duration,时间保持在5分钟到1小时之间。 其他特征没有最低要求。
  • wait_after_last_change: 源表必须多长时间不更新才会开始运行,以便一系列更新先行完成。 必须是零秒或至少60秒。 如果未设置或归零,运行会在源表更新后立即开始。
  • condition: TableTriggerCondition.TABLE_TRIGGER_CONDITION_ANY_UPDATED (默认)在任何源表更新时都会启动运行。 TableTriggerCondition.TABLE_TRIGGER_CONDITION_ALL_UPDATED 只有在所有源表更新后才开始运行。

以下示例等待所有输入表更新,然后等待10分钟以获得进一步更新,最多每小时运行一次:

from datetime import timedelta
from databricks.feature_engineering.entities import TableTrigger, TableTriggerCondition

trigger = TableTrigger(
    condition=TableTriggerCondition.TABLE_TRIGGER_CONDITION_ALL_UPDATED,
    wait_after_last_change=timedelta(minutes=10),
    min_time_between_triggers=timedelta(hours=1),
)

StreamingMode

使用 StreamingMode 连续结构化流式流水线计算功能,该流水线直接将结果写入在线商店。 它对于由 支持的 StreamSource特征是必需的,你也可以用它来支持 DeltaTableSource由 。

from databricks.feature_engineering import FeatureEngineeringClient
from databricks.feature_engineering.entities import (
    StreamSource, Feature, AggregationFunction, Sum,
    RollingWindow, OnlineStoreConfig, StreamingMode,
)
from datetime import timedelta

fe = FeatureEngineeringClient()

stream_source = StreamSource(full_name="my_catalog.my_schema.my_stream")

streaming_feature = fe.create_feature(
    source=stream_source,
    entity=["value.user_id"],
    timeseries_column="value.event_time",
    function=AggregationFunction(
        operator=Sum(input="value.amount"),
        time_window=RollingWindow(window_duration=timedelta(hours=1)),
    ),
    catalog_name="my_catalog",
    schema_name="my_schema",
    name="user_purchase_sum",
)

fe.materialize_features(
    features=[streaming_feature],
    online_config=OnlineStoreConfig(
        catalog_name="my_catalog",
        schema_name="my_schema",
        table_name_prefix="streaming_features_serving",
        online_store_name="feature_store_online",
    ),
    trigger=StreamingMode(),
)

从一个 DeltaTableSource

当你选择 StreamingMode() 由 支持 DeltaTableSource的功能时,流水线会将表 的变更数据源 读取为流源,而不是作为定时批处理作业运行。 它以微批处理模式运行,即以小批量处理新提交。 示例请参见 “使用DeltaTableSource定义流式功能”。

适用以下要求和行为:

  • 源表必须启用变更数据流(delta.enableChangeDataFeed = true)。 管道在开始时检查该属性,如果未设置则失败。
  • ColumnSelection 支持使用 RollingWindow A的 window_duration 特征和聚合特征。 流媒体 DeltaTableSource 功能不支持翻滚、滑动和锯齿槽窗口。
  • 物质化从表的最新版本开始,不处理表中已有的行。 在新数据窗口完整到达之前, RollingWindow 值仅反映流水线开始后提交的数据。
  • 插入和更新的行会贡献特征值。 从源表中删除行并不会从已经聚合好的值中移除行。
  • 你必须提供一个 online_config。 流媒体功能仅在在线商店中出现。

选择触发器

每个功能使用一个触发器;按功能类型分类的选项如下:

功能类型 Trigger 运行时
聚合 (AggregationFunction) 来自 DeltaTableSource CronSchedule 在衍生或手动时刻表上
聚合 (AggregationFunction) 来自 DeltaTableSource TableTrigger 在每个源表提交时
ColumnSelection (摘自 DeltaTableSource) TableTrigger 在每个源表提交时
聚合 (AggregationFunction) 来自 SdpSource CronSchedule 在衍生或手动时刻表上
聚合或 ColumnSelection 来自 SdpSource TableTrigger 关于更新 input_tables
功能 StreamSource StreamingMode 连续流式处理
RollingWindow 聚合或 ColumnSelection 来自 DeltaTableSource StreamingMode 连续流(微批量)

一个 materialize_features 调用可以包含带有不同触发条件、 SdpSourceDeltaTableSource 特征 SdpSource 以及来自不同管道的批量功能。 每个来源、流程和时间表都有自己的任务。 使用功能 StreamingMode 需要单独调用。