Search code examples
droolsrule-enginekie

How can I get a variable already defined in drools lhs?


I'm using drools api to define a rule like this:

PackageDescr pkg = DescrFactory.newPackage()
       .name("org.drools.example")
       .newRule().name("Xyz")
           .attribute("ruleflow-grou","bla")
       .lhs()
           .and()
               .pattern("Student").id( "$stu", false ).constraint("name==miko").constraint("age > 6").end()
               .not().pattern("Bar").constraint("a+b==c").end().end()
           .end()
       .end()

Finnally it will transfer into drl file like:

$stu: Studeng(name == miko, age > 6)
not Bar(a + b == c)

My question is if I wanna to get the '$stu' variable defined befor and to add some more constaints, like: $stu(grade != 2) how can I get it and reuse it?


Solution

  • To add an additional constraint to Student, just chain it after the constraints you already have.

    .pattern("Student")
      .id( "$stu", false )
      .constraint("name == \"miko\"")
      .constraint("age > 6")
      .constraint("grade != 2 ")
    .end()
    

    Which would generate:

    $stu: Student( name == "miko", age > 6, grade != 2)
    

    (I'm presuming that's what you're trying to do, because $stu( grade != 2 ) is not valid syntax.)

    This rule would identify any students with the name "miko" (note this is case sensitive!), have an age greater than 6, and a grade not equal to 2.