javadrools

Drools Rule Matching Behavior - Evaluation of Multiple Objects in a Collection


I am working with a Drools rule in which I have the following pattern matching conditions:

when
$contract: ContractFact()
$entity: EntityFact
$service: ServiceFact(serviceId == $contract.serviceId) from $contract.services
$ec: EvaluationCriteriaFact(
    toCode contains $entity.toCodes,
    fromCode contains $entity.fromCodes,
) from $service.evaluationCriterias

$pricing: Pricing(($entity.Weight >= minWeight && $entity.Weight <= maxWeight)) from 
$ec.pricingscenarios
$priceResult: PricingResultObject()
then
$priceResult.price = $calculatePrice.getTowPriceG($entity.toCodes, ...)
end

`

My concern is regarding the behavior when one of the EvaluationCriteriaFact instances matches the conditions but fails to match the Pricing conditions ($entity.Weight >= minWeight && $entity.Weight <= maxWeight). In this case, does the Drools engine proceed to check the remaining objects present in the evaluationCriterias list, or does it stop evaluating further?


Solution

  • The rule will fire once for each object in the list that matches your criteria. Each element in the list will be considered individually.

    Here's a simpler example.

    rule "example"
    when
      Event( $attendees: attendees ) 
      Person( isVegetarian == true, $name: name ) from $attendees
    then
      System.out.Println($name + " is attending and requires a vegetarian meal.")
    end
    

    If we pass the following object:

    {
      attendees: [
        { name: "Alice", isVegetarian: true },
        { name: "Bob", isVegetarian: false },
        { name: "Charlie", isVegetarian: true },
        { name: "Denise" isVegetarian: false }
      ]
    }
    

    Then the output would be (in some order):

    Alice is attending and requires a vegetarian meal.
    Charlie is attending and requires a vegetarian meal.
    

    If you invoked the rules using fireAllRules, that method would return 2 because the same rule matched and executed twice, once for the 'Alice' person, and once for the 'Charlie' person.