Search code examples
espercumulocity

Iterating over list in event processing


I am currently trying to iterate over a list of ManagedObjects in event processing through a script. It should check a condition for each ManagedObject in the list and once it is true return that Object.

This is my script:

 create expression ManagedObject getCurrentDepot(position, listObjects) [ 
     for (i = 0; i <= listObjects.length; i++) { 
         var obj = listObjects[i]; 
         var distance = distance(position.lat, position.lng, obj.Geofence.lat, obj.Geofence.lng); 
         if (distance <= obj.radius ) { 
             depot; 
         } 
     } 
     null; 
 ];

I get the following error:

Error in statement mytest:statement_2! : Incorrect syntax near ';' at line 3 column 26

It complains about this line:

var obj = listObjects[i];

How can I correctly iterate over the list?


Solution

  • The best solution would be to not do the looping in the expression but in the event processing itself.

    create expression Boolean isInRange(position, element) [
         var distance = distance(position.lat, position.lng, element.Geofence.lat, obj.Geofence.lng); 
         if (distance <= element.radius ) { 
             true; 
         }
         false;
     ];
    
    insert into MyStreamWithDepot
    select
        event.listObjects.firstOf(element => isInRange(event.position, element) is true) as currentDepot
    from InputEvent event;
    

    You can have a look at the documentation for the "firstOf" method here esper documentation