Drools决策表实践运用
Drools 决策表的使用与说明
Drools决策表的使用
官方文档决策表说明
Drools 决策表的使用 16.7. Spreadsheet decision tables
决策表使用方式
在Drools中,决策表通常是以Excel(.xls或.xlsx)或者CSV格式存储的,这些格式的决策表并不能直接被Drools执行。它们需要被转换成Drools规则语言(DRL)的文本格式,之后才能被编译和执行。
Drools提供了工具来帮助完成这一转换,主要使用org.drools.decisiontable.SpreadsheetCompiler类
以下是一个基本的转换过程
这是我的决策表:
表一( Pricing bracket)
表二(Discounts)
文件名称:ExamplePolicyPricing.xls
项目的结构目录:
// 加载决策表文件
InputStream is = DecisionTableToDRL.class.getResourceAsStream("/path/to/decisiontable.xls");
// 创建SpreadsheetCompiler实例
SpreadsheetCompiler compiler = SpreadsheetCompilerFactory.newCompiler();
// 转换决策表为DRL
String drl = compiler.compile(is, "UTF-8", "decisiontable");
// 打印DRL规则
System.out.println(drl);
xls转为drl结果为:
package com.mk.examples.decisiontable;
//generated from Decision Table
import com.mking.drools.bean.decisiontable.*;
// rule values at B9, header at B4
rule "Pricing bracket_9"
when
Driver(age >= 18, age <= 24, locationRiskProfile == "LOW", priorClaims == "1")
policy: Policy(type == "COMPREHENSIVE")
then
policy.setBasePrice(450);
end
// rule values at B10, header at B4
rule "Pricing bracket_10"
when
Driver(age >= 18, age <= 24, locationRiskProfile == "MED")
policy: Policy(type == "FIRE_THEFT")
then
policy.setBasePrice(200);
System.out.println("Priors not relevant");
end
// rule values at B11, header at B4
rule "Pricing bracket_11"
when
Driver(age >= 18, age <= 24, locationRiskProfile == "MED", priorClaims == "0")
policy: Policy(type == "COMPREHENSIVE")
then
policy.setBasePrice(300);
end
// rule values at B12, header at B4
rule "Pricing bracket_12"
when
Driver(age >= 18, age <= 24, locationRiskProfile == "LOW")
policy: Policy(type == "FIRE_THEFT")
then
policy.setBasePrice(150);
end
// rule values at B13, header at B4
rule "Pricing bracket_13"
when
Driver(age >= 18, age <= 24, locationRiskProfile == "LOW", priorClaims == "0")
policy: Policy(type == "COMPREHENSIVE")
then
policy.setBasePrice(150);
System.out.println("Safe driver discount");
end
// rule values at B14, header at B4
rule "Pricing bracket_14"
when
Driver(age >= 18, age <= 24, locationRiskProfile == "MED", priorClaims == "1")
policy: Policy(type == "COMPREHENSIVE")
then
policy.setBasePrice(700);
end
// rule values at B15, header at B4
rule "Pricing bracket_15"
when
Driver(age >= 18, age <= 24, locationRiskProfile == "HIGH", priorClaims == "0")
policy: Policy(type == "COMPREHENSIVE")
then
policy.setBasePrice(700);
System.out.println("Location risk");
end