Drools: modify() or update() only if exists, otherwise add

こ雲淡風輕ζ 提交于 2019-12-13 06:22:24

问题


This is my rule:

rule "Set value of LeftArm fluent" 
when
    $ev: Start()
    $fl:LeftArm()
then
    Sample s = new Sample();
    s.setFluent($fl);
    s.setValue(-1.0);
    insert(s);
end

Ok, but if I want to set the value of the sample only if I haven't Samples with the same $fl AND otherwise modify the value of Sample, how can I do it? Am I obliged to write 2 rules?


回答1:


No, you just add the condition that should inhibit the insertion of a new sample:

rule "Set value of LeftArm fluent" 
when
  $ev: Start()
  $fl:LeftArm()
  not Sample( fluent == $fl )
then
  Sample s = new Sample();
  s.setFluent($fl);
  s.setValue(-1.0);
  insert(s);
end

After modification of the Q If you already have a Sample fact and need to setValue to -1.0 for the combination Start/LeftArm you'll need two rules, but you can use extends:

rule "StartLeftArm" 
when
  $ev: Start()
  $fl:LeftArm()
then
end

rule "create Sample" extends "StartLeftArm"
when
    not Sample( fluent == $fl )
then
    Sample s = new Sample();
    s.setFluent( $fl );
    insert( s );
end
rule "set Sample Value" extends "StartLeftArm"
when
    $s: Sample( fluent == $fl, value != -1.0 )
then
    modify( $s ){ setValue( -1.0 ) }
end


来源:https://stackoverflow.com/questions/21605977/drools-modify-or-update-only-if-exists-otherwise-add

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!