droolsdrools-plannerdrools-flow

Finding the most recent date in from all dates in Drools object


How can I find the most recent date among all joining dates in a Drools object?

My rule is something like this:

declare RecentDate
      dates : java.util.Date
end

rule "insert_dates"
      when
       //reading dates from back end
       Employee($date : dateOfJoining, $name : name, salary > 10000)
       then
       insert(new RecentDate($date))
end

Now I would like to find the most recent employee based on dateOfJoining. Any help is appreciated. Thank you.


Solution

  • One way to do it is to, given an employee, make sure that there is no other with a higher date:

    declare RecentDate
          dates : java.util.Date
    end
    
    rule "insert_dates"
    when
      //reading dates from back end
      Employee( $date : dateOfJoining, $name : name, salary > 10000)
      not Employee (dateOfJoining > $date)
    then
      insert(new RecentDate($date))
    end
    

    The rule above only works on the case you have all your Employee facts in your session before you execute fireAllRules(). If this is not the case, you can try to initially insert a RecentDate with a null date and then compare each Employee against it and update it accordingly:

    rule "Init RecentDate"
    when
      not RecentDate()
    then
      insert new RecentDate(null);
    end
    
    rule "update_dates"
    when
      Employee( $date : dateOfJoining, $name : name, salary > 10000)
      $d: RecentDate ( date == null || date < $date)
    then
      modify ($d){
        setDate($date)
      }
    end
    
    

    Hope it helps,