Processing events using streams
To receive events directly into a listener action, an on statement is used, for example:
01. Temperature t;
02. on all Temperature(sensorId="S001"):t { print t.toString(); }
If, instead, the events are to be received into a stream, a stream assignment statement is used:
01. stream<Temperature> temperatures := all Temperature(sensorId="S001");
This statement declares the stream variable temperatures, which is used to refer to a stream of Temperature events. On the right side of the assignment, the all Temperature(sensorId="S001") expression is a stream source template. A stream source template is an event template preceded by the all keyword; it uses no other event operators. It creates a stream that contains events that are received by the monitor instance and that match the event template.
The following code shows how the events in the stream are processed.
01. Temperature temperature;
02. stream<Temperature> temperatures := all Temperature(sensorId="S001");
03. from t in temperatures retain 3
04. select Temperature("S001", mean(t.temperature)) : temperature {
05. print temperature.toString();
06. }
A from statement is similar to an on statement in form. It consists of three parts:
A stream query
from t in temperatures retain 3
select Temperature("S001", mean(t.temperature))
Followed by a co-assignment
: temperature
Followed by a listener action
{ print temperature.toString(); }
In this example, the stream query processes events from the temperatures stream and computes the average temperature value of the three most recent events. A new output event is created for each new input event, having the literal value "S001" for the sensorId field and the evaluated average temperature value for the temperature field. Each output event, in turn, is co-assigned to the variable temperature and this is used in the print statement, within the listener action.
The average temperature value is calculated using the built-in2 mean() aggregate function.
The following topics provide examples of using the streams language elements.
2 Apama provides a number of commonly used aggregates as predefined built-in aggregates. It is also possible to create user-defined custom aggregates.