Introduction to DRL
DRL allows business analysts and developers to express business logic in a declarative format. Files with the.drl extension contain one or more rules, each defining conditions and actions.
A rule in DRL consists of three main parts:
- Attributes: Optional configurations that affect rule behavior (like priority, timing)
- Conditions (when): Patterns that match facts in working memory
- Actions (then): Operations to execute when conditions are met
Basic Rule Structure
Rule Units
Rule units are a modern approach in Drools 10+ that provides a modular organization for rules and their associated data. A rule unit defines both the rules and the data sources they operate on.Declaration Structure
Data Sources
Rule units support different data source types:DataStore: Mutable collection that allows add/remove operationsDataStream: Append-only collection, ideal for event streamsSingletonStore: Holds a single value that can be updated
Packages and Imports
Package Declaration
Every DRL file must start with a package declaration:Import Statements
Import statements specify the fully qualified paths for classes used in your rules:Type Declarations
You can define new fact types directly in DRL:Metadata in Type Declarations
Add metadata to types or fields:@role(event): Marks a type as an event (for CEP)@timestamp: Specifies event timestamp field@duration: Specifies event duration field@expires: Sets automatic expiration time@key: Marks fields used for equality comparison
Rule Conditions (When)
Rule conditions use OOPath expressions to match patterns in working memory.Basic Pattern Matching
A pattern with constraints matches against a fact of the given type and the additional restrictions in brackets[] that are true or false. For example, the following condition is that the Persons RuleUnit’s age is greater than 21.
Binding Variables
Typical DRL syntax involves binding variables typically using$ before the variable name.
Multiple Constraints
Nested Properties
Advanced Navigation
Operators in Conditions
Comparison Operators
Compound Conditions
String Operators
Collection Operators
Rule Actions (Then)
Rule actions define operations to perform when conditions match.Basic Actions
Working with Data Sources
Modifying Facts
Using themodify block:
Rule Attributes
Rule attributes allow you to control rule behavior:salience: Sets rule priority (higher executes first)no-loop: Prevents rule re-activation if actions modify matching factsdate-effective: Rule only active after datedate-expires: Rule not active after datetimer: Schedule-based rule executionduration: Delay rule executionenabled: Enable or disable rule
Timers and Calendars
Timer Attribute
- Interval:
timer (int: <initial delay> <repeat interval>) - Cron:
timer (cron: <cron expression>)
Calendar Attribute
Conditional Elements
exists
Checks if at least one fact matches:not
Checks if no facts match:forall
Checks if all facts that match the first pattern also match the remaining patterns:Accumulate and GroupBy
Accumulate
The accumulate element allows collecting and processing values from multiple facts:averageminmaxcountsumcollectListcollectSet
GroupBy
GroupBy allows performing accumulate functions on specific groups:Queries
Queries allow you to search the working memory for facts matching specific criteria:Performance Tuning for DRL
Optimize rule performance with these practices:- Define constraints from left to right: `// Better /persons[ firstName == “John” ]
2. **Use equality operators (==) when possible**: // More efficient
/persons[ firstName == “John” ]
// Less efficient
/persons[ firstName != “OtherName” ]
3. **List most restrictive conditions first**: when
person ] // Less restrictive condition
4. **Avoid deep property access with excessive path expressions**: // Better: Add both Person and Address to the knowledge base
person, city == “New York” ]
// Less efficient
/persons/addresses[ city == “New York” ]
`
5. Use event listeners for logging instead of System.out.println
Decision Tables in Spreadsheets
Drools supports defining rules in spreadsheet decision tables (XLS/XLSX). A decision table consists of:RuleSetarea: Global definitions and attributesRuleTableareas: The actual rules, conditions, and actions
Basic Structure
- Label a cell
RuleSetin column B - Provide a rule set name in column C
- Add global attributes below the RuleSet cell
- Create a
RuleTablesection with a name - Define rule attributes, object types, constraints, and conditions
- Add rule values in rows below the conditions
Example Decision Table
Decision table for shipping charges based on order details:Complete Examples
Example 1: Loan Application Process
Example 2: Temperature Monitoring System
Example 3: Order Processing with Discounts
References and Resources
Language Levels
Drools supports different DRL language levels:- DRL6 (default): Compatible with previous Drools versions
- DRL10: Introduces clarity-improving changes
- DRL5, DRL6_STRICT: Deprecated and will be removed