2
votes

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
According to your description it sounds like that you have an instance of Account which has a list of SubSections. But, from your condition, looks like they are independent. Can you clarify? Can you also mention, if you are passing only the Account instance or the SubSections also to the engine?Bhesh Gurung
I send the account to the drools engine with kSession.execute(account);.Nixx

1 Answers

5
votes

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.