gpt4 book ai didi

java - Drools:获取 3 个最近的事件

转载 作者:搜寻专家 更新时间:2023-11-01 02:50:34 25 4
gpt4 key购买 nike

我正在从事一个小型 Drools 项目,因为我想了解更多有关使用规则引擎的信息。我有一个名为 Event 的类,它具有以下字段:

  • 字符串标签;可以是任意字符串的标签。
  • long millis; 一个时间戳。 (实际上,这是从 Event 中的 JodaTime LocalDate 字段转换而来。)
  • int value; 我想要推理的值。

我将数百个 Event 实例插入到我的知识库中,现在我想获取标记有 “OK” 的 3 个最新事件。我想出了以下有效的代码:

rule "Three most recent events tagged with 'OK'"
when
$e1 : Event( tag == "OK",
$millis1 : millis )
$e2 : Event( tag == "OK",
millis < $millis1, $millis2 : millis )
$e3 : Event( tag == "OK",
millis < $millis2, $millis3 : millis )

not Event( tag == "OK",
millis > $millis1 )
not Event( tag == "OK",
millis > $millis2 && millis < $millis1 )
not Event( tag == "OK",
millis > $millis3 && millis < $millis2 )
then
# Do something with $e1.value, $e2.value and $e3.value
end

但我觉得应该有更好的方法来做到这一点。这非常冗长且不易重复使用:例如,如果我想获取具有 value > 10 的五个最近事件怎么办?我最终会复制粘贴大量代码,但我不想那样做 :)。此外,代码对我来说看起来不是很“漂亮”。我不太喜欢重复的 not Event... 约束,而且我也不喜欢必须一遍又一遍地重复相同的标记条件。 (这个例子是我的真实应用程序的高度简化版本,其中的条件实际上要复杂得多。)

如何改进此代码?

最佳答案

假设您正在使用 STREAM 事件处理模式并且您的事件在流中是有序的:

rule "3 most recent events"
when
accumulate( $e : Event( tag == "OK" ) over window:length(3),
$events : collectList( $e ) )
then
// $events is a list that contains your 3 most recent
// events by insertion order
end

=====编辑====

根据您在下面的评论,以下是如何在 Drools 5.4+ 中实现您想要的:

declare window LastEvents
Event() over window:length(3)
end

rule "OK events among the last 3 events"
when
accumulate( $e : Event( tag == "OK" ) from window LastEvents,
$events : collectList( $e ) )
then
// $events is a list that contains the OK events among the last 3
// events by insertion order
end

只需仔细检查语法,因为我正在用心这样做,但它应该接近于此。

关于java - Drools:获取 3 个最近的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12090295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com