Search code examples
javadrools

If I have a rules file in a Drools rules project, how can I choose which rule to apply when I receive a request?


If I have an .drl file, with the following rules:

package com.baeldung.drools.rules;

import com.baeldung.drools.model.Applicant;

global com.baeldung.drools.model.SuggestedRole suggestedRole;

dialect  "mvel"

rule "Suggest Manager Role"
    when
        Applicant(experienceInYears > 10)
        Applicant(currentSalary > 1000000 && currentSalary <= 
         2500000)
    then
        suggestedRole.setRole("Manager");
end

And it is invoked as follows

public SuggestedRole suggestARoleForApplicant(
    Applicant applicant,SuggestedRole suggestedRole){
    KieSession kieSession = kieContainer.newKieSession();
    kieSession.insert(applicant);
    kieSession.setGlobal("suggestedRole",suggestedRole);
    kieSession.fireAllRules();  //I don't want to execute all my rules I just want to execute specific rules
    // ...
}

If I had more than one rule, how would I execute only 1 or 2 specific rules from a list of rules in my rules file (.drl)?

I would expect not to use the kieSession.fireAllRules() method; but one or what steps should I follow to execute only some rules from my rules list?


Solution

  • Check the javadoc https://docs.drools.org/7.5.0.Final/kie-api-javadoc/org/kie/api/runtime/rule/StatefulRuleSession.html#fireAllRules-int- You can use kieSession.fireAllRules(1); to fire any number of rules you want. Also, you can pass an AgendaFilter agendaFilter to the same method if you want to match specific rules only.