droolsdrools-fusion

Drools: Prioritize fact matching based on a field's value


Consider the following scenario in Drools: We have a rule, matching objects of type A and B against each other.

rule 1
    when
        $a : A()
        $b : B($a.matches($b), flagged == false)
    then
        mofidy($b) { flag($a) }
end

However, A objects have a field called priority, and when a B arrives in the working memory, a matching A with the highest priority should flag it, above all other matching As. How is this possible in Drools? How does it affect performance?


Solution

  • Assuming that B.flag() is setting its flagged attribute to true, you can try something like this:

    rule 1
    when
        $a : A()
        not A(this != $a, priority > $a.priority)
        $b : B($a.matches($b), flagged == false)
    then
        mofidy($b) { flag($a) }
    end
    

    One thing to notice in this example is that if an A object with a high priority is inserted, any B that was already flagged with a lower A will not be reflagged.

    If you need to reflag yours Bs, then you can try something like this:

    rule 1
    when
        $a : A()
        not A(this != $a, priority > $a.priority)
        $b : B($a.matches($b), flag != $a)
    then
        mofidy($b) { flag($a) }
    end
    

    Hope it helps,