# Emit computed events

## Overview

**Publish** event query projections to downstream systems, with options to **select**, **refine and calculate** event attributes and **filter** the final projected event.

The following function can be applied to the projection expression

1. <mark style="color:green;">**Event attribute selection**</mark>\
   Select event attributes to be included in the final results.
2. <mark style="color:green;">**Add metric data**</mark>\
   Apply calculated metrics within the projection.
3. <mark style="color:green;">**Apply simple math functions**</mark>\
   Use simple math function on the selected attributes.
4. <mark style="color:green;">**Filter resulting projected data**</mark>\
   Use the *having* filter to narrow the result set, similar to the SQL having clause.
5. <mark style="color:green;">**Attribute renaming using an alias**</mark>\
   Rename attributes to ease system integrations.

## Using the select expression

To bring this to life, we shall use the following select query and final stream event that will be queried.

### Query

```yaml
stream:
  ...
  emit:
    eventType: buy_alert
    select:
        "
        venue.name 'venue',
        symbol, 
        ask,
        bid,
        ask - bid 'spread',
        details.*,
        BidMovingAverage.avg_ask|avg_bid;where symbol = {symbol}
        "
    having: "symbol =='IBM' && spread > 0.05"
```

### Source event

The following event example will be used to demonstrate the `select` query and `having` filter.

```yaml
# Source processed event
streamEvent:
  ...
  attributes:
      symbol: IBM
      ask: 101
      bid: 100
      details: {
         vol: 50
         liq: 60   
      }
      venue: {
         name: nasdaq
      }
```

### Output event

This will produce the following result which is published to the connected consumers.

```yaml
# Result object
event type: buy_alert
  venue: nasdaq
  symbol: IBM
  ask: 101
  bid: 100
  spread: 1
  vol: 50
  liq: 60
  avg_ask: 101.34
  avg_bid: 100.12
```

## Using metrics

A key feature is the ability to use and embed calculated metrics within the `select` expression.&#x20;

This enables the following advanced capabilities:

* Ability to add pre-calculated metrics within the select projection.
* Perform calculations using event attributes and metrics.
* Embed metrics values to be applied to within the `having` clause logic

For further information on how this feature is used go to the apply metrics [documentation](https://docs.fractalworks.io/joule/components/analytics/metrics-engine/apply-metrics).

### Example &#x20;

```yaml
stream:
  ...
  emit:
    ...
    select:
        "
        ...
        # Adding metrics attributes
        BidMovingAverage.avg_ask|avg_bid;where symbol = {symbol}
        "
    having:
       "symbol =='IBM' && avg_ask > 101.15"
```

### Attributes schema

<table><thead><tr><th width="320.3333333333333">Format</th><th width="87">Result</th><th>Description</th></tr></thead><tbody><tr><td><p>BidMovingAverage.avg_ask;where symbol = {symbol}</p><p></p></td><td>101.34</td><td>Query the <code>BidMovingAverage</code> table where the event symbol joins the matched latest row for attribute <code>avg_ask</code></td></tr><tr><td><p>BidMovingAverage.avg_ask|avg_bid;where symbol = {symbol}</p><p></p></td><td>101.34, 100.12</td><td>Query the <code>BidMovingAverage</code> table where the event symbol joins the matched latest row for attributes <code>avg_ask</code> and <code>avg_bid</code></td></tr><tr><td><p>BidMovingAverage.avg_ask;where symbol = {symbol} AND venue=${venue.name}</p><p></p></td><td>101.24, 100.22</td><td>Query the <code>BidMovingAverage</code> table where the event symbol and venue joins the matched latest row for the attribute <code>avg_ask</code></td></tr></tbody></table>

## having clause

This is a Javascript expression based filter that evaluates the expression against the resulting select projection result.

If the expression condition is met the resulting event is published otherwise it is dropped.

{% hint style="info" %}
This is an optional property
{% endhint %}

```yaml
# Only publish IBM events with an avg_ask greater than 101.15
stream:
  ...
  emit:
  ...
    having: "symbol == 'IBM' && avg_ask > 101.15"
```

## retain

This boolean attribute informs the system to cache and conflate the computed select projection event which can be used across processor processing contexts.&#x20;

Each select statement field is prefixed with the `emiited_` tag and stored within the defined group by context object (i.e. symbol ). This context is cached ready for next processing state either on a successful having clause or simply without.&#x20;

#### Example

This example uses the having clause to demonstrate how to use the previous emitted event to deterime if the evednt should be filtered.

```yaml
stream:
  processing unit:
    pipeline:
    ...
     - analytic:
          expression: "(bid_MAX - ask_MIN) / bid_MAX"
          assign to: bid_spread
          
  emit:
    select: symbol, ask_MIN, bid_MAX, volume_SUM, volatility_MEAN, bid_spread
    having: bid_spread > 0.015 && (bid_spread > (emitted_bid_spread || bid_spread))
    retain: true
  
  group by
     - symbol
```

## Attributes schema

<table><thead><tr><th width="145">Attribute</th><th width="356">Description</th><th width="138">Data Type</th><th data-type="checkbox">Required</th></tr></thead><tbody><tr><td>event type</td><td>Allows renaming of the event type in the published output. The default appends the final event type attribute to "_view" </td><td>String<br>Default: &#x3C;eventType>_view</td><td>false</td></tr><tr><td>select</td><td>SQL-style command that lets users specify which fields to include. Users can perform calculations (i.e., averages) on fields as well and it supports integration with the metrics engine for advanced calculations. Users can add metrics to the event output by specifying metric expressions in the select clause</td><td>String</td><td>true</td></tr><tr><td>having</td><td>This is a Javascript expression filter that evaluates the expression against the resulting select project. If the expression passes the resulting event is presented to publishing sinks</td><td><p></p><p></p><p>String</p></td><td>false</td></tr><tr><td>retain</td><td>Store the select projection so that it can be used in next processing cycle. </td><td>Boolean<br>Default: false</td><td>false</td></tr></tbody></table>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.fractalworks.io/joule/components/pipelines/emit-computed-events.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
