Search code examples
javadrools

Accessing list in drools which are created runtime


I have a situation, I need to dynamically add rules in drools. If its a simple rule I can create a string for the same and add it into knowledgebase, but there is a situation where I need to include a list as part of the rule, which will also be created dynamically. Adding the rule and adding the list will happen as different events.

I thought of having a hashmap<String, List<String>> where key is the name of the list, now I want to know, is there way to access the hashmap, retrieve the list using the list name, and use in when criteria of drools as:

$pojo:Pojo($listOfString : list1, $listOfString contains input)

while adding the rule into drools.

And far as I know, even having a general name for the list in pojo wont work, as during fireRule, the drools will be totally confused in choosing the list to be used, and if I assign value to the list while firing rule, then for each rule he will use same list, and result will be as not expected.

Or if there is any other way of achieving the same, please tell me.

I am using drools 5.1


Solution

  • You can launch a query for an element in one of the lists by inserting a Query fact containing the list identification and the element value. eval should work in 5.1.1, IIRC. You may have to guard against there being no List for key x to avoid a NPE.

    rule "is element y in list with key x"
    when
        Query( $x: key, $y: element )
        Pojo( $map: map )
        eval( $map.get($x).contains( $y ) )
    then
        ...
    end