java - Drools 规则 - 空检查和累积条件

标签 java drools

我目前正在对运行一组 Drools 的 java 批处理进行一些修复。 (是的!)规则。

我必须修正的规则是这样的:

rule "Insert a too old condition"
        salience -1
    when
        $person : Person()
        $tooOldInstant : DateTime() from now.minusDays(10)
        DateTime( this < $tooOldInstant ) from accumulate (
            LastData( $date : lastDate ) from $person.personLastDatas,
            maxValue($date)
        )
    then
        insert(new Condition("submitTooOldCondition"));
end

哪里需要简化Person是一个带有 personLastDatas 的简单 bean Set<LastData>LastData有一个org.joda.time.DateTime lastDate 属性。

问题:如何在 if $person.personLastDatas 中插入新条件为 null 则规则适用吗?

类似于:

rule "Insert a too old condition modified"
        salience -1
    when
        $person : Person()
        $tooOldInstant : DateTime() from now.minusDays(10)
        $maxLastDate : DateTime() from accumulate (
            LastData( $date : lastDate ) from $person.personLastDatas,
            maxValue($date)
        )
        ($maxLastDate == null || $maxLastDate < $tooOldInstant)
    then
        insert(new Condition("submitTooOldCondition"));
end

最佳答案

您应该有两条规则,一条用于空条件,一条用于比较日期。

这里是空条件规则;它验证 Person 是否存在,但没有 personLastDatas 属性:

rule "Insert a too old condition modified - null case"
salience -1
when
  $person: Person( personLastDatas == null )
then
  insert(new Condition("submitTooOldCondition"));
end

您现有的规则足以进行日期比较检查。

一般来说,如果您发现自己尝试在规则的任一侧执行复杂的 if-else 逻辑,则很好地表明您应该有两个规则。由于这两条规则不能同时都为真,因此您只能插入一个这种类型的条件。

话虽这么说,如果您使用的是现代版本的 drools,则可以使用条件和命名空间结果。 documentation详细介绍了这一点(我已链接 7.37.0.Final;大多数最近的 7.30+ 版本都具有此功能。)以下是您的规则的示例:

rule "Insert a too old condition"
salience -1
when
  $person : Person( $lastDatas: personLastDatas )
  if ( $lastDatas == null ) break[noData]
  $tooOldInstant : DateTime() from now.minusDays(10)
  DateTime( this < $tooOldInstant ) from accumulate (
            LastData( $date : lastDate ) from $person.personLastDatas,
            maxValue($date)
  )
then
  insert(new Condition("submitTooOldCondition"));
then[noData]
  // any special logic for the null case goes here
  insert(new Condition("submitTooOldCondition"));
end

(这是伪代码;我在这台计算机上没有 drools 项目,但应该类似。)

基本上,这种语法虽然更难阅读,但将允许您处理这些重复/部分共享的案例规则。通常建议您有两个规则,其中一个规则扩展另一个规则,因此常见条件的子集可以触发一个结果,而全套条件可以触发另一个结果。这与您这里所拥有的不完全一样,但是可以根据您的用例对功能进行优化。

break 关键字告诉引擎一旦满足条件就停止计算左​​侧;还有一个 do 关键字允许继续评估。

关于java - Drools 规则 - 空检查和累积条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61890851/

相关文章:

java - Drools optaplanner 规则不起作用

java - 找不到适合 JBoss 应用程序的 MySQL 驱动程序

java - 我如何比较Java中的2个方法?

java - 试图阻止 Swing worker

drools - 使用 Drools 规则引擎对对象列表进行排序

java - Drools 规则表达式 : Access Nested class data member

java - Java 中的 FileLock 在同一进程内或不同进程之间或两者之间跨多个线程是否安全?

java - 如何在 C++ 中使用 JNI 将异常堆栈跟踪重定向到日志文件?

java - 如何从 Drools 列表中获取最大最小项目

java - Drools 6 - 如何解雇规则