Search code examples
drools

Drools - How to access an object in THEN clause


I have a scenario when the data in the input is having different columns for one fact i.e. transposed data for e.g.

EmployeeID | EmpDept1 | EmpDept2 | EmpDept3 | EmpDept4 | EmpDept5

Now I have a lookup Department table as well e.g.

DeptId | DeptName

For me to do the lookup, one way is to create 5 rules like:

rule "Lookup dept-1 data"
when
    e: EmployeeData()
    d: DeptData(deptId == $e.EmpDept1)
then
    System.out.println(e.toString());
end

The problem here is that i have to create 5 rules (and in my case many more). Is there a way I can access the DeptData in the "THEN" clause and then write a JAVA lookup?

Or if there is any other good way, please let me know.

Thanks!


Solution

  • I resolved this by using "collect"

    rule "Lookup dept data"
    when
        e: EmployeeData()
        d1: ArrayList() from collect (DeptData(deptId == $e.EmpDept1))
        d2: ArrayList() from collect (DeptData(deptId == $e.EmpDept2))
        d3: ArrayList() from collect (DeptData(deptId == $e.EmpDept3))
        d4: ArrayList() from collect (DeptData(deptId == $e.EmpDept4))
        d5: ArrayList() from collect (DeptData(deptId == $e.EmpDept5))
    then
        System.out.println("Employee == " + e);
        if (d1.size() > 0) System.out.println("Department 1 == " + d1.get(0));
        if (d2.size() > 0) System.out.println("Department 1 == " + d2.get(0));
        if (d3.size() > 0) System.out.println("Department 1 == " + d3.get(0));
        if (d4.size() > 0) System.out.println("Department 1 == " + d4.get(0));
        if (d5.size() > 0) System.out.println("Department 1 == " + d5.get(0));
    end
    

    The "collect" function here ensures that Employee records are not duplicated and then individual applicable departments can be found.