Pattern matching examples

The MATCH_RECOGNIZE clause of Flink SQL finds sequences of events in a stream, for example to detect possible fraud.

MATCH_RECOGNIZE matches a pattern of rows, like a regular expression over a stream, and returns one row for each match. You partition and order the rows, define the pattern and the conditions of each step, and select the values to return:

Table 1. Clauses of MATCH_RECOGNIZE
Clause Description
PARTITION BY Defines the rows to match separately, for example per card.
ORDER BY Sets the order of the rows in each partition. Order by an event time column.
MEASURES Defines the values to return for each match.
ONE ROW PER MATCH Returns one row for each match.
AFTER MATCH SKIP Sets where the next match starts, for example after the last row of the current match.
PATTERN Defines the sequence of steps to match, with quantifiers such as +.
DEFINE Sets the condition that each step of the pattern must meet.

The following query finds card payments that grow above a threshold. It matches one or more payments above 10, followed by a larger payment:

SELECT *
FROM payments
MATCH_RECOGNIZE (
  PARTITION BY card
  ORDER BY eventTimestamp
  MEASURES
    F.amount AS first_amount,
    E.amount AS last_amount
  ONE ROW PER MATCH
  AFTER MATCH SKIP PAST LAST ROW
  PATTERN (F+ E)
  DEFINE
    F AS F.amount IS NOT NULL AND F.amount > 10,
    E AS E.amount IS NOT NULL AND F.amount < E.amount
);

For more information about MATCH_RECOGNIZE, see Pattern recognition in the Apache Flink documentation.