Search code examples
droolscomplex-event-processingdrools-fusion

Count number of facts in sliding window with Drools Fusion


I need to write a rule that counts the number of Facts I've received in my stream over the last 10 seconds if they match a certain criteria.

So, for instance, if 2 black cars pass through an intersection in the last 10 seconds I want to alert someone.

I have the following rule:

rule "check black cars in 10 seconds" dialect "java"
when

    $car : Car(color == Color.BLACK) over window:time(10s);
then

    System.out.println("got something");

This is working when I pass in a Black car, however, I don't want it to fire unless there are 2 black cars. I cannot find a good example of this.

Thanks.


Solution

  • when
    accumulate( Car(color == Color.BLACK) over window:time(10s);
                $cnt: count(1); $cnt == 2 )
    then
    

    This will fire when the second car arrives within 10 seconds of the first car, and again when a third car arrives within 10 seconds of the second car but later than 10 seconds after the first car, but that's what can be derived from your (vague) spec.