drools rule for counting number of items

user2119807 Source

I am new to Drools and trying to create a rule that would display the customer who purchased the maximum of dell laptop. Please help me fix the rule below:

$c : Customer()
$item : Item()
Number( intValue > 1 )
from accumulate( $item ( this.bought="Dell laptops", this.customer=$c.getname(),count(1) )
drools

Answers

answered 4 months ago Esteban Aliverti #1

Assuming a very simplistic model, one of the easiest ways to achieve this is to use a combination of 2 rules: one that calculates the total of laptops bought by a client and another one to get the customer who bought the most. You can probably achieve the same in a single rule, but the result will be more complicated to read and maintain.

//We create a declared type to keep the information about the total
//amount of items purchased by a single client
declare TotalItemsByCustomer
  customer : Customer
  itemType : String
  amount   : Integer
end

rule "Dell Laptops by Customer"
when
  $c : Customer()
  $amount: Number() from accumulate( 
    Item(bought="Dell laptops", customer=$c.name, count(1))
then
  insert(new TotalItemsByCustomer($c, "Dell laptops", $amount));
end

rule "Customer who bought the most Dell laptops"
when
  $max: TotalItemsByCustomer(
    itemType == "Dell laptops"
  )
  not TotalItemsByCustomer(
    itemType == $max.itemType, 
    amount > $max.amount
  )
then
  System.out.println("Customer "+ $max.getCustomer().getName() + " is the one who bought more "+ $max.getItemType());
end

With a little bit more love you can generalize these 2 rules so they can be used for items other than 'Dell Laptops'.

Hope it helps,

comments powered by Disqus