Script Aggregator Examples

This page contains a few examples of how you can use the Script Aggregator Function.

Example Stream

Open the Peppa CRM example stream to see how the Script Aggregator Function can be used in a stream.

Example 1: Aggregate and Set Timeout

In this example, the timeout has been configured to 1 hour into the future during initialization. Once the timeout is triggered, a mean value is calculated from the sum and then the session is flushed.

/* On Transform script */ if (!session.data.sum) { // Initiate sum property session.data.sum = 0; // Configure the session to timeout 1 hour in the future from first matching record session.setTimeout(new Date(Date.now() + 1000 * 60 * 60)); } // Perform aggregation session.data.sum += payload.sum;
/* On Timeout script */ // Perform aggregation session.data.mean=session.data.sum/session.meta.count; // Flush session await session.flush();

Example 2: Partial Push and Conditional Flush

In this example, the session is partially pushed downstream for every 5 records that matches the current session. If 100 records have matched the session, it will be flushed.

​/* On Transform script */ if (!session.data.sum) { // Initiate sum property session.data.sum = 0; } // Perform aggregation session.data.sum += payload.value; if (session.meta.count === 100) { // Flush on the 100th record await session.flush(); } else if (session.meta.count % 5) { // Push session every 10th record await session.push(); }