Drools using from inside accumulate from

556 Views Asked by At

In drools I can do something like this

rule "rule1"
    dialect "java"
    no-loop true
    
    when
       $order: Order( $cust: customer )
       Customer(id == "213123") from $cust

    then
end
class Order {
   private String areaCode;
   private Customer customer;
}

class Customer {
  private String id;
}

I want rule to identify if there are more than 3 different customers that ordered from same areaCode within an hour. Suppose a new order came in and I want to checkout if there is 3 or more orders from different customers to the same area within an hour.

rule "rule2"
    dialect "java"
    no-loop true
    
    when
        $order: Order( $cust: customer, $areaCode: areaCode)
        Customer( $custId: id) from $cust       
        Set( size >= 3 ) from accumulate ( 
            Order( $id: id, areaCode == $areaCode, customer.id != $custId ) over window:time( 1h ),
            collectSet( $id ) )

    then
end

Can I access customer.id the way that I use in rule 1 within from accumulate?

1

There are 1 best solutions below

3
Roddy of the Frozen Peas On

I'm a little unsure about what exactly you're trying to do in your example "rule3", but in general yes you can have a "from" clause inside of an accumulate.

Here's an example. Assume these models (getters and setters are implied but omitted for brevity):

class Student {
  private String name;
  private List<Course> courses;
}

class Course {
  private Double currentGrade; // [0.0, 100.0]
}

Let's say we want to write a rule where we identify students who have 3 or more classes with a grade < 70.0.

rule "Students with three or more classes with less than a 70"
when
  $student: Student($courses: courses != null)
  $failingCourses: List( size >= 3 ) from accumulate (
    $course: Course( currentGrade < 70.0 ) from $courses,
    collectList( $course )
  )
then
  System.out.println("Student '" + $student.getName() + "' is failing " + $failingCourses.size() + " courses.");
end

In your accumulate you can use a 'from' clause to indicate the source of the objects you're accumulating. In my case it's a list, but you can use a window or temporal operations as well.