Developing Apama Applications > EPL Streams: A Quick Tour > Common stream query patterns > Dynamic filters in stream queries
Dynamic filters in stream queries
Event listeners, created using on statements, are very efficient at matching events. But they have the drawback that the values of any variables or expressions used within an event template are evaluated only when the on statement is executed. That is, they are evaluated only when the event listener is created and they remain fixed thereafter.
For example, suppose you are using event listeners only and you need to change one of the match values each time a match is found. You would need to quit the current listener and recreate it with the new match value. An alternative approach is to use streams. For example, if you want to receive Temperature events for a given sensor, but to select only those where the temperature value is greater than a given, static threshold, you could do the following:
01. event Temperature { string sensorId; float temperature; }
02. monitor StaticFilter {
03. action onload() {
04. Temperature temperature;
05. on all Temperature (sensorId="T001", temperature>38.0): temperature {
06. print temperature.toString();
07. }
08. }
09. }
If, instead, you need to change the temperature threshold dynamically, then the following code could be used:
01. event Temperature { string sensorId; float temperature; }
02. event Threshold { string sensorId; float temperature; }
03. monitor StaticFilter {
04. Threshold threshold := Threshold("T001",38.0);
05. action onload() {
06. Temperature temperature;
07. from t in all Temperature(sensorId="T001")
08. where t.temperature > threshold.temperature select t : temperature {
09. print temperature.toString();
10. }
11. on all Threshold(sensorId="T001"): threshold {}
12. }
13. }
In the static case (that is, where the threshold value does not change), the code in the first example above is more efficient than that of the second example. This is because the events that are not of interest are rejected as early as possible, that is, before being passed to the monitor instance. In the dynamic case, that is, where a changing threshold value is required, the second example above is more elegant and typically more efficient than using a non-streams approach.
In the dynamic threshold use case, choosing which solution to prefer – using only event listeners or using streams - would depend on how frequently the threshold value is expected to change. The cost of quitting the current listener and recreating it with the new threshold value may be acceptable if the threshold value changes only infrequently.
Copyright © 2013-2015 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors.
Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG.