Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

什么例子最能说明按需计算的必要性?

先说出你的答案

定义边界、关键机制、一个反例;P8题再补容量、失败与验证。

查看完整题解

参考回答

直接回答

用当前交易额除以账户过去 30 天的平均交易额,是一个适合按需计算的例子。均值能提前算,当前这笔金额要到请求进来才知道。

讲清原理

如果试着提前为每个账户预存所有可能的比例,既不知道未来输入,也会浪费存储。实际取值时只查已经备好的历史,再完成简单除法即可。

例子与易错点

示例用输入样本模拟上游均值。120 元除以 40 元得到 3.0,均值为零或缺失就返回空值。这个均值取自声明好的历史视图,样例直接用已准备好的值。

from datetime import timedelta
from tecton import (
    Attribute, BatchSource, Entity, FileConfig, RequestSource,
    batch_feature_view, realtime_feature_view,
)
from tecton.types import Field, Float64, String

request = RequestSource(name="current_order", schema=[Field("amount", Float64)])
history = BatchSource(
    name="historical_averages",
    batch_config=FileConfig(uri="s3://example-only/averages/", file_format="parquet",
                            timestamp_field="event_time"),
)
account = Entity(name="account", join_keys=[Field("account_id", String)])

@batch_feature_view(
    sources=[history], entities=[account], mode="pandas",
    timestamp_field="event_time", features=[Attribute("average_30d", Float64)],
    batch_schedule=timedelta(days=1),
)
def historical_average(rows):
    return rows[["account_id", "event_time", "average_30d"]]

@realtime_feature_view(
    sources=[request, historical_average], mode="python",
    features=[Attribute("relative_amount", Float64)],
)
def relative_amount(order, historical):
    average = historical["average_30d"]
    return {"relative_amount": order["amount"] / average if average else None}

def evaluate(average):
    return relative_amount.run_transformation({
        "order": {"amount": 120.0},
        "historical": {"average_30d": average},
    })["relative_amount"]

assert evaluate(40.0) == 3.0
assert evaluate(0.0) is None
assert evaluate(None) is None
print("120 / 40 = 3.0; zero and missing -> None")

相关题:第 12 题、第 26 题、第 28 题、第 29 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。