-- Match a pattern indicating front running:
-- Row with customer order
-- Row with placed order for broker
-- Row with placed order for customer
INSERT INTO StreamFraudAlerts
SELECT "Front Running", Broker.OrderId,
Broker.Symbol, Broker.Customer
FROM StreamPhoneOrders Phone, StreamPlacedOrders Broker,
StreamPlacedOrders Cust
MATCHING [10 SECONDS: Phone, Broker, Cust]
ON Phone.Broker = Broker.Customer = Cust.Broker
AND Phone.Symbol = Broker.Symbol = Cust.Symbol
WHERE Phone.OrderId = Cust.OrderId;
This Query statement includes the following clauses:
-
The SELECT clause specifies a literal string to be inserted into each output row.
-
The FROM clause joins three data sources from two input streams. Note that the clause assigns an alias to each data source without using the word AS.
-
The MATCHING clause looks for a row arriving on Phone, Broker, and Cust, in that order, within 10 seconds. Broker and Cust are two different aliases for the same input stream, so the sequence being matched is a row arriving on StreamPhoneOrders followed by two rows arriving on StreamPlacedOrders within 10 seconds.
-
The ON clause defines two conditions for the join, specifying that the values in the indicated columns be equal. When you define an ON clause with a MATCHING clause, you must define one or more equalities across all the data sources specified in the FROM clause.
-
The WHERE clause paces a further condition on the join, limiting the search to a sequence when the values in the OrderId column of Phone and Cust are equal.
As a result, the query detects the following pattern of events:
-
A row arrives on StreamPhoneOrders.
-
A row arrives on StreamPlacedOrders with the same value in the Symbol column and with a value in the customer ID column (Broker.Customer) that matches the value in the broker ID column in the first row (Phone.Broker). This indicates that the broker has placed an order for him or her self for the same stock that the customer ordered.
-
A row arrives on StreamPlacedOrders with the same value in the Symbol column as the first two rows, the same value in the broker ID column as the first row and the customer ID column in the second row, and with the same value in the OrderId column as the first row. This is the final event, indicating that the broker placed the order for the customer.