开发者

Drools rule to filter element with a numeric property below a percentage of the total from the List

I have just started using Drools on a small project and now I need to write a rule a bit complex and I don't really know what's the best way to do it.

I am applying this rule to a list of objects of the same type (this class has a field called numberOfExecutions). For each element from the list I need to select the ones which have the numberOfExecutions above 5% of the total numberOfExecutions (the sum of numberOfExecutions of all the elements in the list).

I could not think of a nice way to implement this in drools so far, does anyone have a suggestion?

EDIT1: The best I could think so far was 开发者_运维知识库to pre-compute the sum of numberOfExecutions before I apply the rules and make this value somehow available to the drools rules.


The solution depends on your ability to modify or create new object classes. Here is what I'd do in your case:

rule "Rule 1"
when
  $m : MyObject(counted == false)
  $c : Calculator
then
  modify($m) { setCounted(true); }
  $c.count($m);
end

rule "Rule 2"
when
  not  MyObject(counted == false)
  $m : MyObject(numberOfExecutions > ($c.totalExecutions * 0.05))
  $c : Calculator
then
  $m.markBiggerThan5();
end

I've introduced new Calculator class which counts uncounted objects (Rule 1). As you can see, Rule 2 (the one you asking for) will only fire when all object are marked as counted and totals stored in Calculator.


You can use "Java" Rule Dialect. Make a function that execute your logic for numberOfExecutions and set appropriate flag. You can pass list of objects or single object one by one for checking numberOfExecutions criteria. This method will work as any regular java method. Following is a small sample for calling function. It might help.

rule "numberOfExecutions "
    dialect "java"
    salience -1

    when

        $obj : yourObject()     
        eval(if not counted)

    then        
        checkNumberOfExecution($obj);

end

function void checkNumberOfExecution(com.test.YourObject obj) {

        //Your logic
}

It is just a hint. You can use it as you want.

Thanks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜