Mittwoch, 5. Juni 2013

Drools Part 4 - Decision Tables

When taking a look at the Drools documentation, the second chapter deals with decision tables. So I thought, it is time to take a look into this topic. Instead of using  the previously presented DRL files and the MVEL-syntax to formulate rules, Drools also supports so called decision tables. Refering to the documentation "Decision tables are a 'precise yet compact' (ref. Wikipedia) way of representing conditional logic, and are well suited to business level rules". If you want to get more detailled information just take a look at chapter 2.4 of the Drools documentation or go on with reading this post.

So I took a deeper look into this function. After a first look it seems to be a really interesting and compact way to formulate rules. In my sensor scenario I wanted to use this feature, to identify different "levels" of a measurement. Starting with a simple example it should be something like:
  • when measured value > 0 and <= 50 then set quality level to normal and debug
  • when measured value > 50 and <= 100 then set quality level to high and debug
  • when measured value > 101 then set quality level to critical and debug
Using a decision table first of all we have to set up the table structure. I decided to use Microsoft Excel. Because Drools does not support the new .xlsx format I have to save my work as .xls.

A decision table consists of a rule set that contains the definition of the used types, imports etc. and the rule tables. The rule set looks like shown in the picture:


It is as easy as it looks. The rule table is also very easy to set up. The following picture shows the solution for the above rule set.


That’s all what we have to do. Now let’s change our source code, so that the decision table is loaded instead. We have to start the same way as before by creating the KnowledgeBuilder.

   KnowledgeBuilder kbuilder = 
      KnowledgeBuilderFactory.newKnowledgeBuilder();

Next we have to add the resource. Because we are using a decision table, the resource path as well as the type of the resource has to be updated. The rest is similar to the initialization of a knowledge base.

   kbuilder.add(ResourceFactory.newClassPathResource(
      "/dt_example.xls", ResourceType.DTABLE, dtc);   
   KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); 
   kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

One important thing is the dtc variable. This one contains the so-called decision table configuration. It is created using the KnowledgeBuilderFactory.

   DecisionTableConfiguration dtc = 
      KnowledgeBuilderFactory.newDecisionTableConfiguration(); 
   dtc.setInputType(DecisionTableInputType.XLS);   
   dtc.setWorksheetName(“Sheet 1”);

That’s it. Have fun.

Keine Kommentare:

Kommentar veröffentlichen