Search code examples
drools

Latest n events, matching a certain pattern


Is there a built-in feature in Drools, selecting the latest n events, matching a certain pattern? I've read about sliding length windows in the documentation and the stock tick example seemed to be exactly what I wanted: "For instance, if the user wants to consider only the last 10 RHT Stock Ticks, independent of how old they are, the pattern would look like this:"

StockTick( company == "RHT" ) over window:length( 10 )

When testing the example, it seems to me that it is evaluted more like a

StockTick( company == "RHT" ) from StockTick() over window:length( 10 )

selecting the latest 10 StockTick events and afterwards filtering them by company == "RTH", resulting in 0 to 10 RHT-Ticks, event though the stream contains more then 10 RTH-events.

A workaround is something like:

$tick : StockTick( company == "RHT" )
accumulate(
    $other : StockTick(this after $tick, company == "RHT" );
    $cnt : count(other);
    $cnt < 10)

which has bad performance and readability.


Solution

  • Most likely you are seeing an initial phase where the count of events in the window and according to the constraints hasn't reached the length specified in window:length yet. For instance,

    rule "Your First Rule"
    when
    accumulate( $st : Applicant($age: age > 5) over window:length(10)
                      from entry-point X,
                $avg: average ( $age ), $cnt: count( $st ))
    then
    System.out.println("~~~~~avg~~~~~");
    System.out.println($avg + ", count=" + $cnt);
    System.out.println("~~~~~avg~~~~~");
    end
    

    displays an output even before there are 10 matching Applicants but later on, $cnt never falls below 10, even though $age ranges from 0 to 9, periodically.

    If you do think you have found an example supporting your claim, please provide full code for reproduction and make sure to indicate the Drools version.

    Your workaround is very bad indeed, as it accumulates for each StockTick. But a window:length(n) can be very efficiently implemented by using an auxiliary fact maintaining a list of n events. This may even be more advantageous than window:length.