from

The from keyword supports relations between objects.

Purpose

The from statement is used in the condition part of a rule to express relations between objects.

Context

Rule conditions

Syntax

condition from expression; 

Description

This statement returns true when the from condition matches an object that is returned by the from expression.

Using the from statement, you can directly access objects in the working memory and objects that are linked to other objects by fields or by method calls. Methods that are attached directly to the context object can be called in the expression part of the statement.

The from statement fosters performance because pattern matching is done on a reduced number of objects and not on all the objects in the working memory (see the first example below).

You can also use the from statement to access objects in a database. Using SQL queries in the expression part of the statement, you can retrieve information from a relational database (see the second example below).

Example

The first example uses the from keyword to extract a subset of objects while the second example uses the from keyword to query a relational database.

Example 1

The rule FindBookStore returns bookstores or stores with a book department in the city of London.

rule FindBookStore {
   when {
      ?s: Store(city == London);
      ?d: Department(type == Books) from ?s.department;
   }
   then {
      System.out.println(
                "The following book store/department was found: "
                + ?s.address);
   }
}

This rule is processed as follows:

  1. The first condition provides the stores in London in variable ?s.

  2. The second condition uses this reduced set of stores to find which store has a book department.

  3. If the when part is successful, the action part prints the stores found.

Example 2

The rule FindCarOwner finds the owner of a car by means of an SQL query to a relational database where employee information resides. The first condition matches a CarToMove object and returns a license number in variable ?l. The second condition returns, in variable ?c, a Car object found using ?l, the license number. The from statement uses the Person object to return a name in variable ?n, which matches the name of the car owner. An SQL query launched by the getOwner()method retrieves the car owner. The action part of the rule prints the person’s name and telephone number, the car model, and the driver license number.

rule FindCarOwner {
   when {
      CarToMove(?l:license);
      ?c: Car(license == ?l);
      ?p: Person(?n:name) from ?c.getOwner();
   }
   then {
      System.out.println("Contact " + ?n + " at telephone " 
             ?p.telephone + " to move a " + ?c.model + 
             " with license: " + ?l);
   }
}