Is there a way to revert rule engine ( stateful ) to initial state ( state where all rules and facts are inserted and fireAllRules() not been fired ) ?
Thanks in advance !
Is there a way to revert rule engine ( stateful ) to initial state ( state where all rules and facts are inserted and fireAllRules() not been fired ) ?
Thanks in advance !
There is no initial state in a session besides when it's created. When you insert Facts into the session the rules are evaluated, so you cannot go back into the evaluation steps. Maybe you can refactor your use case to make it perform better, but without more knowledge about your specific situation is very difficult to help you.
I ran into the same problem.
Yes, if you create a new session you will need to re-insert your new facts. Supposedly creating sessions is fast, but I have not been forced to run performance tests (yet). If you don't want to recreate the session, you can just retract the inserted fact objects. And then re-insert them. (Note that the 'retract' method has been deprecated in favor of 'delete'). So my code for my toy problem looks like this (I "reset" the session three times):
System.out.println("--Load the knowledge base with rules.--");
KieServices kServices = KieServices.Factory.get();
KieContainer kContainer = kServices.getKieClasspathContainer();
KieSession kSession = kContainer.newKieSession("ksession-rules");
Account account = new Account(200, "Mickey Mouse");
account.withdraw(150);
kSession.insert(account);
int rulesFired = kSession.fireAllRules();
System.out.println("**** Finished first run, fired " + rulesFired + " rule(s).");
// Reset session/rules by retracting facts
FactHandle handle = kSession.getFactHandle(account);
kSession.delete(handle);
account.deposit(1000);
kSession.insert(account);
rulesFired = kSession.fireAllRules();
System.out.println("**** Finished second run, fired " + rulesFired + " rule(s).");
//Reset rules again
handle = kSession.getFactHandle(account);
kSession.delete(handle);
account.deposit(10000000);
kSession.insert(account);
rulesFired = kSession.fireAllRules();
System.out.println("**** Finished third run, fired " + rulesFired + " rule(s).");
kSession.dispose();
You say that you have a "large number of facts". How large is large? (In my toy "Account" object, I have one String and one Integer). 100 BigDecimal fields? 100,000 Strings? Or are you referring to a large number of orders, implying that you need to "reset" the knowledge base many times per second?