Esper - Event Stream and Complex Event Processing for Java

Reference Documentation

2.1.0


Table of Contents

Preface
1. Technology Overview
1.1. Introduction to CEP and event stream analysis
1.2. CEP and relational databases
1.3. The Esper engine for CEP
1.4. Required 3rd Party Libraries
2. Event Representations
2.1. Event Underlying Java Objects
2.2. Event Properties
2.3. Dynamic Event Properties
2.4. Plain-Old Java Object Events
2.4.1. Java Object Event Properties
2.5. java.util.Map Events
2.5.1. Map-Within-Map Nested Events
2.6. org.w3c.dom.Node XML Events
2.7. Additional Event Representations
2.8. Updating and Versioning Events
3. Processing Model
3.1. Introduction
3.2. Insert Stream
3.3. Insert and Remove Stream
3.4. Filters and Where-clauses
3.5. Time Windows
3.5.1. Time Window
3.5.2. Time Batch
3.6. Batch Windows
3.7. Aggregation and Grouping
3.7.1. Insert and Remove Stream
3.7.2. Output for Aggregation and Group-By
3.7.2.1. Un-aggregated and Un-grouped
3.7.2.2. Fully Aggregated and Un-grouped
3.7.2.3. Aggregated and Un-Grouped
3.7.2.4. Fully Aggregated and Grouped
3.7.2.5. Aggregated and Grouped
3.8. EventBean Query Results
4. EPL Reference: Clauses
4.1. EPL Introduction
4.2. EPL Syntax
4.2.1. Specifying Time Periods
4.2.2. Using Comments
4.2.3. Reserved Keywords
4.3. Choosing Event Properties And Events: the Select Clause
4.3.1. Choosing all event properties: select *
4.3.2. Choosing specific event properties
4.3.3. Expressions
4.3.4. Renaming event properties
4.3.5. Choosing event properties and events in a join
4.3.6. Choosing event properties and events from a pattern
4.3.7. Selecting insert and remove stream events
4.3.8. Qualifying property names and stream names
4.4. Specifying Event Streams: the From Clause
4.4.1. Filter-based Event Streams
4.4.1.1. Specifying an event type
4.4.1.2. Specifying filter criteria
4.4.1.3. Filtering Ranges
4.4.1.4. Filtering Sets of Values
4.4.1.5. Filter Limitations
4.4.2. Pattern-based Event Streams
4.4.3. Specifying Views
4.4.4. Using the Stream Name
4.5. Specifying Search Conditions: the Where Clause
4.6. Aggregates and grouping: the Group-by Clause and the Having Clause
4.6.1. Using aggregate functions
4.6.2. Organizing statement results into groups: the Group-by clause
4.6.3. Selecting groups of events: the Having clause
4.6.4. How the stream filter, Where, Group By and Having clauses interact
4.6.5. Comparing the Group By clause and the std:groupby view
4.7. Stabilizing and Limiting Output: the Output Clause
4.7.1. Output Clause Options
4.7.2. Aggregation, Group By, Having and Output clause interaction
4.7.3. Runtime Considerations
4.8. Sorting Output: the Order By Clause
4.9. Merging Streams and Continuous Insertion: the Insert Into Clause
4.9.1. Transposing a Property To a Stream
4.9.2. Merging Streams By Event Type
4.9.3. Merging Disparate Types of Events: Variant Streams
4.10. Joining Event Streams
4.11. Outer Joins
4.12. Unidirectional Joins and Outer Joins
4.13. Subqueries
4.13.1. The 'exists' keyword
4.13.2. The 'in' keyword
4.14. Joining Relational Data via SQL
4.14.1. Joining SQL Query Results
4.14.2. SQL Query and the EPL Where Clause
4.14.3. Outer Joins With SQL Queries
4.14.4. Using Patterns to Request (Poll) Data
4.14.5. JDBC Implementation Overview
4.14.6. Oracle Drivers and No-Metadata Workaround
4.15. Joining Non-Relational Data via Method Invocation
4.15.1. Joining Method Invocation Results
4.15.2. Providing the Method
4.15.3. Using a Map Return Type
4.16. Creating and Using Named Windows
4.16.1. Creating Named Windows: the Create Window clause
4.16.2. Deleting From Named Windows: the On Delete clause
4.16.2.1. Using Patterns in the On Delete Clause
4.16.3. Inserting Into Named Windows
4.16.4. Selecting From Named Windows
4.16.5. Triggered Select on Named Windows: the On Select clause
4.16.6. Triggered Playback from Named Windows: the On Insert clause
4.16.7. Updating and Versioning Events in Named Windows
4.17. Variables
4.17.1. Creating Variables: the Create Variable clause
4.17.2. Setting Variable Values: the On Set clause
4.17.3. Using Variables
5. EPL Reference: Patterns
5.1. Event Pattern Overview
5.2. How to use Patterns
5.2.1. Pattern Syntax
5.2.2. Patterns in EPL
5.2.3. Subscribing to Pattern Events
5.2.4. Pulling Data from Patterns
5.3. Operator Precedence
5.4. Filter Expressions In Patterns
5.5. Pattern Operators
5.5.1. Every
5.5.1.1. Every Operator Example
5.5.1.2. Sensor Example
5.5.2. And
5.5.3. Or
5.5.4. Not
5.5.5. Followed-by
5.6. Pattern Guards
5.6.1. timer:within
5.7. Pattern Observers
5.7.1. timer:interval
5.7.2. timer:at
6. EPL Reference: Operators
6.1. Arithmetic Operators
6.2. Logical And Comparsion Operators
6.3. Concatenation Operators
6.4. Binary Operators
6.5. Array Definition Operator
6.6. The 'in' Keyword
6.7. The 'between' Keyword
6.8. The 'like' Keyword
6.9. The 'regexp' Keyword
7. EPL Reference: Functions
7.1. Single-row Function Reference
7.1.1. The Case Control Flow Function
7.1.2. The Cast Function
7.1.3. The Coalesce Function
7.1.4. The Current_Timestamp Function
7.1.5. The Exists Function
7.1.6. The Instance-Of Function
7.1.7. The Min and Max Functions
7.1.8. The Previous Function
7.1.8.1. Previous Event per Group
7.1.8.2. Restrictions
7.1.8.3. Comparison to the prior Function
7.1.9. The Prior Function
7.2. Aggregate Functions
7.3. User-Defined Functions
8. EPL Reference: Views
8.1. Window views
8.1.1. Length window (win:length)
8.1.2. Length batch window (win:length_batch)
8.1.3. Time window (win:time)
8.1.4. Externally-timed window (win:ext_timed)
8.1.5. Time batch window (win:time_batch)
8.1.6. Time-Length combination batch window (win:time_length_batch)
8.1.7. Time-Accumulating window (win:time_accum)
8.1.8. Keep-All window (win:keepall)
8.2. Standard view set
8.2.1. Unique (std:unique)
8.2.2. Group-By (std:groupby)
8.2.3. Size (std:size)
8.2.4. Last Event (std:lastevent)
8.3. Statistics views
8.3.1. Univariate statistics (stat:uni)
8.3.2. Regression (stat:linest)
8.3.3. Correlation (stat:correl)
8.3.4. Weighted average (stat:weighted_avg)
8.3.5. Multi-dimensional statistics (stat:cube)
8.4. Extension View Set
8.4.1. Sorted Window View (ext:sort)
8.4.2. Time-Order View (ext:time_order)
9. API Reference
9.1. API Overview
9.2. Engine Instances
9.3. The Administrative Interface
9.3.1. Creating Statements
9.3.2. Receiving Statement Results
9.3.3. Setting a Subscriber Object
9.3.3.1. Row-By-Row Delivery
9.3.3.2. Multi-Row Delivery
9.3.4. Adding Listeners
9.3.5. Using Iterators
9.3.6. Managing Statements
9.3.7. Runtime Engine Configuration
9.4. The Runtime Interface
9.4.1. Event Sender
9.4.2. Receiving Unmatched Events
9.4.3. Emit Facility for Publish-Subscribe
9.5. Events Received from the Engine
9.6. Engine Threading and Concurrency
9.7. Time-Keeping Events
9.8. Time Resolution
9.9. Statement Object Model
9.9.1. Building an Object Model
9.9.2. Building Expressions
9.9.3. Building a Pattern Statement
9.9.4. Building a Select Statement
9.9.5. Building a Create-Variable and On-Set Statement
9.9.6. Building Create-Window, On-Delete and On-Select Statements
9.10. Prepared Statement and Substitution Parameters
10. Configuration
10.1. Programmatic Configuration
10.2. Configuration via XML File
10.3. XML Configuration File
10.4. Configuration Items
10.4.1. Events represented by Java Classes
10.4.1.1. Package of Java Event Classes
10.4.1.2. Event type alias to Java class mapping
10.4.1.3. Non-JavaBean and Legacy Java Event Classes
10.4.1.4. Specifying Event Properties for Java Classes
10.4.1.5. Turning off Code Generation
10.4.1.6. Case Sensitivity and Property Names
10.4.2. Events represented by java.util.Map
10.4.3. Events represented by org.w3c.dom.Node
10.4.3.1. Schema Resource
10.4.3.2. XPath Property
10.4.3.3. Absolute or Deep Property Resolution
10.4.3.4. XPath Variable and Function Resolver
10.4.4. Events represented by Plug-in Event Representations
10.4.4.1. Enabling an Custom Event Representation
10.4.4.2. Adding Plug-in Event Types
10.4.4.3. Setting Resolution URIs
10.4.5. Class and package imports
10.4.6. Cache Settings for Method Invocations
10.4.7. Variables
10.4.8. Relational Database Access
10.4.8.1. Connections obtained via DataSource
10.4.8.2. Connections obtained via DriverManager
10.4.8.3. Connections-level settings
10.4.8.4. Connections lifecycle settings
10.4.8.5. Cache settings
10.4.8.6. Column Change Case
10.4.8.7. SQL Types Mapping
10.4.8.8. Metadata Origin
10.4.9. Engine Settings related to Concurrency and Threading
10.4.9.1. Preserving the order of events delivered to listeners
10.4.9.2. Preserving the order of events for insert-into streams
10.4.9.3. Internal Timer Settings
10.4.10. Engine Settings related to Event Metadata
10.4.10.1. Java Class Property Names and Case Sensitivity
10.4.11. Engine Settings related to View Resources
10.4.11.1. Sharing View Resources between Statements
10.4.12. Engine Settings related to Logging
10.4.12.1. Execution Path Debug Logging
10.4.13. Engine Settings related to Variables
10.4.13.1. Variable Version Release Interval
10.4.14. Engine Settings related to Stream Selection
10.4.14.1. Default Statement Stream Selection
10.4.15. Engine Settings related to Time Source
10.4.15.1. Default Time Source
10.4.16. Revision Event Type
10.4.17. Variant Stream
10.5. Type Names
11. Extension and Plug-in
11.1. Custom View Implementation
11.1.1. Implementing a View Factory
11.1.2. Implementing a View
11.1.3. View Contract
11.1.4. Configuring View Namespace and Name
11.2. Custom Aggregation Functions
11.2.1. Implementing an Aggregation Function
11.2.2. Configuring Aggregation Function Name
11.3. Custom Pattern Guard
11.3.1. Implementing a Guard Factory
11.3.2. Implementing a Guard Class
11.3.3. Configuring Guard Namespace and Name
11.4. Custom Pattern Observer
11.4.1. Implementing an Observer Factory
11.4.2. Implementing an Observer Class
11.4.3. Configuring Observer Namespace and Name
11.5. Custom Event Representation
11.5.1. How It Works
11.5.2. Steps
11.5.3. URI-based Resolution
11.5.4. Example
11.5.4.1. Sample Event Type
11.5.4.2. Sample Event Bean
11.5.4.3. Sample Event Representation
11.5.4.4. Sample Event Bean Factory
12. Examples, Tutorials, Case Studies
12.1. Examples Overview
12.2. Market Data Feed Monitor
12.2.1. Input Events
12.2.2. Computing Rates Per Feed
12.2.3. Detecting a Fall-off
12.2.4. Event generator
12.3. JMS Server Shell and Client
12.3.1. Overview
12.3.2. JMS Messages as Events
12.3.3. JMX for Remote Dynamic Statement Management
12.4. Transaction 3-Event Challenge
12.4.1. The Events
12.4.2. Combined event
12.4.3. Real time summary data
12.4.4. Find problems
12.4.5. Event generator
12.5. J2EE Self-Service Terminal Management
12.5.1. Events
12.5.2. Detecting Customer Check-in Issues
12.5.3. Absence of Status Events
12.5.4. Activity Summary Data
12.5.5. Sample Application for J2EE Application Server
12.5.5.1. Running the Example
12.5.5.2. Building the Example
12.5.5.3. Running the Event Simulator and Receiver
12.6. Assets Moving Across Zones - An RFID Example
12.7. AutoID RFID Reader generating XML documents
12.8. StockTicker
12.9. MatchMaker
12.10. QualityOfService
12.11. LinearRoad
12.12. StockTick RSI
13. Performance
13.1. Performance Results
13.2. Performance Tips
13.2.1. Understand how to tune your Java virtual machine
13.2.2. Compare Esper to other solutions
13.2.3. Select the underlying event rather than individual fields
13.2.4. Prefer stream-level filtering over post-data-window filtering
13.2.5. Reduce the use of arithmetic in expressions
13.2.6. Consider using EventPropertyGetter for fast access to event properties
13.2.7. Consider casting the underlying event
13.2.8. Turn off logging
13.2.9. Disable view sharing
13.2.10. Disable delivery order guarantees
13.2.11. Use a Subscriber Object to Receive Events
13.2.12. Performance, JVM, OS and hardware
13.3. Using the performance kit
13.3.1. How to use the performance kit
13.3.2. How we use the performance kit
14. References
14.1. Reference List
A. Output Reference and Samples
A.1. Introduction and Sample Data
A.2. Output for Un-aggregated and Un-grouped Queries
A.2.1. No Output Rate Limiting
A.2.2. Output Rate Limiting - Default
A.2.3. Output Rate Limiting - Last
A.2.4. Output Rate Limiting - First
A.2.5. Output Rate Limiting - Snapshot
A.3. Output for Fully-aggregated and Un-grouped Queries
A.3.1. No Output Rate Limiting
A.3.2. Output Rate Limiting - Default
A.3.3. Output Rate Limiting - Last
A.3.4. Output Rate Limiting - First
A.3.5. Output Rate Limiting - Snapshot
A.4. Output for Aggregated and Un-grouped Queries
A.4.1. No Output Rate Limiting
A.4.2. Output Rate Limiting - Default
A.4.3. Output Rate Limiting - Last
A.4.4. Output Rate Limiting - First
A.4.5. Output Rate Limiting - Snapshot
A.5. Output for Fully-aggregated and Grouped Queries
A.5.1. No Output Rate Limiting
A.5.2. Output Rate Limiting - Default
A.5.3. Output Rate Limiting - All
A.5.4. Output Rate Limiting - Last
A.5.5. Output Rate Limiting - First
A.5.6. Output Rate Limiting - Snapshot
A.6. Output for Aggregated and Grouped Queries
A.6.1. No Output Rate Limiting
A.6.2. Output Rate Limiting - Default
A.6.3. Output Rate Limiting - All
A.6.4. Output Rate Limiting - Last
A.6.5. Output Rate Limiting - First
A.6.6. Output Rate Limiting - Snapshot
B. Reserved Keywords
Index

Preface

Analyzing and reacting to information in real-time oftentimes requires the development of custom applications. Typically these applications must obtain the data to analyze, filter data, derive information and then indicate this information through some form of presentation or communication. Data may arrive with high frequency requiring high throughput processing. And applications may need to be flexible and react to changes in requirements while the data is processed. Esper is an event stream processor that aims to enable a short development cycle from inception to production for these types of applications.

This document is a resource for software developers who develop event driven applications. It also contains information that is useful for business analysts and system architects who are evaluating Esper.

It is assumed that the reader is familiar with the Java programming language.

This document is relevant in all phases of your software development project: from design to deployment and support.

If you are new to Esper, please follow these steps:

  1. Read the tutorials, case studies and solution patterns available on the Esper public web site at http://esper.codehaus.org

  2. Read Section 1.1, “Introduction to CEP and event stream analysis” if you are new to CEP and ESP (complex event processing, event stream processing)

  3. Read Chapter 2, Event Representations that explains the different ways of representing events to Esper

  4. Read Chapter 3, Processing Model to gain insight into EPL continuous query results

  5. Read Section 4.1, “EPL Introduction” for an introduction to event stream processing via EPL

  6. Read Section 5.1, “Event Pattern Overview” for an overview over event patterns

  7. Then glance over the examples Section 12.1, “Examples Overview”

  8. Finally to test drive Esper performance, read Chapter 13, Performance

Chapter 1. Technology Overview

1.1. Introduction to CEP and event stream analysis

The Esper engine has been developed to address the requirements of applications that analyze and react to events. Some typical examples of applications are:

  • Business process management and automation (process monitoring, BAM, reporting exceptions)

  • Finance (algorithmic trading, fraud detection, risk management)

  • Network and application monitoring (intrusion detection, SLA monitoring)

  • Sensor network applications (RFID reading, scheduling and control of fabrication lines, air traffic)

What these applications have in common is the requirement to process events (or messages) in real-time or near real-time. This is sometimes referred to as complex event processing (CEP) and event stream analysis. Key considerations for these types of applications are throughput, latency and the complexity of the logic required.

  • High throughput - applications that process large volumes of messages (between 1,000 to 100k messages per second)

  • Low latency - applications that react in real-time to conditions that occur (from a few milliseconds to a few seconds)

  • Complex computations - applications that detect patterns among events (event correlation), filter events, aggregate time or length windows of events, join event streams, trigger based on absence of events etc.

The Esper engine was designed to make it easier to build and extend CEP applications.

1.2. CEP and relational databases

Relational databases and the standard query language (SQL) are designed for applications in which most data is fairly static and complex queries are less frequent. Also, most databases store all data on disks (except for in-memory databases) and are therefore optimized for disk access.

To retrieve data from a database an application must issue a query. If an application need the data 10 times per second it must fire the query 10 times per second. This does not scale well to hundreds or thousands of queries per second.

Database triggers can be used to fire in response to database update events. However database triggers tend to be slow and often cannot easily perform complex condition checking and implement logic to react.

In-memory databases may be better suited to CEP applications then traditional relational database as they generally have good query performance. Yet they are not optimized to provide immediate, real-time query results required for CEP and event stream analysis.

1.3. The Esper engine for CEP

The Esper engine works a bit like a database turned upside-down. Instead of storing the data and running queries against stored data, the Esper engine allows applications to store queries and run the data through. Response from the Esper engine is real-time when conditions occur that match queries. The execution model is thus continuous rather then only when a query is submitted.

Esper provides two principal methods or mechanisms to process events: event patterns and event stream queries.

Esper offers an event pattern language to specify expression-based event pattern matching. Underlying the pattern matching engine is a state machine implementation. This method of event processing matches expected sequences of presence or absence of events or combinations of events. It includes time-based correlation of events.

Esper also offers event stream queries that address the event stream analysis requirements of CEP applications. Event stream queries provide the windows, aggregation, joining and analysis functions for use with streams of events. These queries are following the EPL syntax. EPL has been designed for similarity with the SQL query language but differs from SQL in its use of views rather then tables. Views represent the different operations needed to structure data in an event stream and to derive data from an event stream.

Esper provides these two methods as alternatives through the same API.

1.4. Required 3rd Party Libraries

Esper requires the following 3rd-party libraries at runtime:

  • ANTLR is the parser generator used for parsing and parse tree walking of the pattern and EPL syntax. Credit goes to Terence Parr at http://www.antlr.org. The ANTLR license is in the lib directory. The library is required for compile-time only.

  • CGLIB is the code generation library for fast method calls. This open source software is under the Apache license. The Apache 2.0 license is in the lib directory.

  • LOG4J and Apache commons logging are logging components. This open source software is under the Apache license. The Apache 2.0 license is in the lib directory.

Esper requires the following 3rd-party libraries at compile-time and for running the test suite:

  • JUnit is a great unit testing framework. Its license has also been placed in the lib directory. The library is required for build-time only.

  • MySQL connector library is used for testing SQL integration and is required for running the automated test suite.

Chapter 2. Event Representations

2.1. Event Underlying Java Objects

An event is an immutable record of a past occurrence of an action or state change. Event properties capture the state information for an event. An event is represented by either a POJO (plain-old Java object), a java.util.Map or a XML document via org.w3c.dom.Node.

In Esper, an event can be represented by any of the following underlying Java objects:

Table 2.1. Event Underlying Java Objects

Java ClassDescription
java.lang.ObjectAny Java POJO (plain-old java object) with getter methods following JavaBean conventions; Legacy Java classes not following JavaBean conventions can also serve as events .
java.util.MapMap events are key-values pairs
org.w3c.dom.NodeXML document object model (DOM)

2.2. Event Properties

Event properties capture the state information for an event. Event properties be simple as well as indexed, mapped and nested event properties. The table below outlines the different types of properties and their syntax in an event expression. This syntax allows statements to query deep JavaBean objects graphs, XML structures and Map events.

Table 2.2. Types of Event Properties

TypeDescriptionSyntaxExample
SimpleA property that has a single value that may be retrieved.
name
sensorId
IndexedAn indexed property stores an ordered collection of objects (all of the same type) that can be individually accessed by an integer-valued, non-negative index (or subscript).
name[index]
sensor[0]
MappedA mapped property stores a keyed collection of objects (all of the same type).
name('key')
sensor('light')
NestedA nested property is a property that lives within another property of an event.
name.nestedname
sensor.value

Combinations are also possible. For example, a valid combination could be person.address('home').street[0].

If your application uses java.util.Map or XML to represent events, then event property names may themselves contain the dot ('.') character. The backslash ('\') character can be used to escape dot characters in property names, allowing a property name to contain dot characters.

For example, the EPL as shown below expects a property by name part1.part2 to exist on event type MyEvent:

select part1\.part2 from MyEvent

2.3. Dynamic Event Properties

Dynamic (unchecked) properties are event properties that need not be known at statement compilation time. Such properties are resolved during runtime.

The idea behind dynamic properties is that for a given underlying event representation we don't always know all properties in advance. An underlying event may have additional properties that are not known at statement compilation time, that we want to query on. The concept is especially useful for events that represent rich, object-oriented domain models.

The syntax of dynamic properties consists of the property name and a question mark. Indexed, mapped and nested properties can also be dynamic properties:

Table 2.3. Types of Event Properties

TypeSyntax
Dynamic Simple
name?
Dynamic Indexed
name[index]?
Dynamic Mapped
name('key')?
Dynamic Nested
name?.nestedPropertyName

Dynamic properties always return the java.lang.Object type. Also, dynamic properties return a null value if the dynamic property does not exist on events processed at runtime.

As an example, consider an OrderEvent event that provides an "item" property. The "item" property is of type Object and holds a reference to an instance of either a Service or Product.

Assume that both Service and Product classes provide a property named "price". Via a dynamic property we can specify a query that obtains the price property from either object (Service or Product):

select item.price? from OrderEvent

As a second example, assume that the Service class contains a "serviceName" property that the Product class does not possess. The following query returns the value of the "serviceName" property for Service objects. It returns a null-value for Product objects that do not have the "serviceName" property:

select item.serviceName? from OrderEvent

Consider the case where OrderEvent has multiple implementation classes, some of which have a "timestamp" property. The next query returns the timestamp property of those implementations of the OrderEvent interface that feature the property:

select timestamp? from OrderEvent

The query as above returns a single column named "timestamp?" of type Object.

When dynamic properties are nested, then all properties under the dynamic property are also considered dynamic properties. In the below example the query asks for the "direction" property of the object returned by the "detail" dynamic property:

select detail?.direction from OrderEvent
// equivalent to 
select detail?.direction? from OrderEvent

The functions that are often useful in conjunction with dynamic properties are:

  • The cast function casts the value of a dynamic property (or the value of an expression) to a given type.

  • The exists function checks whether a dynamic property exists. It returns true if the event has a property of that name, or false if the property does not exist on that event.

  • The instanceof function checks whether the value of a dynamic property (or the value of an expression) is of any of the given types.

Dynamic event properties work with all event representations outlined next: Java objects, Map-based and XML DOM-based events.

2.4. Plain-Old Java Object Events

Plain-old Java object events are object instances that expose event properties through JavaBeans-style getter methods. Events classes or interfaces do not have to be fully compliant to the JavaBean specification; however for the Esper engine to obtain event properties, the required JavaBean getter methods must be present.

Esper supports JavaBeans-style event classes that extend a superclass or implement one or more interfaces. Also, Esper event pattern and EPL statements can refer to Java interface classes and abstract classes.

Classes that represent events should be made immutable. As events are recordings of a state change or action that occurred in the past, the relevant event properties should not be changeable. However this is not a hard requirement and the Esper engine accepts events that are mutable as well.

The hashCode and equals methods do not need to be implemented. The implementation of these methods by a Java event class does not affect the behavior of the engine in any way.

Please see Chapter 10, Configuration on options for naming event types represented by Java object event classes.

2.4.1. Java Object Event Properties

As outlined earlier, the different property types are supported by the standard JavaBeans specification, and some of which are uniquely supported by Esper:

  • Simple properties have a single value that may be retrieved. The underlying property type might be a Java language primitive (such as int, a simple object (such as a java.lang.String), or a more complex object whose class is defined either by the Java language, by the application, or by a class library included with the application.

  • Indexed - An indexed property stores an ordered collection of objects (all of the same type) that can be individually accessed by an integer-valued, non-negative index (or subscript). Alternatively, the entire set of values may be retrieved using an array.

  • Mapped - As an extension to standard JavaBeans APIs, Esper considers any property that accepts a String-valued key a mapped property.

  • Nested - A nested property is a property that lives within another Java object which itself is a property of an event.

Assume there is an EmployeeEvent event class as shown below. The mapped and indexed properties in this example return Java objects but could also return Java language primitive types (such as int or String). The Address object and Employee objects can themselves have properties that are nested within them, such as a streetName in the Address object or a name of the employee in the Employee object.

public class EmployeeEvent {
	public String getFirstName();
	public Address getAddress(String type);
	public Employee getSubordinate(int index);
	public Employee[] getAllSubordinates();
}

Simple event properties require a getter-method that returns the property value. In this example, the getFirstName getter method returns the firstName event property of type String.

Indexed event properties require either one of the following getter-methods. A method that takes an integer-type key value and returns the property value, such as the getSubordinate method. Or a method that returns an array-type such as the getSubordinates getter method, which returns an array of Employee. In an EPL or event pattern statement, indexed properties are accessed via the property[index] syntax.

Mapped event properties require a getter-method that takes a String-typed key value and returns the property value, such as the getAddress method. In an EPL or event pattern statement, mapped properties are accessed via the property('key') syntax.

Nested event properties require a getter-method that returns the nesting object. The getAddress and getSubordinate methods are mapped and indexed properties that return a nesting object. In an EPL or event pattern statement, nested properties are accessed via the property.nestedProperty syntax.

All event pattern and EPL statements allow the use of indexed, mapped and nested properties (or a combination of these) anywhere where one or more event property names are expected. The below example shows different combinations of indexed, mapped and nested properties in filters of event pattern expressions:

every EmployeeEvent(firstName='myName')
every EmployeeEvent(address('home').streetName='Park Avenue')
every EmployeeEvent(subordinate[0].name='anotherName')
every EmployeeEvent(allSubordinates[1].name='thatName')
every EmployeeEvent(subordinate[0].address('home').streetName='Water Street')

Similarly, the syntax can be used in EPL statements in all places where an event property name is expected, such as in select lists, where-clauses or join criteria.

select firstName, address('work'), subordinate[0].name, subordinate[1].name
from EmployeeEvent
where address('work').streetName = 'Park Ave'

Property names follows Java standards: the class java.beans.Introspector and method getBeanInfo returns the property names as derived from the name of getter methods. In addition, Esper configuration provides a flag to turn off case-sensitive property names. A sample list of getter methods and property names is:

Table 2.4. JavaBeans-style Getter Methods and Property Names

MethodProperty NameExample
getPrice()price
select price from MyEvent
getNAME()NAME
select NAME from MyEvent
getItemDesc()itemDesc
select itemDesc from MyEvent
getQ()q
select q from MyEvent
getQN()QN
select QN from MyEvent
getqn()qn
select qn from MyEvent
gets()s
select s from MyEvent

Constants are public static final fields in Java that may also participate in expressions of all kinds, as this example shows:

select * from MyEvent where property=MyConstantClass.FIELD_VALUE

Event properties that are enumeration values can be compared by their enumeration value:

select * from MyEvent where enumProp=EnumClass.ENUM_VALUE_1

Alternatively, a static method may be employed on a class, such as the enumeration class 'EnumClass' as below:

select * from MyEvent where enumProp=EnumClass.valueOf('ENUM_VALUE_1')

Instance methods may also be invoked on event instances by specifying a stream name, as shown below:

select myevent.computeSomething() as result from MyEvent as myevent

Java classes that do not follow JavaBean conventions, such as legacy Java classes that expose public fields, or methods not following naming conventions, require additional configuration. Via configuration it is also possible to control case sensitivity in property name resolution. The relevant section in the chapter on configuration is Section 10.4.1.3, “Non-JavaBean and Legacy Java Event Classes”.

2.5. java.util.Map Events

Events can also be represented by objects that implement the java.util.Map interface. Event properties of Map events are the values in the map accessible through the get method exposed by the java.util.Map interface.

The engine can process java.util.Map events via the sendEvent(Map map, String eventTypeAlias) method on the EPRuntime interface. Entries in the Map represent event properties. Keys must be of type java.util.String for the engine to be able to look up event property names specified by pattern or EPL statements.

Map event properties can be of any type. Map event properties that are Java application objects or that are of type java.util.Map offer additional power:

  • Properties that are Java application objects can be queried via the nested, indexed, mapped and dynamic property syntax as outlined earlier.

  • Properties that are of type Map allow Maps to be nested arbitrarily deep and thus can be used to represent complex domain information. The nested, indexed, mapped and dynamic property syntax can be used to query Maps within Maps..

In order to use Map events, the event type name and property names and types must be made known to the engine via Configuration. Please see the examples in Section 10.4.2, “Events represented by java.util.Map”.

The code snippet below creates and processes a Map event. The example assumes the CarLocationUpdateEvent event type alias has been configured.

Map event = new HashMap();
event.put("carId", carId);
event.put("direction", direction);
epRuntime.sendEvent(event, "CarLocUpdateEvent");

The CarLocUpdateEvent can now be used in a statement:

select carId from CarLocUpdateEvent.win:time(1 min) where direction = 1

The engine can also query Java objects as values in a Map event via the nested property syntax. Thus Map events can be used to aggregate multiple data structures into a single event and query the composite information in a convenient way. The example below demonstrates a Map event with a transaction and an account object.

Map event = new HashMap();
event.put("txn", txn);
event.put("account", account);
epRuntime.sendEvent(event, "TxnEvent");

An example statement could look as follows.

select account.id, account.rate * txn.amount 
from TxnEvent.win:time(60 sec) 
group by account.id

2.5.1. Map-Within-Map Nested Events

Strongly-typed nested Map-within-Map events can be used to build rich, type-safe event types on the fly. Use the addNestableEventTypeAlias method on Configuration or ConfigurationOperations for initialization-time and runtime-time type definition.

Noteworthy points are:

  • JavaBean (POJO) objects can also appear as properties in Map-within-Map.

  • There is no limit to the number of nesting levels.

  • Dynamic properties can be used to query Map-within-Map keys that may not be known in advance.

  • The engine returns a null value for properties for which the access path into the nested structure cannot be followed where map entries do not exist.

For demonstration, in this example our top-level event type is an AccountUpdate event, which has an UpdatedField structure as a property. Inside the UpdatedField structure the example defines various fields, as well as a property by name 'history' that holds a JavaBean class 'UpdateHistory' to represent the update history for the account. The code snippet to define the event type is thus:

Map<String, Object> updatedFieldDef = new HashMap<String, Object>();
updatedFieldDef.put("name", String.class);
updatedFieldDef.put("addressLine1", String.class);
updatedFieldDef.put("history", UpdateHistory.class);

Map<String, Object> accountUpdateDef = new HashMap<String, Object>();
accountUpdateDef.put("accountId", long.class);
accountUpdateDef.put("fields", updatedFieldDef);

epService.getEPAdministrator().getConfiguration().
    addNestableEventTypeAlias("AccountUpdate", accountUpdateDef);

The next code snippet populates a sample event and sends the event into the engine:

Map<String, Object> updatedField = new HashMap<String, Object>();
updatedField.put("name", "Joe Doe");
updatedField.put("addressLine1", "40 Popular Street");
updatedField.put("history", new UpdateHistory());

Map<String, Object> accountUpdate = new HashMap<String, Object>();
accountUpdate.put("accountId", 10009901);
accountUpdate.put("fields", updatedField);

epService.getEPRuntime().sendEvent(accountUpdate, "AccountUpdate");

Last, a sample query to interrogate AccountUpdate events is as follows:

select accountId, fields.name, fields.addressLine1, fields.history.lastUpdate
from AccountUpdate

Note that type information for nested maps is only available to the immediately selecting stream. For example, the second select-query does not work:

insert into MyStream select fields from NestedMapEvent
// this does not work ... instead select the individual fields in the insert-into statement
select fields.name from MyStream 

2.6. org.w3c.dom.Node XML Events

Events can also be represented as org.w3c.dom.Node instances and send into the engine via the sendEvent method on EPRuntime. Please note that configuration is required for allowing the engine to map the event type alias to Node element names. See Chapter 10, Configuration.

Esper allows configuring XPath expressions as event properties. You can specify arbitrary XPath functions or expressions and provide a property name by which their result values will be available for use in expressions. For XML documents that follow an XML schema, Esper can load and interrogate your schema and validate event property names and types against the schema information.

Nested, mapped and indexed event properties are also supported in expressions against org.w3c.dom.Node events. Thus XML trees can conveniently be interrogated using the existing event property syntax for querying JavaBean objects, JavaBean object graphs or java.util.Map events.

Let's look at how a sample XML document could be queried, given the sample XML below.

<?xml version="1.0" encoding="UTF-8"?>
<Sensor>
	<ID>urn:epc:1:4.16.36<ID>
	<Observation Command="READ_PALLET_TAGS_ONLY">
		<ID>00000001<ID>
		<Tag>
			<ID>urn:epc:1:2.24.400<ID>
		</Tag>
		<Tag>
			<ID>urn:epc:1:2.24.401<ID>
		</Tag>
	</Observation>
</Sensor>

To configure the engine for processing Sensor documents, simply configure a SensorEvent event type alias for the Sensor element name via Configuration. Now the document can be queried as below.

select ID, Observation.ID, Observation.Command, Observation.Tag[0], countTags
from SensorEvent.win:time(30 sec)

The equivalent XPath expressions to each of the properties are listed below.

  • The equivalent XPath expression to Observeration.ID is /Sensor/Observation/ID

  • The equivalent XPath expression to Observeration.Command is /Sensor/Observation/@Command

  • The equivalent XPath expression to Observeration.Tag[0] is /Sensor/Observation/Tag[position() = 1]

  • The equivalent XPath expression to countTags is count(/Sensor/Observation/Tag) for returning a count of tag elements. This assumes the countTags property has been configured as an XPath property.

By specifying an event property such below:

nestedElement.mappedElement('key').indexedElement[1]

The equivalent XPath expression is as follows:

/simpleEvent/nestedElement/mappedElement[@id='key']/indexedElement[position() = 2]

2.7. Additional Event Representations

Part of the extension and plug-in features of Esper is an event representation API. This set of classes allow an application to create new event types and event instances based on information available elsewhere, statically or dynamically at runtime when EPL statements are created. Please see Section 11.5, “Custom Event Representation” for details.

Creating a plug-in event representation can be useful when your application has existing Java classes that carry event metadata and event property values and your application does not want to (or cannot) extract or transform such event metadata and event data into one of the built-in event representations (POJO Java objects, Map or XML DOM).

Further use of a plug-in event representation is to provide a faster or short-cut access path to event data. For example, access to event data stored in an XML format through the Streaming API for XML (StAX) is known to be very efficient. A plug-in event representation can also provide network lookup and dynamic resolution of event type and dynamic sourcing of event instances.

Currently, EsperIO provides the following additional event representations:

  • Apache Axiom: Streaming API for XML (StAX) implementation

Please see the EsperIO documentation for details on the above.

The chapter on Section 11.5, “Custom Event Representation” explains how to create your own custom event representation.

2.8. Updating and Versioning Events

To summarize, an event is an immutable record of a past occurrence of an action or state change, and event properties contain useful information about an event.

The length of time an event is of interest to the event processing engine (retention time) depends on your EPL statements, and especially the data window, pattern and output rate limiting clauses of your statements.

During the retention time of an event more information about the event may become available, such as additional properties or changes to existing properties. Esper provides the concept of revision event type to handle such situations. A revision event type instructs the engine that new versions of an existing event are to be processed that update, amend or add to an existing event.

Revision event types work together with the named window feature of the engine: A named window provides an explicit expiration policy for event instances that can be updated, thereby allowing the engine to retain only those versions that are relevant to any retained event and discarding updates to events not retained.

Please see Section 4.16.7, “Updating and Versioning Events in Named Windows” for further instructions and examples.

Note that patterns do not reflect changes to past events. For the temporal nature of patterns, any changes to events that were observed in the past do not reflect upon current pattern state.

Chapter 3. Processing Model

3.1. Introduction

The Esper processing model is continuous: Update listeners to statements receive updated data as soon as the engine processes events for that statement, according to the statement's choice of event streams, views, filters and output rates.

As outlined in Chapter 9, API Reference the interface for listeners is com.espertech.esper.client.UpdateListener. Implementations must provide a single update method that the engine invokes when results become available:

The engine provides statement results to update listeners by placing results in com.espertech.esper.event.EventBean instances. A typical listener implementation queries the EventBean instances via getter methods to obtain the statement-generated results.

The get method on the EventBean interface can be used to retrieve result columns by name. The property name supplied to the get method can also be used to query nested, indexed or array properties of object graphs as discussed in more detail in Chapter 2, Event Representations.

The getUnderlying method on the EventBean interface allows update listeners to obtain the underlying event object. For wildcard selects, the underlying event is the event object that was sent into the engine via the sendEvent method. For joins and select clauses with expressions, the underlying object implements java.util.Map.

3.2. Insert Stream

In this section we look at the output of a very simple EPL statement. The statement selects an event stream without using a data window and without applying any filtering, as follows:

select * from Withdrawal

This statement selects all Withdrawal events. Every time the engine processes an event of type Withdrawal or any sub-type of Withdrawal, it invokes all update listeners, handing the new event to each of the statement's listeners.

The term insert stream denotes the new events arriving, and entering a data window or aggregation. The insert stream in this example is the stream of arriving Withdrawal events, and is posted to listeners as new events.

The diagram below shows a series of Withdrawal events 1 to 6 arriving over time. The number in parenthesis is the withdrawal amount, an event property that is used in the examples that discuss filtering.

Output example for a simple statement

Figure 3.1. Output example for a simple statement

The example statement above results in only new events and no old events posted by the engine to the statement's listeners.

3.3. Insert and Remove Stream

A length window instructs the engine to only keep the last N events for a stream. The next statement applies a length window onto the Withdrawal event stream. The statement serves to illustrate the concept of data window and events entering and leaving a data window:

select * from Withdrawal.win:length(5)

The size of this statement's length window is five events. The engine enters all arriving Withdrawal events into the length window. When the length window is full, the oldest Withdrawal event is pushed out the window. The engine indicates to listeners all events entering the window as new events, and all events leaving the window as old events.

While the term insert stream denotes new events arriving, the term remove stream denotes events leaving a data window, or changing aggregation values. In this example, the remove stream is the stream of Withdrawal events that leave the length window, and such events are posted to listeners as old events.

The next diagram illustrates how the length window contents change as events arrive and shows the events posted to an update listener.

Output example for a length window

Figure 3.2. Output example for a length window

As before, all arriving events are posted as new events to listeners. In addition, when event W1 leaves the length window on arrival of event W6, it is posted as an old event to listeners.

Similar to a length window, a time window also keeps the most recent events up to a given time period. A time window of 5 seconds, for example, keeps the last 5 seconds of events. As seconds pass, the time window actively pushes the oldest events out of the window resulting in one or more old events posted to update listeners.

Note: By default the engine only delivers the insert stream to listeners and observers. EPL supports optional istream, irstream and rstream keywords on select-clauses and on insert-into clauses to control which stream to deliver, see Section 4.3.7, “Selecting insert and remove stream events”. There is also a related, engine-wide configuration setting described in Section 10.4.14, “Engine Settings related to Stream Selection”.

3.4. Filters and Where-clauses

Filters to event streams allow filtering events out of a given stream before events enter a data window. The statement below shows a filter that selects Withdrawal events with an amount value of 200 or more.

select * from Withdrawal(amount>=200).win:length(5)

With the filter, any Withdrawal events that have an amount of less then 200 do not enter the length window and are therefore not passed to update listeners. Filters are discussed in more detail in Section 4.4.1, “Filter-based Event Streams” and Section 5.4, “Filter Expressions In Patterns”.

Output example for a statement with an event stream filter

Figure 3.3. Output example for a statement with an event stream filter

The where-clause and having-clause in statements eliminate potential result rows at a later stage in processing, after events have been processed into a statement's data window or other views.

The next statement applies a where-clause to Withdrawal events. Where-clauses are discussed in more detail in Section 4.5, “Specifying Search Conditions: the Where Clause”.

select * from Withdrawal.win:length(5) where amount >= 200

The where-clause applies to both new events and old events. As the diagram below shows, arriving events enter the window however only events that pass the where-clause are handed to update listeners. Also, as events leave the data window, only those events that pass the conditions in the where-clause are posted to listeners as old events.

Output example for a statement with where-clause

Figure 3.4. Output example for a statement with where-clause

The where-clause can contain complex conditions while event stream filters are more restrictive in the type of filters that can be specified. The next statement's where-clause applies the ceil function of the java.lang.Math Java library class in the where clause. The insert-into clause makes the results of the first statement available to the second statement:

insert into WithdrawalFiltered select * from Withdrawal where Math.ceil(amount) >= 200

select * from WithdrawalFiltered

3.5. Time Windows

In this section we explain the output model of statements employing a time window view and a time batch view.

3.5.1. Time Window

A time window is a moving window extending to the specified time interval into the past based on the system time. Time windows enable us to limit the number of events considered by a query, as do length windows.

As a practical example, consider the need to determine all accounts where the average withdrawal amount per account for the last 4 seconds of withdrawals is greater then 1000. The statement to solve this problem is shown below.

select account, avg(amount) 
from Withdrawal.win:time(4 sec) 
group by account
having amount > 1000

The next diagram serves to illustrate the functioning of a time window. For the diagram, we assume a query that simply selects the event itself and does not group or filter events.

select * from Withdrawal.win:time(4 sec)

The diagram starts at a given time t and displays the contents of the time window at t + 4 and t + 5 seconds and so on.

Output example for a statement with a time window

Figure 3.5. Output example for a statement with a time window

The activity as illustrated by the diagram:

  1. At time t + 4 seconds an event W1 arrives and enters the time window. The engine reports the new event to update listeners.

  2. At time t + 5 seconds an event W2 arrives and enters the time window. The engine reports the new event to update listeners.

  3. At time t + 6.5 seconds an event W3 arrives and enters the time window. The engine reports the new event to update listeners.

  4. At time t + 8 seconds event W1 leaves the time window. The engine reports the event as an old event to update listeners.

3.5.2. Time Batch

The time batch view buffers events and releases them every specified time interval in one update. Time windows control the evaluation of events, as does the length batch window.

The next diagram serves to illustrate the functioning of a time batch view. For the diagram, we assume a simple query as below:

select * from Withdrawal.win:time_batch(4 sec)

The diagram starts at a given time t and displays the contents of the time window at t + 4 and t + 5 seconds and so on.

Output example for a statement with a time batch view

Figure 3.6. Output example for a statement with a time batch view

The activity as illustrated by the diagram:

  1. At time t + 1 seconds an event W1 arrives and enters the batch. No call to inform update listeners occurs.

  2. At time t + 3 seconds an event W2 arrives and enters the batch. No call to inform update listeners occurs.

  3. At time t + 4 seconds the engine processes the batched events and a starts a new batch. The engine reports events W1 and W2 to update listeners.

  4. At time t + 6.5 seconds an event W3 arrives and enters the batch. No call to inform update listeners occurs.

  5. At time t + 8 seconds the engine processes the batched events and a starts a new batch. The engine reports the event W3 as new data to update listeners. The engine reports the events W1 and W2 as old data (prior batch) to update listeners.

3.6. Batch Windows

The built-in data windows that act on batches of events are the win:time_batch and the win:length_batch views. The win:time_batch data window collects events arriving during a given time interval and posts collected events as a batch to listeners at the end of the time interval. The win:length_batch data window collects a given number of events and posts collected events as a batch to listeners when the given number of events has collected.

Let's look at how a time batch window may be used:

select account, amount from Withdrawal.win:time_batch(1 sec)

The above statement collects events arriving during a one-second interval, at the end of which the engine posts the collected events as new events (insert stream) to each listener. The engine posts the events collected during the prior batch as old events (remove stream). The engine starts posting events to listeners one second after it receives the first event and thereon.

For statements containing aggregation functions and/or a group by clause, the engine posts consolidated aggregation results for an event batch. For example, consider the following statement:

select sum(amount) as mysum from Withdrawal.win:time_batch(1 sec)

Note that output rate limiting also generates batches of events following the output model as discussed here.

3.7. Aggregation and Grouping

3.7.1. Insert and Remove Stream

Statements that aggregate events via aggregation functions also post remove stream events as aggregated values change.

Consider the following statement that alerts when 2 Withdrawal events have been received:

select count(*) as mycount from Withdrawal having count(*) = 2

When the engine encounters the second withdrawal event, the engine posts a new event to update listeners. The value of the "mycount" property on that new event is 2. Additionally, when the engine encounters the third Withdrawal event, it posts an old event to update listeners containing the prior value of the count. The value of the "mycount" property on that old event is also 2.

The istream or rstream keyword can be used to eliminate either new events or old events posted to listeners. The next statement uses the istream keyword causing the engine to call the listener only once when the second Withdrawal event is received:

select istream count(*) as mycount from Withdrawal having count(*) = 2

3.7.2. Output for Aggregation and Group-By

Following SQL (Standard Query Language) standards for queries against relational databases, the presence or absence of aggregation functions and the presence or absence of the group by clause dictates the number of rows posted by the engine to listeners. The next sections outline the output model for batched events under aggregation and grouping. The examples also apply to data windows that don't batch events and post results continously as events arrive or leave data windows. The examples also apply to patterns providing events when a complete pattern matches.

In summary, as in SQL, if your query only selects aggregation values, the engine provides one row of aggregated values. It provides that row every time the aggregation is updated (insert stream), which is when events arrive or a batch of events gets processed, and when the events leave a data window or a new batch of events arrives. The remove stream then consists of prior aggregation values.

Also as in SQL, if your query selects non-aggregated values along with aggregation values in the select clause, the engine provides a row per event. The insert stream then consists of the aggregation values at the time the event arrives, while the remove stream is the aggregation value at the time the event leaves a data window, if any is defined in your query.

The documentation provides output examples for query types in Appendix A, Output Reference and Samples, and the next sections outlines each query type.

3.7.2.1. Un-aggregated and Un-grouped

An example statement for the un-aggregated and un-grouped case is as follows:

select * from Withdrawal.win:time_batch(1 sec)

At the end of a time interval, the engine posts to listeners one row for each event arriving during the time interval.

The appendix provides a complete example including input and output events over time at Section A.2, “Output for Un-aggregated and Un-grouped Queries”

3.7.2.2. Fully Aggregated and Un-grouped

If your statement only selects aggregation values and does not group, your statement may look as the example below:

select sum(amount) 
from Withdrawal.win:time_batch(1 sec)

At the end of a time interval, the engine posts to listeners a single row indicating the aggregation result. The aggregation result aggregates all events collected during the time interval.

The appendix provides a complete example including input and output events over time at Section A.3, “Output for Fully-aggregated and Un-grouped Queries”

3.7.2.3. Aggregated and Un-Grouped

If your statement selects non-aggregated properties and aggregation values, and does not group, your statement may be similar to this statement:

select account, sum(amount) 
from Withdrawal.win:time_batch(1 sec)

At the end of a time interval, the engine posts to listeners one row per event. The aggregation result aggregates all events collected during the time interval.

The appendix provides a complete example including input and output events over time at Section A.4, “Output for Aggregated and Un-grouped Queries”

3.7.2.4. Fully Aggregated and Grouped

If your statement selects aggregation values and all non-aggregated properties in the select clause are listed in the group by clause, then your statement may look similar to this example:

select account, sum(amount) 
from Withdrawal.win:time_batch(1 sec) 
group by account

At the end of a time interval, the engine posts to listeners one row per unique account number. The aggregation result aggregates per unique account.

The appendix provides a complete example including input and output events over time at Section A.5, “Output for Fully-aggregated and Grouped Queries”

3.7.2.5. Aggregated and Grouped

If your statement selects non-aggregated properties and aggregation values, and groups only some properties using the group by clause, your statement may look as below:

select account, accountName, sum(amount) 
from Withdrawal.win:time_batch(1 sec) 
group by account

At the end of a time interval, the engine posts to listeners one row per event. The aggregation result aggregates per unique account.

The appendix provides a complete example including input and output events over time at Section A.6, “Output for Aggregated and Grouped Queries”

3.8. EventBean Query Results

The engine posts events to UpdateListener implementations as com.espertech.esper.event.EventBean instances. The EventBean represents a row (event) in your continuous query's result set.

Use the iterator method on EPStatement statements to poll or read data out of statements, if you require read-based access to statement result sets. Statement iterators also return EventBean instances.

The EventBean interface offers property type metadata via the getEventType method returning an EventType. The EventType provides property name, property type and underlying type information. This information can be useful to dynamically interrogate query results. The underlying event that an EventBean represents can be obtained via the getUnderlying method. Please see Chapter 2, Event Representations for more information on different event underlying objects.

Consider a statement that returns the symbol, count of events per symbol and average price per symbol for tick events. Our sample statement may declare a fully-qualified Java class name as the event type: org.sample.StockTickEvent. Assume that this class exists and exposes a symbol property of type String, and a price property of type (Java primitive) double.

select symbol, avg(price) as avgprice, count(*) as mycount 
from org.sample.StockTickEvent 
group by symbol

The next table summarizes the property names and types as posted by the statement above:

Table 3.1. Properties offered by sample statement aggregating price

NameTypeDescriptionJava code snippet
symboljava.lang.StringValue of symbol event property
eventBean.get("symbol")
avgpricejava.lang.DoubleAverage price per symbol
eventBean.get("avgprice")
mycountjava.lang.LongNumber of events per symbol
eventBean.get("mycount")

A code snippet out of a possible UpdateListener implementation to this statement may look as below:

String symbol = (String) newEvents[0].get("symbol");
Double price= (Double) newEvents[0].get("avgprice");
Long count= (Long) newEvents[0].get("mycount");

The engine supplies the boxed java.lang.Double and java.lang.Long types as property values rather then primitive Java types. This is because aggregated values can return a null value to indicate that no data is available for aggregation. Also, in a select statement that computes expressions, the underlying event objects to EventBean instances are of type java.util.Map.

Consider the next statement that specifies a wildcard selecting the same type of event:

select * from org.sample.StockTickEvent where price > 100

The property names and types provided by an EventBean query result row, as posted by the statement above are as follows:

Table 3.2. Properties offered by sample wildcard-select statement

NameTypeDescriptionJava code snippet
symboljava.lang.StringValue of symbol event property
eventBean.get("symbol")
pricedoubleValue of price event property
eventBean.get("price")

As an alternative to querying individual event properties via the get methods, the getUnderlying method on EventBean returns the underlying object representing the query result. In the sample statement that features a wildcard-select, the underlying event object is of type org.sample.StockTickEvent:

StockTickEvent tick = (StockTickEvent) newEvents[0].getUnderlying();

Chapter 4. EPL Reference: Clauses

4.1. EPL Introduction

The Event Processing Language (EPL) is a SQL-like language with SELECT, FROM, WHERE, GROUP BY, HAVING and ORDER BY clauses. Streams replace tables as the source of data with events replacing rows as the basic unit of data. Since events are composed of data, the SQL concepts of correlation through joins, filtering and aggregation through grouping can be effectively leveraged. The INSERT INTO clause is recast as a means of forwarding events to other streams for further downstream processing. External data accessible through JDBC may be queried and joined with the stream data. Additional clauses such as the PATTERN and OUTPUT clauses are also available to provide the missing SQL language constructs specific to event processing.

EPL statements are used to derive and aggregate information from one or more streams of events, and to join or merge event streams. This section outlines EPL syntax. It also outlines the built-in views, which are the building blocks for deriving and aggregating information from event streams.

EPL statements contain definitions of one or more views. Similar to tables in a SQL statement, views define the data available for querying and filtering. Some views represent windows over a stream of events. Other views derive statistics from event properties, group events or handle unique event property values. Views can be staggered onto each other to build a chain of views. The Esper engine makes sure that views are reused among EPL statements for efficiency.

The built-in set of views is:

  1. Data window views: win:length, win:length_batch, win:time, win:time_batch, win:time_length_batch, win:time_accum, win:ext_timed, ext:sort_window, ext:time_order, std:unique, std:groupby, std:lastevent

  2. Views that derive statistics: std:size, stat:uni, stat:linest, stat:correl, stat:weighted_avg, stat:cube

EPL provides the concept of named window. Named windows are data windows that can be inserted-into and deleted-from by one or more statements, and that can queried by one or more statements. Named windows have a global character, being visible and shared across an engine instance beyond a single statement. Use the CREATE WINDOW clause to create named windows. Use the INSERT INTO clause to insert data into a named window, the ON DELETE clause to remove events from a named window, and the ON SELECT clause to perform a non-continuous fire-once query on a named window. Finally, the name of the named window can occur in a statement's FROM clause to query a named window or include the named window in a join or subquery.

Variables can come in handy to parameterize statements and change parameters on-the-fly and in response to events. Variables can be used in an expression anywhere in a statement as well as in the output clause for dynamic control of output rates.

Esper can be extended by plugging-in custom developed views and aggregation functions.

4.2. EPL Syntax

EPL queries are created and stored in the engine, and publish results to listeners as events are received by the engine or timer events occur that match the criteria specified in the query. Events can also be obtained from running EPL queries via the safeIterator and iterator methods that provide a pull-data API.

The select clause in an EPL query specifies the event properties or events to retrieve. The from clause in an EPL query specifies the event stream definitions and stream names to use. The where clause in an EPL query specifies search conditions that specify which event or event combination to search for. For example, the following statement returns the average price for IBM stock ticks in the last 30 seconds.

select avg(price) from StockTick.win:time(30 sec) where symbol='IBM'

EPL queries follow the below syntax. EPL queries can be simple queries or more complex queries. A simple select contains only a select clause and a single stream definition. Complex EPL queries can be build that feature a more elaborate select list utilizing expressions, may join multiple streams, may contain a where clause with search conditions and so on.

[insert into insert_into_def]
select select_list
from stream_def [as name] [, stream_def [as name]] [,...]
[where search_conditions]
[group by grouping_expression_list]
[having grouping_search_conditions]
[output output_specification]
[order by order_by_expression_list]

4.2.1. Specifying Time Periods

Time-based windows as well as pattern observers and guards take a time period as a parameter. Time periods follow the syntax below.

time-period : [day-part] [hour-part] [minute-part] [seconds-part] [milliseconds-part]

day-part : number ("days" | "day")
hour-part : number ("hours" | "hour")
minute-part : number ("minutes" | "minute" | "min")
seconds-part : number ("seconds" | "second" | "sec")
milliseconds-part : number ("milliseconds" | "millisecond" | "msec")

Some examples of time periods are:

10 seconds
10 minutes 30 seconds
20 sec 100 msec
1 day 2 hours 20 minutes 15 seconds 110 milliseconds
0.5 minutes

4.2.2. Using Comments

Comments can appear anywhere in the EPL or pattern statement text where whitespace is allowed. Comments can be written in two ways: slash-slash (// ...) comments and slash-star (/* ... */) comments.

Slash-slash comments extend to the end of the line:

// This comment extends to the end of the line.
// Two forward slashes with no whitespace between them begin such comments.

select * from MyEvent  // this is a slash-slash comment

// All of this text together is a valid statement.

Slash-star comments can span multiple lines:

/* This comment is a "slash-star" comment that spans multiple lines.
 * It begins with the slash-star sequence with no space between the '/' and '*' characters.
 * By convention, subsequent lines can begin with a star and are aligned, but this is 
 * not required.
 */		
select * from MyEvent  /* this also works */

Comments styles can also be mixed:

select field1, // first comment
  /* second comment*/  field2
  from MyEvent

4.2.3. Reserved Keywords

Certain words such as select, delete or set are reserved and may not be used as identifiers. Please consult Appendix B, Reserved Keywords for the list of reserved keywords and permitted keywords.

Names of built-in functions and certain auxiliary keywords are permitted as event property names and in the rename syntax of the select clause. For example, count is acceptable.

Consider the example below, which assumes that 'last' is an event property of MyEvent:

// valid
select last, count(*) as count from MyEvent

This example shows an incorrect use of a reserved keyword:

// invalid
select insert from MyEvent

EPL does not offer an escape syntax for reserved keywords.

4.3. Choosing Event Properties And Events: the Select Clause

The select clause is required in all EPL statements. The select clause can be used to select all properties via the wildcard *, or to specify a list of event properties and expressions. The select clause defines the event type (event property names and types) of the resulting events published by the statement, or pulled from the statement via the iterator methods.

The select clause also offers optional istream, irstream and rstream keywords to control whether input stream, remove stream or input and remove stream events are posted to UpdateListener instances and observers to a statement. By default, the engine provides only the insert stream to listener and observers. See Section 10.4.14, “Engine Settings related to Stream Selection” on how to change the default.

The syntax for the select clause is summarized below.

select [istream | irstream | rstream] * | expression_list ... 

The istream keyword is the default, and indicates that the engine only delivers insert stream events to listeners and observers. The irstream keyword indicates that the engine delivers both insert and remove stream. Finally, the rstream keyword tells the engine to deliver only the remove stream.

4.3.1. Choosing all event properties: select *

The syntax for selecting all event properties in a stream is:

select * from