Drools Rule Learning

Source: Internet
Author: User
Tags set time

Drools Rule Learning

In Drools, a standard rule file is a text file that ends with ". DrL" because it is a
A standard text file, so you can open, view, and edit it with some Notepad tools. The rules are placed on
Rules file, a rule file can hold multiple rules, in addition, in the rules file can also be stored
User-defined functions, data objects, and custom queries related to some of the objects that may be used in the rules.
The file structure diagram is as follows:
Package
Imports
Globals
Functions
Queries
Rules
.....

For a rule file, it is necessary to declare the package first, except for the
The order in the file is arbitrary, meaning that there must be a package declaration in the rules file, and
The package declaration must be placed on the first line of the rule file. A rule usually consists of three parts: the attribute section (attribute), the condition
Section (LHS) and result section (RHS) a standard rule is structured as follows:
Rule "Name"
Attributes
When
LHS
Then
RHS
End

1. In the LHS, can contain 0~n conditions, if the LHS part is not empty, then the engine will automatically add an eval (true) condition, because the condition always returns true, so the LHS empty rule always returns True
2. There is no symbolic connection in these two pattern, there is no connection symbol in pattern in drools, then it is used as the default connection, so only two of the pattern in the LHS part of the rule is satisfied to return true. By default, each line can be ";" As a terminator (as with the end of Java), of course the end of the line can not add ";" End.


Conditional Section
1. Bind a connection
for connections to multiple constraints inside an object, you can use the && (and), | | (or) and "," (and) to implement
Sample code:
Rule "rule1"
when
Customer (age>20 | | gender== ' male ' && city== ' sh ')
then
<action>..
End

2. Comparison operators
There are 12 types of comparison operators available in drools: >, >=, <, <=, = =,! =, contains, not contains, member Of, not memberof, matches, not matches; Among the 12 types of comparison operators, the first six are more common and use more comparison operators
contains sample code:
Rule "Rule1"
When
er: Order ();
$customer: Customer (age >20, Orders contains er);
then
System.out.println ($customer. GetName ());
End

Not contains sample code:
Rule "Rule1"
When
er: Order (items not contains "phone");
Then
System.out.println (er. GetName ());
End

MemberOf (MemberOf is used to determine whether a field of a Fact object is in a collection (Collection/array)) sample code:
Global string[] ordernames; Defining Global Variables
Rule "Rule1"
When
er: Order (name MemberOf ordernames);
Then
System.out.println (er. GetName ());
End

Not memberOf (this operator is the opposite of the MemberOf action) example code:
Rule "Rule1"
When
erList: string[] ();
er: Order (name not memberOf erList);
Then
System.out.println (er. GetName ());
End

Matches is used to match a Fact field to a standard Java regular expression, and the string being compared can be a standard Java regular expression, but one thing to note is that there is no escaping problem of "\" in regular expression strings.
Example code:
Rule "Rule1"
When
$customer: Customer (name matches "Lee. *");
Then
System.out.println ($customer. GetName ());
End

Not matches (this operator is the opposite of the matches action)

Results section

We know that in the rules LHS is used to place conditions, so in the RHS although you can directly write
Java code, but it is not recommended to have conditional judgment in the code, if you need conditional judgment, then reconsider putting it in
LHS, otherwise it would violate the purpose of the rules of use.

In the Drools, inside the RHS, there are some macros that enable fast operation of the current working Memory.
Macro functions or objects, such as insert/insertlogical, update, and retract, can be implemented on the current working Memory
Add, delete, or modify a Fact object in the

1.insert
The role of insert is the same as the Insert method in which we call the Statefulknowledgesession object in the Java class, all of which are used to insert a Fact object into the current working Memory
Note: Once the Insert macro function is called, then Drools will re-match all the rules again, and for a rule that does not set the No-loop property to True, if the condition is met, regardless of whether it has been executed before, it will be executed again, this feature not only exists in the insert On the macro function, the update and retract macro functions described later have the same feature, so in some cases it is easy to invoke insert, update, or retract to cause a dead loop
The sample code is as follows:
Rule "Rule1"
Salience 1//The function of this property is to confirm the priority of the rule execution by a number, the higher the number, the higher the execution
When
Eval (true); Default setting
Then
Customer Cus=new customer ();
Cus.setname ("Zhang San");
Insert (cus);
End
Rule "Rule2"
Salience 2
When
$customer: Customer (name = = "Zhang San");
Then
System.out.println ("rule2----" + $customer. GetName ());
End

2.insertLogical
The Insertlogical function is similar to insert, and its role is to insert a Fact object into the current working Memroy

3.update
The update function has the same meaning as its name, which is used to update the fact in the current working memory, and the function of the update macro is basically the same as the Statefulsession object's Update method, which is used to tell when
Before the working Memory the Fact object has changed. It is used in two forms, one to update a fact object directly, and the other to update the fact object corresponding to the specified Facthandle by specifying Facthandle
The first one directly updates a Fact object:
Rule "Rule1"
Salience 2
When
Eval (true);
Then
Customer Cus=new customer ();
Cus.setname ("Zhang San");
Cus.setage (1);
Insert (cus);
End
Rule "Rule2"
Salience 1
When
$customer: Customer (name== "Zhang San", age<10);
Then
$customer. Setage ($customer. Getage () +1);
Update ($customer);
System.out.println ("----------" + $customer. GetName ());
End

The second can support the creation of a new fact object that replaces the fact object specified by the Facthandle object, thus implementing a new update of the object:
Rule "Rule1"
Salience 2
When
Eval (true);
Then
Customer Cus=new customer ();
Cus.setname ("Zhang San");
Cus.setage (1);
Insert (cus);
End
Rule "Rule2"
Salience 1
When
$customer: Customer (name== "Zhang San", age<10);
Then
Customer Customer=new customer ();
Customer.setname ("Zhang San");
Customer.setage ($customer. Getage () +1);
Update (Drools.getworkingmemory (). Getfacthandlebyidentity ($customer), customer);
System.out.println ("----------" + $customer. GetName ());
End

4.retract
Retract is used to remove the sample code from the working memory of a Fact object in the working memory:
Rule "Rule1"
Salience 2
When
Eval (true);
Then
Customer Cus=new customer ();
Cus.setname ("Zhang San");
Cus.setage (1);
Insert (cus);
End
Rule "Rule2"
Salience 1
When
$customer: Customer (name== "Zhang San");
Then
Retract ($customer);
End
5.modify
Modify is an expression block that can quickly modify multiple properties of a Fact object and automatically update to the current working Memory after the modification is complete.
Rule "Rule1"
Salience 2
When
$customer: Customer (name== "Zhang San", age==20);
Then
System.out.println ("Modify before customer
ID: "+ $customer. GetId () +"; Age: "+ $customer. Getage ());
Modify ($customer) {
SetId ("Super Man"),
Setage (30),
SetName ("Yellow Five")
}
End
Rule "Rule2"
Salience 1
When
$customer: Customer (name== "Yellow Five");
Then
System.out.println ("Modify after customer
ID: "+ $customer. GetId () +"; Age: "+ $customer. Getage ());
End


Properties section
1.salience
The function is used to set the priority of the rule execution, the value of the Salience property is a number, the higher the number, the higher the execution priority, and its value can be a negative. By default, the salience default value of the rule is 0, so if we do not manually set the Salience property of the rule, then its order of execution is random.
Example code:
Rule "Rule1"
Salience 1
When
Eval (True)
Then
System.out.println ("Rule1");
End
Rule "Rule2"
Salience 2
When
Eval (True)
Then
System.out.println ("Rule2");
End

Although the rule1 is in front, but because its salience is 1, and the Salience property of Rule2 is 2, Rule2 executes first and then Rule1.

2.no-loop
The effect is to control whether the rule that has already been executed is executed again when the condition is met again. The value of the No-loop property is a Boolean, and by default the value of the No-loop property of the rule is false, and if the No-loop property value is true, then the rule will be checked only once by the engine,
If the RHS part of the rule is executed if the condition is met, it ignores all rules that have the No-loop property set to True if the engine starts the check rule again due to the Fact update causing the engine to start again.
Example code:
Rule "Rule1"
Salience 1
No-loop true
When
$customer: Customer (name== "Zhang San")
Then
Update ($customer);
System.out.println ("Customer Name:" + $customer. GetName ());
End

3.date-effective
The function is to control the rules only after the arrival of the trigger, when the rule is run, the engine will automatically take the current operating system with the Date-effective set time value, only when the system time >=date-effective set time value,
The rule will not trigger execution, otherwise execution will not execute. Without setting this property, the rule can be triggered at any time, with no such restriction. The value of date-effective is a date type string, by default, the date-effective acceptable date format is "dd-mmm-yyyy"
Example code:
Rule "Rule1"
Date-effective "2009-09-25"//current date not less than 2009-09-25 can be executed
When
Eval (true);
Then
System.out.println ("Rule1 is execution!");
End
In the process of actual use, if you do not want to format this time, you can modify the default time format in the calling Java code by using the System.setproperty (String key,string value) method
Add this command to the Java file: System.setproperty ("Drools.dateformat", "yyyy-mm-dd");

4.date-expires
The effect is the opposite of the Date-effective property, Date-expires is used to set the validity period of the rule, the engine in the execution of rules, will check whether the rule has date-expires attributes, if any, Then the value of this property is compared to the current system time, if it is greater than the system time, then the rule executes, otherwise it is not executed.
Example code:
Rule "Rule1"
Date-effective "2009-09-25"//current date not less than 2009-09-25 can be executed (incl. 2009-09-25) Note the Change time format
Date-expires "2009-09-30"//current date greater than 2009-09-30 can be performed (without 2009-09-30) Note the Change time format
When
Eval (true);
Then
System.out.println ("Rule1 is execution!");
End

5.enabled
The function is used to define whether a rule is available. The value of this property is a Boolean value, and the default value of this property is true, indicating that the rule is available. Set its Enabled property value to False, then the engine will not execute the rule

6.dialect
The role is to define the type of language to be used in the rule, and currently supports two types of languages: Mvel and Java, by default, if there is no manual dialect of the rules, the Java language used

7.duration
The effect is to trigger in another thread after the value specified by the property. The value for this property is a long integer, in milliseconds
Example code:
Rule "Rule1"
Duration 3000
When
Eval (True)
Then
System.out.println ("Rule thread ID:" +thread.currentthread (). GetId ());
End

8.lock-on-active
The effect is an enhanced version of No-loop, which is primarily useful when using the Ruleflow-group property or Agenda-group property. The default value of the Lock-on-active property is false.
9.activation-group
The function is to divide several rules into a group, naming the group with a string, so that when one of the rules with the same Activation-group attribute is executed, the other rules will no longer be executed.
That is, in a set of rules with the same activation-group attribute, only one rule will be executed and no other rules will be executed. Of course, for a rule with the same activation-group attribute, whichever one executes first, it can be implemented with attributes like salience.
Example code:
Rule "Rule1"
Activation-group "Test"
When
Eval (True)
Then
System.out.println ("Rule1 execute");
End
Rule "Rule 2"
Activation-group "Test"
When
Eval (True)
Then
System.out.println ("Rule2 execute");
End

10.agenda-group
The function is the value of the Agenda-group property is also a string, through this string, the rules can be divided into several agenda group, by default, the engine calls these settings Agenda-group properties of the rules need to display
Specifies that a Agenda group receives focus (focus) so that rules in the Agenda group trigger execution, otherwise it will not execute.
Example code:
Rule "Rule1"
Agenda-group "001"
When
Eval (True)
Then
System.out.println ("Rule1 execute");
End
Rule "Rule 2"
Agenda-group "002"
When
Eval (True)
Then
System.out.println ("Rule2 execute");
End
Java calls:
Statefulknowledgesession statefulsession = Knowledgebase.newstatefulknowledgesession ();
Statefulsession.getagenda (). Getagendagroup ("002"). SetFocus (); Get execution focus
Statefulsession.fireallrules ();
Statefulsession.dispose ();

Learn what you don't use

11.auto-focus
The effect is to set the rule on the Agenda-group set to automatically take focus, if the property is set to true, then when the engine executes, it is not necessary to set the focus for a agenda group, otherwise.
12.ruleflow-group
The function is used to divide the rules into groups, and then use the corresponding rules by using the values of the Ruleflow-group property in the rule flow.






















Drools Rule Learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.