www.espertech.comDocumentation

Chapter 11. EPL Reference: Enumeration Methods

11.1. Overview
11.2. Example Events
11.3. How to Use
11.3.1. Syntax
11.3.2. Introductory Examples
11.3.3. Index and Size Formal Parameters
11.3.4. Input, Output and Limitations
11.4. Inputs
11.4.1. Subquery Results
11.4.2. Named Window
11.4.3. Table
11.4.4. Event Property and Insert-Into With @eventbean
11.4.5. Event Aggregation Function
11.4.6. Prev, Prevwindow and Prevtail Single-Row Functions as Input
11.4.7. Single-Row Function, User-Defined Function and Enum Types
11.4.8. Declared Expression
11.4.9. Variables
11.4.10. Substitution Parameters
11.4.11. Match-Recognize Group Variable
11.4.12. Pattern Repeat and Repeat-Until Operators
11.5. Example
11.6. Reference
11.6.1. Aggregate
11.6.2. AllOf
11.6.3. AnyOf
11.6.4. ArrayOf
11.6.5. Average
11.6.6. CountOf
11.6.7. DistinctOf
11.6.8. Except
11.6.9. FirstOf
11.6.10. GroupBy
11.6.11. Intersect
11.6.12. LastOf
11.6.13. LeastFrequent
11.6.14. Max
11.6.15. MaxBy
11.6.16. Min
11.6.17. MinBy
11.6.18. MostFrequent
11.6.19. OrderBy and OrderByDesc
11.6.20. Reverse
11.6.21. SelectFrom
11.6.22. SequenceEqual
11.6.23. SumOf
11.6.24. Take
11.6.25. TakeLast
11.6.26. TakeWhile
11.6.27. TakeWhileLast
11.6.28. ToMap
11.6.29. Union
11.6.30. Where

EPL provides enumeration methods that work with lambda expressions to perform common tasks on subquery results, named windows, tables, event properties or inputs that are or can be projected to a collection of events, scalar values or objects.

Enumeration methods are stateless and the use of enumeration methods alone does not cause the runtime to retain any events or other state (with the possible exception of short-lived caching of evaluation results).

A lambda expression is an anonymous expression. Lambda expressions are useful for encapsulating user-defined expressions that are applied to each element in a collection. This section discusses built-in enumeration methods and their lambda expression parameters.

Lambda expressions use the lambda operator =>, which is read as "goes to" (-> may be used and is equivalent). The left side of the lambda operator specifies the lambda expression input parameter(s) (if any) and the right side holds the expression. The lambda expression x => x * x is read "x goes to x times x.". Lambda expressions are also used for expression declaration as discussed in Section 5.2.9, “Expression Declaration”.

When writing lambdas, you do not have to specify a type for the input parameter(s) or output result(s) because the compiler can infer all types based on the input and the expression body. So if you are querying an RFIDEvent, for example, then the input variable is inferred to be an RFIDEvent event, which means you have access to its properties and methods.

The term element in respect to enumeration methods means a single event, scalar value or object in a collection that is the input to an enumeration method. The term collection means a sequence or group of elements.

The below table summarizes the built-in enumeration methods available:

Table 11.1. Enumeration Methods

MethodResult
aggregate(seed, accumulator lambda)

Aggregate elements by using seed as an initial accumulator value and applying an accumulator expression.

Section 11.6.1, “Aggregate”.

allof(predicate lambda)

Return true when all elements satisfy a condition.

Section 11.6.2, “AllOf”.

anyof(predicate lambda)

Return true when any element satisfies a condition.

Section 11.6.3, “AnyOf”.

arrayOf()

Returns an array of the scalar elements.

Section 11.6.4, “ArrayOf”.

arrayOf(value-selector lambda)

Returns the array containing each value returned by the value-selector expression when applied to each element.

Section 11.6.4, “ArrayOf”.

average()

Computes the average of values obtained from numeric elements.

Section 11.6.5, “Average”.

average(projection lambda)

Computes the average of values obtained from elements by invoking a projection expression on each element.

Section 11.6.5, “Average”.

countof()

Returns the number of elements.

Section 11.6.6, “CountOf”.

countof(predicate lambda)

Returns the number of elements that satisfy a condition.

Section 11.6.6, “CountOf”.

distinctOf()

Returns distinct elements according to default hash and equals semantics.

Section 11.6.7, “DistinctOf”.

distinctOf(key-selector lambda)

Returns distinct elements according using the key function provided.

Section 11.6.7, “DistinctOf”.

except(source)

Produces the set difference of the two collections.

Section 11.6.8, “Except”.

firstof()

Returns the first element.

Section 11.6.9, “FirstOf”.

firstof(predicate lambda)

Returns the first element that satisfies a condition.

Section 11.6.9, “FirstOf”.

groupby(key-selector lambda)

Groups the elements according to a specified key-selector expression.

Section 11.6.10, “GroupBy”.

groupby(key-selector lambda, value-selector lambda)

Groups the elements according to a key-selector expression mapping each element to a value according to a value-selector.

Section 11.6.10, “GroupBy”.

intersect(source)

Produces the set intersection of the two collections.

Section 11.6.11, “Intersect”.

lastof()

Returns the last element.

Section 11.6.12, “LastOf”.

lastof(predicate lambda)

Returns the last element that satisfies a condition.

Section 11.6.12, “LastOf”.

leastFrequent()

Returns the least frequent value among a collection of values.

Section 11.6.13, “LeastFrequent”.

leastFrequent(transform lambda)

Returns the least frequent value returned by the transform expression when applied to each element.

Section 11.6.13, “LeastFrequent”.

max()

Returns the maximum value among a collection of elements.

Section 11.6.14, “Max”.

max(value-selector lambda)

Returns the maximum value returned by the value-selector expression when applied to each element.

Section 11.6.14, “Max”.

maxby(value-selector lambda)

Returns the element that provides the maximum value returned by the value-selector expression when applied to each element.

Section 11.6.15, “MaxBy”.

min()

Returns the minimum value among a collection of elements.

Section 11.6.14, “Max”.

min(value-selector lambda)

Returns the minimum value returned by the value-selector expression when applied to each element.

Section 11.6.16, “Min”.

minby(value-selector lambda)

Returns the element that provides the minimum value returned by the value-selector expression when applied to each element..

Section 11.6.17, “MinBy”.

mostFrequent()

Returns the most frequent value among a collection of values.

Section 11.6.18, “MostFrequent”.

mostFrequent(transform lambda)

Returns the most frequent value returned by the transform expression when applied to each element.

Section 11.6.18, “MostFrequent”.

orderBy()

Sorts the elements in ascending order.

Section 11.6.19, “OrderBy and OrderByDesc”.

orderBy(key-selector lambda)

Sorts the elements in ascending order according to a key.

Section 11.6.19, “OrderBy and OrderByDesc”.

orderByDesc()

Sorts the elements in descending order.

Section 11.6.19, “OrderBy and OrderByDesc”.

orderByDesc(key-selector lambda)

Sorts the elements in descending order according to a key.

Section 11.6.19, “OrderBy and OrderByDesc”.

reverse

Reverses the order of elements.

Section 11.6.20, “Reverse”.

selectFrom(transform lambda)

Transforms each element resulting in a collection of transformed elements.

Section 11.6.21, “SelectFrom”.

sequenceEqual(second)

Determines whether two collections are equal by comparing each element (equals semantics apply).

Section 11.6.22, “SequenceEqual”.

sumOf()

Computes the sum from a collection of numeric elements.

Section 11.6.23, “SumOf”.

sumOf(projection lambda)

Computes the sum by invoking a projection expression on each element.

Section 11.6.23, “SumOf”.

take(numElements)

Returns a specified number of contiguous elements from the start.

Section 11.6.24, “Take”.

takeLast(numElements)

Returns a specified number of contiguous elements from the end.

Section 11.6.25, “TakeLast”.

takeWhile(predicate lambda)

Returns elements from the start as long as a specified condition is true.

Section 11.6.26, “TakeWhile”.

takeWhile( (predicate, index) lambda)

Returns elements from the start as long as a specified condition is true, allowing each element's index to be used in the logic of the predicate expression.

Section 11.6.26, “TakeWhile”.

takeWhileLast(predicate)

Returns elements from the end as long as a specified condition is true.

Section 11.6.27, “TakeWhileLast”.

takeWhileLast( (predicate,index) lambda)

Returns elements from the end as long as a specified condition is true, allowing each element's index to be used in the logic of the predicate expression.

Section 11.6.27, “TakeWhileLast”.

toMap(key-selector lambda, value-selector lambda)

Returns a Map according to specified key selector and value-selector expressions.

Section 11.6.28, “ToMap”.

union(source)

Forms a union of the input elements with source elements.

Section 11.6.29, “Union”.

where(predicate lambda)

Filters elements based on a predicate.

Section 11.6.30, “Where”.

where( (predicate,index) lambda)

Filters elements based on a predicate, allowing each element's index to be used in the logic of the predicate expression.

Section 11.6.30, “Where”.


The examples in this section come out of the domain of location report (aka. RFID, asset tracking etc.) processing:

The examples use example single-row functions for computing the distance (distance) and for determining if a location falls within a rectangle (inrect) that are not provided by the EPL language. These example UDF functions are not enumeration methods and are used in statements to provide a sensible example.

The Item event contains an assetId id, a (x,y) location, a luggage flag to indicate whether the item represents a luggage (true) or passenger (false), and the assetIdPassenger that holds the asset id of the associated passenger when the item is a piece of luggage.

The Item event is defined as follows (access methods not shown for brevity):

public class Item {
  String assetId;             // passenger or luggage asset id
  Location location;          // (x,y) location
  boolean luggage;            // true if this item is a luggage piece
  String assetIdPassenger;    // if the item is luggage, contains passenger associated
...

The LocationReport event contains a list of Item items for which it reports events.

The LocationReport event is defined as follows:

public class LocationReport {
  List<Item> items;
...

The Zone event contains a zone name and (x1, y1, x2, y2) rectangle.

The Zone event is defined as follows:

public class Zone {
  String name;
  Rectangle rectangle;
...

The Location object is a nested object to Item and provides the current (x,y) location:

public class Location {
  int x;
  int y;
...

The Rectangle object is a nested object to Zone and provides a zone rectangle(x1,y1,x2,y2):

public class Rectangle {
  int x1;
  int y1;
  int x2;
  int y2;
...

The syntax for enumeration methods is the same syntax as for any chained invocation:

input_coll.enum_method_name( [method_parameter [, method_parameter [,...]]])
	  .[ [enum_method_name(...) [...]] | property_name] 

Following the input_coll input collection (options outlined below), is the . (dot) operator and the enum_method_name enumeration method name. It follows in parenthesis a comma-separated list of method parameter expressions. Additional enumeration methods can be chained thereafter. An event property name can follow for those enumeration methods returning an event-typed (non-scalar) element.

If the method parameter is a lambda expression with a single lambda-parameter, specify the lambda-parameter name followed by the => lambda operator and followed by the expression. The synopsis for use with a single lambda-parameter is:

method_parameter: lambda_param => lambda_expression

If the method parameter is a lambda expression with two or more lambda-parameters, specify the lambda parameter names in parenthesis followed by the => lambda operator followed by the expression. The synopsis for use with multiple lambda-parameters is:

method_parameter: (lambda_param [,lambda_param [,...]]) => lambda_expression

Generally for lambda expressions, the runtime applies the lambda expression to each element in the input collection. The expression yields a result that, depending on the particular enumeration method, is used for aggregation, as a filter or for output, for example.

It is not necessary to use classes for event representation. The example above applies the same to Object-array, Map or XML underlying events.

For most enumeration methods the input can be any collection of events, scalar values or objects. For some enumeration methods limitations apply that are documented below. For example, the sumOf enumeration method requires a collection of numeric scalar values if used without parameters. If the input to sumOf is a collection of events or scalar values the enumeration method requires a lambda expression as parameter that yields the numeric value to use to compute the sum.

Many examples of this section operate on the collection returned by the event property items in the LocationReport event class. There are many other inputs yielding collections as listed below. Most examples herein use an event property as a input simply because the example can thus be brief and does not need to refer to a subquery, named window, table or other concept.

For enumeration methods that return a collection, for example where and orderBy, the runtime outputs an implementation of the Collection interface that contains the selected value(s). The collection returned must be considered read-only. As Java does not allow resettable iterators, the Collection interface allows more flexibility to query size and navigate among collection elements. We recommend against down-casting a collection returned by the runtime to a more specific subclass of the Collection interface.

For enumeration methods that return an element, for example firstOf, lastOf, minBy and maxBy the runtime outputs the scalar value or the underlying event if operating on events. You may add an event property name after the enumeration method to return a property value.

Enumeration methods generally retain the order of elements provided by the collection.

The following restrictions apply to enumeration methods:

The input of data for built-in enumeration methods is a collection of scalar values, events or other objects. Input can originate from any of the following:

Subqueries can return the rows of another stream's data window or rows from a named window or table. By providing a where-clause the rows returned by a subquery can be correlated to data provided by stream(s) in the from-clause. See Section 5.11, “Subqueries”.

A subquery that selects (*) wildcard provides a collection of events as input. A subquery that selects a single value expression provides a collection of scalar values as input. Subqueries that select multiple value expressions are not allowed as input to enumeration methods.

The following example uses a subquery to retrieve all zones for each location report item where the location falls within the rectangle of the zone. Please see a description of example events and functions above.

select assetId,
  (select * from Zone#unique(name)).where(z => inrect(z.rectangle, location)) as zones
from Item

You may place the subquery in an expression declaration to reuse the subquery in multiple places of the same statement.

This sample EPL declares the same statement as above in an expression declaration:

expression myquery {itm =>
  (select * from Zone#unique(name)).where(z => inrect(z.rectangle, itm.location))
}
select assetId, myquery(item) as subq, 
    myquery(item).where(z => z.zone = 'Z01') as assetItem
from Item as item

The above statement also demonstrates how an enumeration method, in the example the where-method, can be run across the results returned by a subquery in an expression declaration.

Place a single column in the subquery select-clause to provide a collection of scalar values as input.

The next example selects all names of zones and orders the names returning an order collection of string names every 30 seconds:

select (select name from Zone#unique(name)).orderBy() as orderedZones
from pattern[every timer:interval(30)]

The next example utilizes a subquery that counts zone events per name and finds those that have a count greater than 1:

select (select name, count(*) as cnt from Zone#keepall group by name)
  .where(v => cnt > 1) from LocationReport]

When the subquery selects a single column that is itself an event, the result of the subquery is a collection of events of that type and can provide input to enumeration methods.

For example:

create schema SettlementEvent (symbol string);
create schema PriceEvent (symbol string, price double);
create schema OrderEvent (orderId string, pricedata PriceEvent);
select (select pricedata from OrderEvent#unique(orderId))
  .anyOf(v => v.symbol = 'GE') as has_ge from SettlementEvent(symbol = 'GE')

Note that the runtime can cache intermediate results thereby is not forced to re-evaluate the subquery for each occurrence in the select-clause.

Named windows are globally-visible data windows. See Section 6.2, “Named Window Usage”.

You may specify the named window name as input for an enumeration method and can optionally provide a correlation where-clause. The syntax is equivalent to a sub-query against a named window but much shorter.

Synopsis:

named-window-name[(correlation-expression)].enum-method-name(...)

When selecting all events in a named window you do not need the correlation-expression. To select a subset of data in the named window, specify a correlation-expression. From the perspective of best runtime performance, a correlation expression is preferred to reduce the number of rows returned.

The following example first declares a named window to hold the last zone event per zone name:

create window ZoneWindow#unique(name) as Zone

Then you create a statement to insert zone events that arrive to the named window:

insert into ZoneWindow select * from Zone

Finally this statement queries the named window to retrieve all zones for each location report item where the location falls within the rectangle of the zone:

select ZoneWindow.where(z => inrect(z.rectangle, location)) as zones from Item

If you have a filter or correlation expression, append the expression to the named window name and place in parenthesis.

This slightly modified statement is the example above except that it adds a filter expression such that only zones with name Z1, Z2 or Z3 are considered:

select ZoneWindow(name in ('Z1', 'Z2', 'Z3')).where(z => inrect(z.rectangle, location)) as zones 
from Item

You may prefix property names provided by the named window with the name to disambiguate property names.

This sample statement prefixed the name property and returns the count of matching zones:

select ZoneWindow(ZoneWindow.name in ('Z1', 'Z2', 'Z3')).countof()) as zoneCount
from Item

The runtime internally interprets the shortcut syntax and creates a subquery from it. Thus all indexing and query planning for subqueries against named windows apply here as well.

Tables are globally-visible data structures. See Section 6.3, “Table Usage”.

Tables can hold aggregation state such as the window and sorted aggregation state.

The example EPL below declares a table to hold StockTick events in a column named theTicks:

create table MyTable(theTicks window(*) @type(StockTick))

The table column can be input to an enumeration method, for example:

select MyTable.theTicks.anyOf(v=> price > 100) from MyEvent

Event properties that are a collection, array or iterable of scalar values or objects can be an input to enumeration methods. Event properties that hold a collection or array of events can be an input to enumeration methods. Use @eventbean in the select-clause with insert into to select events.

The LocationReport event from the example contains a list of Item events. Any indexed property (list, array, collection, iterable) is eligible for use as input to an enumeration method. If the indexed property contains non-scalar objects the objects are treated as events and can be used as input to enumeration methods as a collection of events.

The next sample statement returns items that are less than 20 units away from the center, taking the items event property provided by each LocationReport event as input:

select items.where(p => distance(0, 0, p.location.x, p.location.y) < 20) as centeritems
from LocationReport

The next three statements declare an OrderEvent type that contains OrderDetail events and a statement that enumerates order detail:

create schema OrderDetail(itemId string)
create schema OrderEvent(details OrderDetail[])
select details.where(i => i.itemId = '001') from OrderEvent

The first statement in this two-statement explanation selects the events that have a price of greater than 100 from a 10-second time window if the count of events is at least 10. It inserts the events into stream TicksLarge. The use of @eventbean means that the event property ticksLargePrice holds events (and not underlying objects). The second statement further filters the events and returns a collection of events that have price of less than 100.

insert into TicksLarge select window(*).where(e => e.price > 100) @eventbean as ticksLargePrice
from StockTick#time(10) having count(*) > 10
select ticksLargePrice.where(e => e.price < 200) as ticksLargeLess200 from TicksLarge

Event aggregation functions return an event or multiple events. They are aggregation functions and as such sensitive to the presence of group by. See Section 10.2.2, “Event Aggregation Functions”.

You can use window, first or last event aggregation functions as input to an enumeration method. Specify the * wildcard as the parameter to the event aggregation function to provide a collection of events as input. Or specify a property name as the parameter to event aggregation function to provide a collection of scalar values as input.

You can use the sorted, maxby, minby, maxbyever or minbyever event aggregation functions as input to an enumeration method. Specify one or more criteria expressions that provide the sort order as parameters to the event aggregation function.

Aggregation methods are used in conjunction with aggregations and can also provide input to an enumeration method. Please go to Section 13.2.5, “Using Dot to Enumerate Events”.

In this example statement the window(*) aggregation function returns the last 10 seconds of item location reports for the same asset id as the incoming event. Among that last 10 seconds of events for the same asset id, the enumeration method returns those item location reports where the distance to center is less than 20, for each arriving Item event.

Sample statement:

select window(*).where(p => distance(0, 0, p.location.x, p.location.y) < 20) as centeritems
from Item(type='P')#time(10) group by assetId

The next sample statement instead selects the asset id property of all events and returns an ordered collection:

select window(assetId).orderBy() as orderedAssetIds
from Item#time(10) group by assetId

The following example outputs the 5 highest prices per symbol among the last 10 seconds of stock ticks:

select sorted(price desc).take(5) as highest5PricesPerSymbol
from StockTick#time(10) group by symbol

The prev, prevwindow and prevtail single-row functions allow access into a stream's data window however are not aggregation functions and and as such not sensitive to the presence of group by. See Section 10.1.15, “The Previous-Window Function”.

When using any of the prev single-row functions as input to a built-in enumeration method you can specify the stream name as a parameter to the function or an event property. The input to the enumeration method is a collection of events if you specify the stream name, or a collection of scalar value if you specify an event property.

In this example statement the prevwindow(stream) single-row function returns the last 10 seconds of item location reports, among which the enumeration method filters those item location reports where the distance to center is less than 20, for each Item event that arrived in the last 10 seconds considering passenger-type Item events only (see filter type = 'P').

Sample statement:

select prevwindow(items)
    .where(p => distance(0, 0, p.location.x, p.location.y) < 20) as centeritems
from Item(type='P')#time(10) as items

This sample statement demonstrates the use of the prevwindow function to return a collection of scalar values (collection of asset id) as input to orderby:

select prevwindow(assetId).orderBy() as orderedAssetIds
from Item#time(10) as items

Your single-row or user-defined function can return either an array or any collection that implements either the Collection or Iterable interface. For arrays, the array component type and for collections, the collection or iterable generic type should be the class providing event properties.

As an example, assume a ZoneFactory class exists and a static method getZones() returns a list of zones to filter items, for example:

public class ZoneFactory {
  public static Iterable<Zone> getZones() {
    List<Zone> zones = new ArrayList<Zone>();
    zones.add(new Zone("Z1", new Rectangle(0, 0, 20, 20)));
    return zones;
  }
}

Import the class through runtime or static configuration, or add the method above as a plug-in single-row function.

The following statement returns for each Item event all zones that the item belongs to:

select ZoneFactory.getZones().where(z => inrect(z.rectangle, item.location)) as zones
from Item as item

If the class and method were registered as a plug-in single-row function, you can leave the class name off, for example:

select getZones().where(z => inrect(z.rectangle, item.location)) as zones
from Item as item

Your single-row or user-defined function can also return an array, collection or iterable or scalar values.

For example, the static method getZoneNames() returns a list of zone names:

public static String[] getZoneNames() { 
  return new String[] { "Z1", "Z2"};
}

The following statement returns zone names every 30 seconds and excludes zone Z1:

select getZoneNames().where(z => z != "Z1")
from pattern[every timer:interval(30)]

An enum type can also be a useful source for enumerable values.

The following sample Java declares an enum type EnumOfZones:

public enum EnumOfZones {
  ZONES_OUTSIDE(new String[] {"z1", "z2"}),
  ZONES_INSIDE(new String[] {"z3", "z4"})

  private final String[] zones;

  private EnumOfZones(String[] zones) {
	  this.zones = zones;
  }

  public String[] getZones() {
    return zones;
  }
}

A sample statement that utilizes the enum type is shown next:

select EnumOfZones.ZONES_OUTSIDE.getZones().anyOf(v => v = zone) from Item

Following the RFID asset tracking example as introduced earlier, this section introduces two use cases solved by enumeration methods.

The first use case requires us to find any luggage that is more than 20 units away from the passenger that the luggage belongs to. The declared expression lostLuggage solves this question.

The second question to answer is: For each of such lost luggage what single other passenger is nearest to that luggage. The declared expression nearestOwner which uses lostLuggage answers this question.

Below is the complete statement (one statement not multiple):

// expression to return a collection of lost luggage
expression lostLuggage {
  lr => lr.items.where(l => l.type='L' and
    lr.items.some(p => p.type='P' and p.assetId=l.assetIdPassenger 
      and LRUtil.distance(l.location.x, l.location.y, p.location.x, p.location.y) > 20))
}

// expression to return all passengers
expression passengers {
  lr => lr.items.where(l => l.type='P')
}

// expression to find the nearest owner
expression nearestOwner {
  lr => lostLuggage(lr).toMap(key => key.assetId,
    value => passengers(lr).minBy(
        p => LRUtil.distance(value.location.x, value.location.y, p.location.x, p.location.y))
    )
}

select lostLuggage(lr) as val1, nearestOwner(lr) as val2 from LocationReport lr

The aggregate enumeration method takes an expression providing the initialization value (seed) and an accumulator lambda expression. The return value is the final accumulator value.

Via the aggregate method you may perform a calculation over elements. The method initializes the aggregated value by evaluating the expression provided in the first parameter. The method then calls the lambda expression of the second parameter once for each element in the input. The lambda expression receives the last aggregated value and the element from the input. The result of the expression replaces the previous aggregated value and returns the final result after completing all elements. The collection element index and collection size are additional optional formal parameters.

Some expression examples with scalar values as input and with the optional collection element index and collection size formal parameters are:

{1, 2, 3}.aggregate(0, (result, value) => result + value)  // Returns 6
{1, 2, 3}.aggregate(0, (result, value, index) => result + value + index*10)  // Returns 36 = 1 + 12 + 23
{1, 2, 3}.aggregate(0, (result, value, index, size) => result + value + index*10 + size*100)  // Returns 936 = 301 + 312 + 323

The example below aggregates price of each OrderEvent in the last 10 seconds computing a total price:

// Initialization value is zero.
// Aggregate by adding up the price.
select window(*).aggregate(0, (result, order) => result + order.price) as totalPrice
from OrderEvent#time(10)

In the statement above, the initialization value is zero, result is used for the last aggregated value and order denotes the element that the expression adds the value of the price property.

This example aggregation builds a comma-separated list of all asset ids of all items:

select items.aggregate('', 
  (result, item) => result || (case when result='' then '' else ',' end) || item.assetId) as assets			
from LocationReport

In above statement, the empty string represents the initialization value. The name result is used for the last aggregated value and the name item is used to denote the element.

The type value returned by the initialization expression must match to the type of value returned by the accumulator lambda expression.

If the input is null the method returns null. If the input is empty the method returns the initialization value.

The distinctOf enumeration method returns distinct elements.

The enumeration method can take a single key-selector lambda expression as parameter and returns distinct elements according to the key yielded by the expression. For same-value keys, distinct returns the first element for that key. Further detail on key expressions can be found at Section 5.2.13, “Composite Keys and Array Values as Keys”.

An expression example with scalar values:

{2, 3, 2, 1}.distinctOf()   // Returns {2, 3, 1}
{2, 3, 2, 1}.distinctOf(v => case when v > 1 then 0 else -1 end)   // Returns {2, 1}
{2, 3, 2, 1}.distinctOf((v, index) => case when index = 0 then 1 else 2 end)   // Returns {2, 3}
{2, 3, 2, 1}.distinctOf((v, index, size) => case when index+1=size then 1 else 2 end)   // Returns {2, 1}

This example returns items distinct by item id returning the first item for each distinct item id:

select items.distinctOf(i => itemId) as itemsNearFirst
from LocationReport

The key-selector lambda expression, when provided, must return a comparable type: Any primitive or boxed or Comparable type is permitted.

If the input is null the method returns null. If the input is empty the method returns an empty collection.

The groupby enumeration method groups the elements according to a specified key-selector lambda expression. There are two version of the groupby method.

The first version of the method takes a key-selector lambda expression and returns a Map of key with each value a list of objects, one for each distinct key that was encountered. The result is a Map<Object, Collection<Object>> wherein object is the event underlying object.

The second version of the method takes a key-selector lambda expression and value-selector lambda expression and returns a Map of key with each value a list of values, one for each distinct key that was encountered. The result is a Map<Object, Collection<Object>> wherein object is the result of applying the value-selector expression.

The example expressions with scalar values are:

{1, 2, 3}.groupby(k => 'K' || Integer.toString(k))   // Returns map {K1=[1], K2=[2], K3=[3]}
{1, 2, 3}.groupby(k => 'K' || Integer.toString(k), v => 'V' || Integer.toString(v))   // Returns map {K1=[V1], K2=[V2], K3=[V3]}
{1, 2, 3}.groupby(
  (k, i) => 'K' || Integer.toString(k) || "_" || Integer.toString(i), 
  (v, i) => 'V' || Integer.toString(v) || "_" || Integer.toString(i)
  )  // Returns map {K1_0=[V1_0], K2_1=[V2_1], K3_2=[V3_2]}
{1, 2, 3}.groupby(
  (k, i, s) => 'K' || Integer.toString(k) || "_" || Integer.toString(s), 
  (v, i, s) => 'V' || Integer.toString(v) || "_" || Integer.toString(s)
  )  // Returns map {K1_3=[V1_3], K2_3=[V2_3], K3_3=[V3_3]}

The next statement filters out all luggage items using a where method and then groups by the luggage's passenger asset id. It returns a map of passenger asset id and the collection of luggage items for each passenger:

select items.where(type='L').groupby(i => assetIdPassenger) as luggagePerPerson
from LocationReport

The statement shown below generates a map of item asset id and distance to center:

select items.groupby(
    k => assetId, v => distance(v.location.x, v.location.y, 0, 0)) as distancePerItem
from LocationReport

If the input is null the method returns null. Null values as key and value are allowed.

The leastFrequent enumeration method returns the least frequent value among a collection of values, or the least frequent value after applying a transform expression to each element.

The method has two versions: The first version takes no parameters and returns the least frequent value. The second version takes a transform lambda expression yielding the value to count occurrences for. The method applies the lambda expression to each element and returns the expression result value with the least number of occurrences. The return type is the type of value in the collection or the type of value returned by the transform lambda expression if one was provided.

An expression example with scalar values:

{1, 2, 3, 2, 1}.leastFrequent()   // Returns 3
{1, 2, 3, 2, 1}.leastFrequent(v => case when v = 3 then 4 else v end)   // Returns 4
{1, 2, 3, 2, 1}.leastFrequent((v, index) => case when index = 2 then 4 else v end)   // Returns 4
{1, 2, 3, 2, 1}.leastFrequent((v, index, size) => case when index = size - 2 then 4 else v end)  // Returns 2

The example EPL below returns the least frequent item type, counting the distinct item types among all items for the current LocationReport event:

select items.leastFrequent(i => type) as leastFreqType from LocationReport

If the input is null or empty the method returns null. The transform expression may also yield null. A null value can be returned as the most frequent value if the most frequent value is null. If multiple values have the same number of occurrences the method returns the first value with the least number of occurrences considering the ordering of the collection.

The mostFrequent enumeration method returns the most frequent value among a collection of values, or the most frequent value after applying a transform expression to each element.

The method has two versions: The first version takes no parameters and returns the most frequent value. The second version takes a transform lambda expression yielding the value to count occurrences for. The method applies the lambda expression to each element and returns the expression result value with the most number of occurrences. The return type is the type of value in the collection or the type of value returned by the transform lambda expression if one was provided.

An expression example with scalar values:

{1, 2, 3, 2, 1, 2}.mostFrequent()   // Returns 2
{1, 2, 3, 2, 1, 2}.mostFrequent(v => case when v = 2 then 10 else v end)   // Returns 10
{1, 2, 3, 2, 1, 2}.mostFrequent((v, index) => case when index > 2 then 4 else v end)   // Returns 4
{1, 2, 3, 2, 1, 2}.mostFrequent((v, index, size) => case when size > 3 then 0 else v end)   // Returns 0

The example EPL below returns the least frequent item type, counting the distinct item types among all items for the current LocationReport event:

select items.leastFrequent(i => type) as leastFreqType from LocationReport

If the input is null or empty the method returns null. The transform expression may also yield null. A null value can be returned as the most frequent value if the most frequent value is null. If multiple values have the same number of occurrences the method returns the first value with the most number of occurrences considering the ordering of the collection.

The selectFrom enumeration method transforms each element resulting in a collection of transformed elements.

The enumeration method has two versions. The first version takes only a transformation lambda expression and applies that to each element and returns the result of each transformation as a collection. The second version takes a transformation lambda expression and index for use within the transformation expression.

Use the new operator to yield multiple values for each element, see Section 9.14, “The 'New' Keyword”.

The following are expression examples with scalar values:

{'A','B','C'}.selectFrom(v => '<' || v || '>')   // Returns [<A>, <B>, <C>]
{'A','B','C'}.selectFrom((v, index) => v || '_' || Integer.toString(index))   // Returns [A_0, B_1, C_2]
{'A','B','C'}.selectFrom((v, index, size) => v || '_' || Integer.toString(size))   // Returns [A_3, B_3, C_3]

The next statement returns a collection of asset ids:

select items.selectFrom(i => assetId) as itemAssetIds from LocationReport

This sample statement evaluates each item and returns the asset id as well as the distance from center for each item:

select items.selectFrom(i => 
  new {
    assetId, 
    distanceCenter = distance(i.location.x, i.location.y, 0, 0)
  } ) as itemInfo from LocationReport

The second version of the selectFrom enumeration method also represents the index of the input element starting at zero for the first element.

The example appends the passenger-type and the index returning a string-type value for each item:

select items.selectFrom((p, ind) => p.type || Integer.toString(ind)) from LocationReport

If the input is null the method returns null. If the input is empty the method returns an empty collection.

The takeWhileLast enumeration method returns elements from the end as long as a specified condition is true.

The enumeration method has two versions. The first version takes a predicate lambda expression and the second version takes a predicate lambda expression and index for use within the predicate expression. Both versions return elements from the end as long as the specified condition is true.

The expression examples with scalar values are:

{1, 2, 3}.takeWhileLast(v => v < 3)   // Returns {} (empty collection)
{1, 2, 3}.takeWhileLast(v => v > 1)   // Returns {2, 3}
{1, 2, 3}.takeWhileLast((v,ind) => ind > 2)   // Returns {2, 3}
{1, 2, -1, 4, 5, 6}.takeWhileLast((v,ind) => ind < 5 and v > 0)  // Returns {4, 5, 6} (Take while index<5 amd value>0)
{1, 2, -1, 4, 5, 6}.takeWhileLast((v,ind,sz) => ind < sz-4 and v > 0)   // Returns {5, 6}

This example selects all items from a location report, starting from the last element and proceeding backwards, until the first item that has a distance to center greater than 20 units:

select items.takeWhile(i => distance(i.location.x, i.location.y, 0, 0) < 20)
from LocationReport

The second version provides the index of the input element starting at zero for the last element (reverse index).

The next example is similar to the statement above but also limits the result to the last 10 items:

select items.takeWhile((i, ind) => distance(i.location.x, i.location.y, 0, 0) < 20) and ind < 10)
from LocationReport

If the input is null the method returns null. If the input is empty the method returns an empty collection.