Search code examples
espercumulocity

Esper very simple context and aggregation


I have a quite simple problem to modelize and I don't have experience in Esper, so I may be headed the wrong way so I'd like some insight.

Here's the scenario: I have one stream of events "ParkingEvent", with two types of events "SpotTaken" and "SpotFree". So I have an Esper context both partitioned by id and bordered by a starting event of type "SpotTaken" and an end event of type "SpotFree". The idea is to monitor a parking spot with a sensor and then aggregate data to count the number of times the spot has been taken and also the time occupation.

That's it, no time window or whatsoever, so it seems quite simple but I struggle aggregating data. Here's the code I got so far:

create context ParkingSpotOccupation
  context PartionBySource
    partition by source from SmartParkingEvent,

  context ContextBorders
    initiated by SmartParkingEvent(
      type = "SpotTaken") as startEvent

    terminated by SmartParkingEvent(
      type = "SpotFree") as endEvent;

@Name("measurement_occupation")
context ParkingSpotOccupation
insert into CreateMeasurement
select
  e.source as source,
  "ParkingSpotOccupation" as type,
  {
    "startDate", min(e.time),
    "endDate",  max(e.time),
    "duration", dateDifferenceInSec(max(e.time), min(e.time))
  } as fragments
from
  SmartParkingEvent e
output
  snapshot when terminated;

I got the same data for min and max so I'm guessing I'm doing somthing wrong.

When I'm using context.ContextBorders.startEvent.time and context.ContextBorders.endEvent.time instead of min and max, the measurement_occupation statement is not triggered.


Solution

  • Given that measurements have already been computed by the EPL that you provided, this counts the number of times the spot has been taken (and freed) and totals up the duration:

    select source, count(*), sum(duration) from CreateMeasurement group by source