问题
I'm using the drools 6 engine. Suppose I have an account object that has a collection of sections and each section has a status flag that can be "GOOD" or "BAD". If I was to write the following:
rule "Check if account has a good subsection"
when
$account : Account()
SubSection (status == "GOOD") from $account.getSubSections()
then
insertLogical(new AccountIsGood($account));
end
I would expect this to simply add the logical rule AccountIsGood($account)
if atleast one section was good. However, it seems this does not simply check for one successful subsection and end the rule, but instead it continues checking all subsections and inserting the logical rule for each valid subsection. Ex, if an account has four valid subsections, I get four copies of the rule for that account.
So my question is, is there a way to rewrite this rule to get the desired behavior?
The account class:
public class Account {
private List<SubSection> subsections;
// Getters / Setters/ other code
}
回答1:
Keep the rules as simple as possible. While it is feasible to check for the presence of the inserted AccoundIsGood()
, it is recommended to write the logic so that only the existence of a single good subsection is tested. Also, you need a from
to extract the subsections from the Account object.
rule testForGood
when
$account: Account( $sub: subsections )
exists SubSection( status == "GOOD" ) from $sub
then
insertLogical( new AccountIsGood($account) );
end
It might be a good idea to keep insertLogical
, if there is a chance that the subsection status might change away from "GOOD": the logically inserted fact would be retracted if the accound doesn't have at lease one GOOD section.
来源:https://stackoverflow.com/questions/23896960/drools-rule-format-for-firing-only-once