Search in sources :

Example 1 with GroupKey

use of org.drools.model.functions.accumulate.GroupKey in project drools by kiegroup.

the class AccumulateTest method testGroupBy3WithExists2.

@Test
public void testGroupBy3WithExists2() {
    String str = "import java.util.*;\n" + "import " + GroupKey.class.getCanonicalName() + ";\n" + "import " + Parent.class.getCanonicalName() + ";\n" + "import " + Child.class.getCanonicalName() + ";\n" + "global List results;\n" + "rule R1 when\n" + "    $p : Parent()\n" + "    exists( Child( this == $p.child) )\n " + "    not( GroupKey(topic ==\"a\", key == $p.getChild() ) )\n" + "then\n" + "    insert( new GroupKey( \"a\", $p.getChild() ) );\n" + "end\n" + "\n" + "rule R2 when\n" + "    $group: GroupKey( topic ==\"a\", $key : key )\n" + "    not( $p : Parent() and exists( Child( this == $key ) ) )\n" + "then\n" + "    delete( $group );\n" + "end\n" + "\n" + "rule R3 when\n" + "    GroupKey( topic ==\"a\", $k : key )\n" + "    accumulate (\n" + "            $p : Parent() and exists( Child( this == $p.getChild()) );\n" + "            $count : count($p)\n" + "         )\n" + "then\n" + "    results.add(java.util.Arrays.asList($k, $count));\n" + "end";
    KieSession ksession = getKieSession(str);
    List results = new ArrayList();
    ksession.setGlobal("results", results);
    Child child1 = new Child("Child1", 1);
    Parent parent1 = new Parent("Parent1", child1);
    Child child2 = new Child("Child2", 2);
    Parent parent2 = new Parent("Parent2", child2);
    ksession.insert(parent1);
    ksession.insert(parent2);
    FactHandle toRemove = ksession.insert(child1);
    ksession.insert(child2);
    ksession.fireAllRules();
    Assertions.assertThat(results).containsOnly(Arrays.asList(child1, 2L), Arrays.asList(child2, 2L));
    // Remove child1, therefore it does not exist, therefore there should be no groupBy matches for the child.
    results.clear();
    ksession.delete(toRemove);
    // Yet, we still get (Child2, 0).
    ksession.fireAllRules();
    Assertions.assertThat(results).containsOnly(Arrays.asList(child2, 1L));
}
Also used : Parent(org.drools.modelcompiler.domain.Parent) FactHandle(org.kie.api.runtime.rule.FactHandle) GroupKey(org.drools.model.functions.accumulate.GroupKey) ArrayList(java.util.ArrayList) KieSession(org.kie.api.runtime.KieSession) List(java.util.List) ArrayList(java.util.ArrayList) Child(org.drools.modelcompiler.domain.Child) Test(org.junit.Test)

Example 2 with GroupKey

use of org.drools.model.functions.accumulate.GroupKey in project drools by kiegroup.

the class AccumulateTest method testGroupBy3.

@Test
public void testGroupBy3() {
    // DROOLS-4737
    String str = "import java.util.*;\n" + "import " + GroupKey.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + "global Map results;\n" + "rule R1 when\n" + "    Person( $initial : name.substring(0,1) )\n" + "    not( GroupKey(topic ==\"a\", key == $initial) )\n" + "then\n" + "    insert( new GroupKey( \"a\", $initial ) );\n" + "end\n" + "\n" + "rule R2 when\n" + "    $k: GroupKey( topic ==\"a\", $initial : key )\n" + "    not( Person( name.substring(0,1) == $initial ) )\n" + "then\n" + "    delete( $k );\n" + "end\n" + "\n" + "rule R3 when\n" + "    GroupKey( topic ==\"a\", $initial : key )\n" + "    accumulate (\n" + "            Person( $age: age, name.substring(0,1) == $initial );\n" + "            $sumOfAges : sum($age)\n" + "         )\n" + "then\n" + "    results.put($initial, $sumOfAges);\n" + "end";
    KieSession ksession = getKieSession(str);
    Map results = new HashMap();
    ksession.setGlobal("results", results);
    ksession.insert(new Person("Mark", 42));
    ksession.insert(new Person("Edson", 38));
    FactHandle meFH = ksession.insert(new Person("Mario", 45));
    ksession.insert(new Person("Maciej", 39));
    ksession.insert(new Person("Edoardo", 33));
    FactHandle geoffreyFH = ksession.insert(new Person("Geoffrey", 35));
    ksession.fireAllRules();
    assertEquals(3, results.size());
    assertEquals(35, results.get("G"));
    assertEquals(71, results.get("E"));
    assertEquals(126, results.get("M"));
    results.clear();
    ksession.delete(meFH);
    ksession.fireAllRules();
    assertEquals(1, results.size());
    assertEquals(81, results.get("M"));
    results.clear();
    ksession.update(geoffreyFH, new Person("Geoffrey", 40));
    ksession.insert(new Person("Matteo", 38));
    ksession.fireAllRules();
    assertEquals(2, results.size());
    assertEquals(40, results.get("G"));
    assertEquals(119, results.get("M"));
}
Also used : HashMap(java.util.HashMap) FactHandle(org.kie.api.runtime.rule.FactHandle) GroupKey(org.drools.model.functions.accumulate.GroupKey) KieSession(org.kie.api.runtime.KieSession) Map(java.util.Map) HashMap(java.util.HashMap) Person(org.drools.modelcompiler.domain.Person) Test(org.junit.Test)

Example 3 with GroupKey

use of org.drools.model.functions.accumulate.GroupKey in project drools by kiegroup.

the class AccumulateTest method testGroupBy3With2VarsKey.

@Test
public void testGroupBy3With2VarsKey() {
    String str = "import java.util.*;\n" + "import " + GroupKey.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + "global Map results;\n" + "rule R1 when\n" + "    Person( $initial : name.substring(0,1) )\n" + "    String( $l : length )\n " + "    not( GroupKey(topic ==\"a\", key == $initial + $l) )\n" + "then\n" + "    insert( new GroupKey( \"a\", $initial + $l ) );\n" + "end\n" + "\n" + "rule R2 when\n" + "    $group: GroupKey( topic ==\"a\", $k : key )\n" + "    not( Person( $initial : name.substring(0,1) ) and\n" + "         String( $l : length, $k == $initial + $l )\n " + "    )\n" + "then\n" + "    delete( $group );\n" + "end\n" + "\n" + "rule R3 when\n" + "    GroupKey( topic ==\"a\", $k : key )\n" + "    accumulate (\n" + "            Person( $age: age, $initial : name.substring(0,1) ) and\n" + "            String( $l : length, $k == $initial + $l );\n" + "            $sumOfAges : sum($age)\n" + "         )\n" + "then\n" + "    results.put($k, $sumOfAges);\n" + "end";
    KieSession ksession = getKieSession(str);
    Map results = new HashMap();
    ksession.setGlobal("results", results);
    ksession.insert("test");
    ksession.insert("check");
    ksession.insert(new Person("Mark", 42));
    ksession.insert(new Person("Edson", 38));
    FactHandle meFH = ksession.insert(new Person("Mario", 45));
    ksession.insert(new Person("Maciej", 39));
    ksession.insert(new Person("Edoardo", 33));
    FactHandle geoffreyFH = ksession.insert(new Person("Geoffrey", 35));
    ksession.fireAllRules();
    assertEquals(6, results.size());
    assertEquals(35, results.get("G4"));
    assertEquals(71, results.get("E4"));
    assertEquals(126, results.get("M4"));
    assertEquals(35, results.get("G5"));
    assertEquals(71, results.get("E5"));
    assertEquals(126, results.get("M5"));
    results.clear();
    ksession.delete(meFH);
    ksession.fireAllRules();
    assertEquals(2, results.size());
    assertEquals(81, results.get("M4"));
    assertEquals(81, results.get("M5"));
    results.clear();
    ksession.update(geoffreyFH, new Person("Geoffrey", 40));
    ksession.insert(new Person("Matteo", 38));
    ksession.fireAllRules();
    assertEquals(4, results.size());
    assertEquals(40, results.get("G4"));
    assertEquals(119, results.get("M4"));
    assertEquals(40, results.get("G5"));
    assertEquals(119, results.get("M5"));
}
Also used : HashMap(java.util.HashMap) FactHandle(org.kie.api.runtime.rule.FactHandle) GroupKey(org.drools.model.functions.accumulate.GroupKey) KieSession(org.kie.api.runtime.KieSession) Map(java.util.Map) HashMap(java.util.HashMap) Person(org.drools.modelcompiler.domain.Person) Test(org.junit.Test)

Example 4 with GroupKey

use of org.drools.model.functions.accumulate.GroupKey in project drools by kiegroup.

the class GroupByTest method testWithNull.

@Test
public void testWithNull() {
    Variable<MyType> var = D.declarationOf(MyType.class);
    Variable<MyType> groupKey = D.declarationOf(MyType.class);
    Variable<Long> count = D.declarationOf(Long.class);
    AtomicInteger mappingFunctionCallCounter = new AtomicInteger(0);
    Function1<MyType, MyType> mappingFunction = (a) -> {
        mappingFunctionCallCounter.incrementAndGet();
        return a.getNested();
    };
    D.PatternDef<MyType> onlyOnesWithNested = D.pattern(var).expr(myType -> myType.getNested() != null);
    ExprViewItem groupBy = D.groupBy(onlyOnesWithNested, var, groupKey, mappingFunction, D.accFunction(CountAccumulateFunction::new).as(count));
    List<MyType> result = new ArrayList<>();
    Rule rule = D.rule("R").build(groupBy, D.on(groupKey, count).execute((drools, key, acc) -> result.add(key)));
    Model model = new ModelImpl().addRule(rule);
    KieBase kieBase = KieBaseBuilder.createKieBaseFromModel(model);
    MyType objectWithoutNestedObject = new MyType(null);
    MyType objectWithNestedObject = new MyType(objectWithoutNestedObject);
    KieSession ksession = kieBase.newKieSession();
    ksession.insert(objectWithNestedObject);
    ksession.insert(objectWithoutNestedObject);
    ksession.fireAllRules();
    // Side issue: this number is unusually high. Perhaps we should try to implement some cache for this?
    System.out.println("GroupKey mapping function was called " + mappingFunctionCallCounter.get() + " times.");
    Assertions.assertThat(result).containsOnly(objectWithoutNestedObject);
}
Also used : Arrays(java.util.Arrays) InternalFactHandle(org.drools.core.common.InternalFactHandle) Accumulator(org.drools.core.spi.Accumulator) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Global(org.drools.model.Global) RuleEventListener(org.kie.internal.event.rule.RuleEventListener) DSL(org.drools.model.DSL) Child(org.drools.modelcompiler.domain.Child) Match(org.kie.api.runtime.rule.Match) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) Declaration(org.drools.core.rule.Declaration) Assertions(org.assertj.core.api.Assertions) KieSession(org.kie.api.runtime.KieSession) Parent(org.drools.modelcompiler.domain.Parent) Set(java.util.Set) Index(org.drools.model.Index) ConsequenceBuilder(org.drools.model.consequences.ConsequenceBuilder) EvaluationUtil(org.drools.modelcompiler.util.EvaluationUtil) Objects(java.util.Objects) List(java.util.List) Tuple(org.drools.core.spi.Tuple) CountAccumulateFunction(org.drools.core.base.accumulators.CountAccumulateFunction) Person(org.drools.modelcompiler.domain.Person) DSL.from(org.drools.model.DSL.from) ModelImpl(org.drools.model.impl.ModelImpl) HashMap(java.util.HashMap) PatternDSL(org.drools.model.PatternDSL) ArrayList(java.util.ArrayList) Function1(org.drools.model.functions.Function1) CollectListAccumulateFunction(org.drools.core.base.accumulators.CollectListAccumulateFunction) RuleEventManager(org.kie.internal.event.rule.RuleEventManager) KieBase(org.kie.api.KieBase) LinkedHashSet(java.util.LinkedHashSet) Model(org.drools.model.Model) IntegerMaxAccumulateFunction(org.drools.core.base.accumulators.IntegerMaxAccumulateFunction) ReteEvaluator(org.drools.core.common.ReteEvaluator) ViewItem(org.drools.model.view.ViewItem) Pair(org.apache.commons.math3.util.Pair) Variable(org.drools.model.Variable) D(org.drools.modelcompiler.dsl.pattern.D) IntegerSumAccumulateFunction(org.drools.core.base.accumulators.IntegerSumAccumulateFunction) ToIntFunction(java.util.function.ToIntFunction) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) GroupKey(org.drools.model.functions.accumulate.GroupKey) FactHandle(org.kie.api.runtime.rule.FactHandle) KieBaseBuilder(org.drools.modelcompiler.builder.KieBaseBuilder) Assert.assertNull(org.junit.Assert.assertNull) Ignore(org.junit.Ignore) Rule(org.drools.model.Rule) ExprViewItem(org.drools.model.view.ExprViewItem) RuleTerminalNodeLeftTuple(org.drools.core.reteoo.RuleTerminalNodeLeftTuple) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) ExprViewItem(org.drools.model.view.ExprViewItem) D(org.drools.modelcompiler.dsl.pattern.D) ArrayList(java.util.ArrayList) CountAccumulateFunction(org.drools.core.base.accumulators.CountAccumulateFunction) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) KieBase(org.kie.api.KieBase) Model(org.drools.model.Model) KieSession(org.kie.api.runtime.KieSession) Rule(org.drools.model.Rule) ModelImpl(org.drools.model.impl.ModelImpl) Test(org.junit.Test)

Example 5 with GroupKey

use of org.drools.model.functions.accumulate.GroupKey in project drools by kiegroup.

the class GroupByTest method testSumPersonAgeGroupByInitialWithAcc.

@Test
public void testSumPersonAgeGroupByInitialWithAcc() throws Exception {
    final Variable<Person> var_GENERATED_$pattern_Person$4$ = D.declarationOf(Person.class);
    final Variable<String> var_$initial = D.declarationOf(String.class);
    final Variable<GroupKey> var_sCoPe3_GENERATED_$pattern_GroupKey$3$ = D.declarationOf(GroupKey.class);
    Rule rule1 = D.rule("R1").build(D.pattern(var_GENERATED_$pattern_Person$4$).bind(var_$initial, (Person _this) -> _this.getName().substring(0, 1)), D.not(D.pattern(var_sCoPe3_GENERATED_$pattern_GroupKey$3$).expr("FF3B1999B2904B3324A471615B8760C9", var_$initial, (GroupKey _this, java.lang.String $initial) -> EvaluationUtil.areNullSafeEquals(_this.getKey(), $initial), D.reactOn("key"))), D.on(var_$initial).execute((org.drools.model.Drools drools, java.lang.String $initial) -> {
        {
            drools.insert(new GroupKey("a", $initial));
        }
    }));
    final Variable<GroupKey> var_$k = D.declarationOf(GroupKey.class);
    final Variable<Object> var_$key = D.declarationOf(Object.class);
    final Variable<Person> var_sCoPe4_GENERATED_$pattern_Person$5$ = D.declarationOf(Person.class);
    Rule rule2 = D.rule("R2").build(D.pattern(var_$k).expr("8313F8B6FD1C0612B7758BFDB93F0DE4", (GroupKey _this) -> EvaluationUtil.areNullSafeEquals(_this.getTopic(), "a"), D.reactOn("topic")).bind(var_$key, (GroupKey _this) -> _this.getKey(), D.reactOn("key")), D.not(D.pattern(var_sCoPe4_GENERATED_$pattern_Person$5$).expr("AFBC8D66DD9165C71D89004BBF5B0F9C", var_$key, (Person _this, Object $key) -> EvaluationUtil.areNullSafeEquals(_this.getName().substring(0, 1), $key.toString()), D.reactOn("name"))), D.on(var_$k).execute((org.drools.model.Drools drools, GroupKey $k) -> {
        {
            drools.delete($k);
        }
    }));
    final Global<Map> var_results = D.globalOf(Map.class, "defaultpkg", "results");
    final Variable<GroupKey> var_GENERATED_$pattern_GroupKey$4$ = D.declarationOf(GroupKey.class);
    final Variable<Person> var_GENERATED_$pattern_Person$6$ = D.declarationOf(Person.class);
    final Variable<Integer> var_$age = D.declarationOf(Integer.class);
    final Variable<Integer> var_$sumOfAges = D.declarationOf(java.lang.Integer.class);
    Rule rule3 = D.rule("R3").build(D.pattern(var_GENERATED_$pattern_GroupKey$4$).expr("8313F8B6FD1C0612B7758BFDB93F0DE4", (GroupKey _this) -> EvaluationUtil.areNullSafeEquals(_this.getTopic(), "a"), D.reactOn("topic")).bind(var_$key, (GroupKey _this) -> _this.getKey(), D.reactOn("key")), D.accumulate(D.pattern(var_GENERATED_$pattern_Person$6$).bind(var_$age, (Person _this) -> _this.getAge(), D.reactOn("age")).expr("AFBC8D66DD9165C71D89004BBF5B0F9C", var_$key, (Person _this, Object $key) -> EvaluationUtil.areNullSafeEquals(_this.getName().substring(0, 1), $key), D.reactOn("name")), D.accFunction(org.drools.core.base.accumulators.IntegerSumAccumulateFunction::new, var_$age).as(var_$sumOfAges)), D.pattern(var_$sumOfAges).expr("00DE1D5962263283D8D799CF83F1A729", (java.lang.Integer $sumOfAges) -> EvaluationUtil.greaterThanNumbers($sumOfAges, 10)), D.on(var_$key, var_results, var_$sumOfAges).execute((Object $key, Map results, Integer $sumOfAges) -> {
        {
            results.put($key, $sumOfAges);
        }
    }));
    Model model = new ModelImpl().addRule(rule1).addRule(rule2).addRule(rule3).addGlobal(var_results);
    KieSession ksession = KieBaseBuilder.createKieBaseFromModel(model).newKieSession();
    Map results = new HashMap();
    ksession.setGlobal("results", results);
    ksession.insert(new Person("Mark", 42));
    ksession.insert(new Person("Edson", 38));
    FactHandle meFH = ksession.insert(new Person("Mario", 45));
    ksession.insert(new Person("Maciej", 39));
    ksession.insert(new Person("Edoardo", 33));
    FactHandle geoffreyFH = ksession.insert(new Person("Geoffrey", 35));
    ksession.fireAllRules();
    assertEquals(3, results.size());
    assertEquals(35, results.get("G"));
    assertEquals(71, results.get("E"));
    assertEquals(126, results.get("M"));
    results.clear();
    ksession.delete(meFH);
    ksession.fireAllRules();
    assertEquals(1, results.size());
    assertEquals(81, results.get("M"));
    results.clear();
    ksession.update(geoffreyFH, new Person("Geoffrey", 40));
    ksession.insert(new Person("Matteo", 38));
    ksession.fireAllRules();
    assertEquals(2, results.size());
    assertEquals(40, results.get("G"));
    assertEquals(119, results.get("M"));
}
Also used : HashMap(java.util.HashMap) InternalFactHandle(org.drools.core.common.InternalFactHandle) FactHandle(org.kie.api.runtime.rule.FactHandle) GroupKey(org.drools.model.functions.accumulate.GroupKey) KieSession(org.kie.api.runtime.KieSession) ModelImpl(org.drools.model.impl.ModelImpl) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Model(org.drools.model.Model) Rule(org.drools.model.Rule) Person(org.drools.modelcompiler.domain.Person) Map(java.util.Map) HashMap(java.util.HashMap) Test(org.junit.Test)

Aggregations

GroupKey (org.drools.model.functions.accumulate.GroupKey)5 Test (org.junit.Test)5 KieSession (org.kie.api.runtime.KieSession)5 FactHandle (org.kie.api.runtime.rule.FactHandle)5 HashMap (java.util.HashMap)4 Map (java.util.Map)4 Person (org.drools.modelcompiler.domain.Person)4 ArrayList (java.util.ArrayList)2 List (java.util.List)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 InternalFactHandle (org.drools.core.common.InternalFactHandle)2 Model (org.drools.model.Model)2 Rule (org.drools.model.Rule)2 Child (org.drools.modelcompiler.domain.Child)2 Parent (org.drools.modelcompiler.domain.Parent)2 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 LinkedHashSet (java.util.LinkedHashSet)1 Objects (java.util.Objects)1 Set (java.util.Set)1