How to Write DRL Rules in Kogito for Globals Use Cases
Quick tutorial on how to write DRL rules in Kogito for globals use cases with syntax that is similar to regular Drools.
Join the DZone community and get the full member experience.Join For Free
While writing DRL rules for Kogito, its syntax is not so different from regular Drools. However, I recommend to take a look at the document:
Notable differences are:
- Designate Rule Unit
- Facts are supplied through DataSource
- LHS is written with OOPath
You can see kogito-examples (https://github.com/kiegroup/kogito-examples/) will help you to understand these differences.
Then… You may wonder “What about Global?”
To use a global to collect rule outcome is a popular use case in Drools.
global org.example.Result result; rule "older than 18" when $p : Person(age > 18) then result.addAdultPersonName("Hello " + $p.getName()); end
I will explain how to implement DRL rules in Kogito for such use cases
A) SingletonStore (recommended)
SingletonStore: A writable storage option for setting or clearing a single element and then notifying all subscribers that the element has been modified. Rules can pattern-match against the value and update or clear available values. For users familiar with Drools, this option is equivalent to a global. In fact, a Singleton<Object> is similar to an old-style global, except that when used in conjunction with rules, you can pattern-match against it.
You can replace global with SingletonStore, which is a singleton DataSource.
declare Hello extends RuleUnitData result : SingletonStore<Result> = DataSource.createSingleton() persons : DataStore<Person> = DataSource.createStore() end
Note that SingletonStore is a DataSource so you need to refer it in the LHS (unlike globals). But I think it’s rather a good thing so you see what you do.
rule "older than 18" when $r : /result $p : /persons[age > 18] then $r.addAdultPersonName("Hello, " + $p.getName()); end
Then you can write a simple query to return the result.
query hello $r : /result end
B) Plain Field in RuleUnitData
If you have a plain field (not a DataSource) in RuleUnitData class, it is a “global”.
declare Hello extends RuleUnitData result : Result = new Result() persons : DataStore<Person> = DataSource.createStore() end
You can use the field in RHS.
rule "older than 18" when $p : /persons[age > 18] then result.addAdultPersonName("Hello, " + $p.getName()); end
The field cannot be accessed in OOPath but you can refer it via “from”. So you can write a query like this.
query hello $r : Result() from result end
Opinions expressed by DZone contributors are their own.
10 Traits That Separate the Best Devs From the Crowd
Strategies for Reducing Total Cost of Ownership (TCO) For Integration Solutions
Knowing and Valuing Apache Kafka’s ISR (In-Sync Replicas)
Front-End: Cache Strategies You Should Know