Search code examples
drools

How to join two query in drools rule language


I have two queries used to find specific items, they are as follows:

query "score" (double s)
    Item( score > s )
end

query "price" (double p)
    Item( price < p )
end

The following query is used to find items score > s or price < p:

query "price or score" (double p, double s)
    price(p;) or score(s;)
end

My question is how I can find all items score > s and price < p

The following query doesn't work. It performs cross-join, not inner-join.

query "price and score" (double p, double s)
    price(p;) and score(s;)
end

Thanks


Solution

  • This query delivers Item facts with a price < p and a score > s:

    query "price and score" (double p, double s)
        item: Item(price < p, score > s)
    end
    

    To compose a query as a conjunction of two queries, you must provide a variable for binding a reference to the fact:

    query "score" (double s, Item item)
        Item( this == item, score > s )
    end
    
    query "price" (double p, Item item)
        Item( this == item, price < p )
    end
    
    query "price and score" (double p, double s )
        price(p, item; ) and score(s, item; )
    end