You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Drools嵌套exists规则报错:如何实现双列表对象匹配?

Drools嵌套exists报错的解决方案

你的规则报错是因为嵌套exists的from语法位置错误,Drools要求from必须紧跟在对应的模式声明之后。以下是几种纯Drools的正确实现方式,满足你判断A对象的bList和cList中存在B、C对象满足B.name == C.id的需求:

方法一:调整嵌套exists的结构

修正原规则的语法位置,将from $a.cList直接放在内部exists C(...)的模式之后:

rule "find B-C match"
when
    $a: A(bList != null && cList != null)
    exists B(
        name != null, // 避免空指针异常
        exists C(id == name) from $a.cList
    ) from $a.bList
then
    System.out.println("A has a match");
    // 执行其他操作
end

方法二:使用非嵌套的exists包裹匹配对

这种写法更直观,通过exists包裹B和C的匹配组合,明确表达"存在这样一对B和C"的逻辑:

rule "find B-C match"
when
    $a: A(bList != null && cList != null)
    exists (
        $b: B(name != null) from $a.bList
        $c: C(id == $b.name) from $a.cList
    )
then
    System.out.println("A has a match");
    // 执行其他操作
end

方法三:直接匹配(需注意重复触发)

如果不需要严格的"存在性判断",而是每找到一对匹配就触发规则,可以去掉exists,直接匹配B和C:

rule "find B-C match"
when
    $a: A(bList != null && cList != null)
    $b: B(name != null) from $a.bList
    $c: C(id == $b.name) from $a.cList
then
    System.out.println("A has a match");
    // 执行其他操作
end

注意:方法三会在每找到一组匹配的B、C时触发一次规则,如果A的bList和cList中有多组匹配,规则会多次执行。如果只需要判断"是否存在",推荐使用前两种方法。

内容的提问来源于stack exchange,提问作者Kaven Xiong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 05:37:34