cep.md 63.5 KB
Newer Older
1 2
---
title: "FlinkCEP - Complex event processing for Flink"
3 4 5
nav-title: Event Processing (CEP)
nav-parent_id: libs
nav-pos: 1
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
---
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

26
FlinkCEP is the Complex Event Processing (CEP) library implemented on top of Flink.
27
It allows you to detect event patterns in an endless stream of events, giving you the opportunity to get hold of what's important in your
28
data.
29

30 31
This page describes the API calls available in Flink CEP. We start by presenting the [Pattern API](#the-pattern-api),
which allows you to specify the patterns that you want to detect in your stream, before presenting how you can
32
[detect and act upon matching event sequences](#detecting-patterns). We then present the assumptions the CEP
33
library makes when [dealing with lateness](#handling-lateness-in-event-time) in event time and how you can
34
[migrate your job](#migrating-from-an-older-flink-version) from an older Flink version to Flink-1.3.
35 36 37 38

* This will be replaced by the TOC
{:toc}

39 40
## Getting Started

41
If you want to jump right in, [set up a Flink program]({{ site.baseurl }}/dev/linking_with_flink.html) and
42
add the FlinkCEP dependency to the `pom.xml` of your project.
43

44 45
<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
46 47 48 49 50 51 52
{% highlight xml %}
<dependency>
  <groupId>org.apache.flink</groupId>
  <artifactId>flink-cep{{ site.scala_version_suffix }}</artifactId>
  <version>{{site.version }}</version>
</dependency>
{% endhighlight %}
53 54 55 56 57 58 59 60 61 62 63 64
</div>

<div data-lang="scala" markdown="1">
{% highlight xml %}
<dependency>
  <groupId>org.apache.flink</groupId>
  <artifactId>flink-cep-scala{{ site.scala_version_suffix }}</artifactId>
  <version>{{site.version }}</version>
</dependency>
{% endhighlight %}
</div>
</div>
65

66
{% info %} FlinkCEP is not part of the binary distribution. See how to link with it for cluster execution [here]({{site.baseurl}}/dev/linking.html).
67

68 69
Now you can start writing your first CEP program using the Pattern API.

70 71
{% warn Attention %} The events in the `DataStream` to which
you want to apply pattern matching must implement proper `equals()` and `hashCode()` methods
72
because FlinkCEP uses them for comparing and matching events.
73

74 75
<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
76 77 78
{% highlight java %}
DataStream<Event> input = ...

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
Pattern<Event, ?> pattern = Pattern.<Event>begin("start").where(
        new SimpleCondition<Event>() {
            @Override
            public boolean filter(Event event) {
                return event.getId() == 42;
            }
        }
    ).next("middle").subtype(SubEvent.class).where(
        new SimpleCondition<Event>() {
            @Override
            public boolean filter(SubEvent subEvent) {
                return subEvent.getVolume() >= 10.0;
            }
        }
    ).followedBy("end").where(
         new SimpleCondition<Event>() {
            @Override
            public boolean filter(Event event) {
                return event.getName().equals("end");
            }
         }
    );
101

102
PatternStream<Event> patternStream = CEP.pattern(input, pattern);
103

104 105 106 107 108 109 110
DataStream<Alert> result = patternStream.select(
    new PatternSelectFunction<Event, Alert> {
        @Override
        public Alert select(Map<String, List<Event>> pattern) throws Exception {
            return createAlertFrom(pattern);
        }
    }
111 112
});
{% endhighlight %}
113 114 115
</div>
<div data-lang="scala" markdown="1">
{% highlight scala %}
116
val input: DataStream[Event] = ...
117

118 119 120
val pattern = Pattern.begin("start").where(_.getId == 42)
  .next("middle").subtype(classOf[SubEvent]).where(_.getVolume >= 10.0)
  .followedBy("end").where(_.getName == "end")
121

122
val patternStream = CEP.pattern(input, pattern)
123

124
val result: DataStream[Alert] = patternStream.select(createAlert(_))
125 126 127 128
{% endhighlight %}
</div>
</div>

129 130
## The Pattern API

131
The pattern API allows you to define complex pattern sequences that you want to extract from your input stream.
132

133
Each complex pattern sequence consists of multiple simple patterns, i.e. patterns looking for individual events with the same properties. From now on, we will call these simple patterns **patterns**, and the final complex pattern sequence we are searching for in the stream, the **pattern sequence**. You can see a pattern sequence as a graph of such patterns, where transitions from one pattern to the next occur based on user-specified
134
*conditions*, e.g. `event.getName().equals("start")`. A **match** is a sequence of input events which visits all
135 136
patterns of the complex pattern graph, through a sequence of valid pattern transitions.

137
{% warn Attention %} Each pattern must have a unique name, which you use later to identify the matched events.
138

139
{% warn Attention %} Pattern names **CANNOT** contain the character `":"`.
140

141
In the rest of this section we will first describe how to define [Individual Patterns](#individual-patterns), and then how you can combine individual patterns into [Complex Patterns](#combining-patterns).
142 143 144

### Individual Patterns

145 146
A **Pattern** can be either a *singleton* or a *looping* pattern. Singleton patterns accept a single
event, while looping patterns can accept more than one. In pattern matching symbols, the pattern `"a b+ c? d"` (or `"a"`, followed by *one or more* `"b"`'s, optionally followed by a `"c"`, followed by a `"d"`), `a`, `c?`, and `d` are
147
singleton patterns, while `b+` is a looping one. By default, a pattern is a singleton pattern and you can transform
148
it to a looping one by using [Quantifiers](#quantifiers). Each pattern can have one or more
149 150 151 152
[Conditions](#conditions) based on which it accepts events.

#### Quantifiers

153 154 155 156 157
In FlinkCEP, you can specifiy looping patterns using these methods: `pattern.oneOrMore()`, for patterns that expect one or more occurrences of a given event (e.g. the `b+` mentioned before); and `pattern.times(#ofTimes)`, for patterns that
expect a specific number of occurrences of a given type of event, e.g. 4 `a`'s; and `pattern.times(#fromTimes, #toTimes)`, for patterns that expect a specific minimum number of occurrences and a maximum number of occurrences of a given type of event, e.g. 2-4 `a`s.

You can make looping patterns greedy using the `pattern.greedy()` method, but you cannot yet make group patterns greedy. You can make all patterns, looping or not, optional using the `pattern.optional()` method.

158
For a pattern named `start`, the following are valid quantifiers:
159

160 161 162 163 164
 <div class="codetabs" markdown="1">
 <div data-lang="java" markdown="1">
 {% highlight java %}
 // expecting 4 occurrences
 start.times(4);
165

166 167
 // expecting 0 or 4 occurrences
 start.times(4).optional();
168

169 170 171
 // expecting 2, 3 or 4 occurrences
 start.times(2, 4);

172 173 174
 // expecting 2, 3 or 4 occurrences and repeating as many as possible
 start.times(2, 4).greedy();

175 176 177
 // expecting 0, 2, 3 or 4 occurrences
 start.times(2, 4).optional();

178 179 180
 // expecting 0, 2, 3 or 4 occurrences and repeating as many as possible
 start.times(2, 4).optional().greedy();

181 182
 // expecting 1 or more occurrences
 start.oneOrMore();
183

184 185 186
 // expecting 1 or more occurrences and repeating as many as possible
 start.oneOrMore().greedy();

187 188
 // expecting 0 or more occurrences
 start.oneOrMore().optional();
189

190 191 192
 // expecting 0 or more occurrences and repeating as many as possible
 start.oneOrMore().optional().greedy();

193 194 195
 // expecting 2 or more occurrences
 start.timesOrMore(2);

196 197
 // expecting 2 or more occurrences and repeating as many as possible
 start.timesOrMore(2).greedy();
198

199 200
 // expecting 0, 2 or more occurrences and repeating as many as possible
 start.timesOrMore(2).optional().greedy();
201 202
 {% endhighlight %}
 </div>
203

204 205 206 207
 <div data-lang="scala" markdown="1">
 {% highlight scala %}
 // expecting 4 occurrences
 start.times(4)
208

209 210
 // expecting 0 or 4 occurrences
 start.times(4).optional()
211

212
 // expecting 2, 3 or 4 occurrences
213
 start.times(2, 4)
214

215
 // expecting 2, 3 or 4 occurrences and repeating as many as possible
216
 start.times(2, 4).greedy()
217

218
 // expecting 0, 2, 3 or 4 occurrences
219
 start.times(2, 4).optional()
220

221
 // expecting 0, 2, 3 or 4 occurrences and repeating as many as possible
222
 start.times(2, 4).optional().greedy()
223

224 225
 // expecting 1 or more occurrences
 start.oneOrMore()
226

227
 // expecting 1 or more occurrences and repeating as many as possible
228
 start.oneOrMore().greedy()
229

230 231
 // expecting 0 or more occurrences
 start.oneOrMore().optional()
232

233
 // expecting 0 or more occurrences and repeating as many as possible
234
 start.oneOrMore().optional().greedy()
235

236
 // expecting 2 or more occurrences
237
 start.timesOrMore(2)
238

239
 // expecting 2 or more occurrences and repeating as many as possible
240
 start.timesOrMore(2).greedy()
241

242
 // expecting 0, 2 or more occurrences
243
 start.timesOrMore(2).optional()
244 245

 // expecting 0, 2 or more occurrences and repeating as many as possible
246
 start.timesOrMore(2).optional().greedy()
247 248 249 250 251 252
 {% endhighlight %}
 </div>
 </div>

#### Conditions

253 254
At every pattern, and to go from one pattern to the next, you can specify additional **conditions**.
You can relate these conditions to:
255

256
 1. A [property of the incoming event](#conditions-on-properties), e.g. its value should be larger than 5,
257 258
 or larger than the average value of the previously accepted events.

259
 2. The [contiguity of the matching events](#conditions-on-contiguity), e.g. detect pattern `a,b,c` without
260
 non-matching events between any matching ones.
261 262

The latter refers to "looping" patterns, *i.e.* patterns that can accept more than one event, e.g. the `b+` in `a b+ c`,
263 264 265 266
which searches for one or more `b`'s.

##### Conditions on Properties

267
You can specify conditions on the event properties via the `pattern.where()`, `pattern.or()` or the `pattern.until()` method. These can be either `IterativeCondition`s or `SimpleCondition`s.
268

269 270
**Iterative Conditions:** This is the most general type of condition. This is how you can specify a condition that
accepts subsequent events based on properties of the previously accepted events or a statistic over a subset of them.
271

272
Below is the code for an iterative condition that accepts the next event for a pattern named "middle" if its name starts
273
with "foo", and if the sum of the prices of the previously accepted events for that pattern plus the price of the current event do not exceed the value of 5.0. Iterative conditions can be powerful, especially in combination with looping patterns, e.g. `oneOrMore()`.
274 275 276 277

<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
{% highlight java %}
278
middle.oneOrMore().where(new IterativeCondition<SubEvent>() {
279 280 281 282 283
    @Override
    public boolean filter(SubEvent value, Context<SubEvent> ctx) throws Exception {
        if (!value.getName().startsWith("foo")) {
            return false;
        }
284

K
kl0u 已提交
285
        double sum = value.getPrice();
286 287 288 289 290 291 292 293 294 295 296
        for (Event event : ctx.getEventsForPattern("middle")) {
            sum += event.getPrice();
        }
        return Double.compare(sum, 5.0) < 0;
    }
});
{% endhighlight %}
</div>

<div data-lang="scala" markdown="1">
{% highlight scala %}
297
middle.oneOrMore().where(
298
    (value, ctx) => {
K
kl0u 已提交
299 300
        lazy val sum = ctx.getEventsForPattern("middle").asScala.map(_.getPrice).sum
        value.getName.startsWith("foo") && sum + value.getPrice < 5.0
301 302 303 304 305 306
    }
)
{% endhighlight %}
</div>
</div>

307
{% warn Attention %} The call to `context.getEventsForPattern(...)` finds all the
308
previously accepted events for a given potential match. The cost of this operation can vary, so when implementing
309
your condition, try to minimize its use.
310

311
**Simple Conditions:** This type of condition extends the aforementioned `IterativeCondition` class and decides
312
whether to accept an event or not, based *only* on properties of the event itself.
313

314 315
<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
316
{% highlight java %}
317
start.where(new SimpleCondition<Event>() {
318 319
    @Override
    public boolean filter(Event value) {
320
        return value.getName().startsWith("foo");
321 322 323
    }
});
{% endhighlight %}
324 325 326 327
</div>

<div data-lang="scala" markdown="1">
{% highlight scala %}
328
start.where(event => event.getName.startsWith("foo"))
329 330 331
{% endhighlight %}
</div>
</div>
332

333
Finally, you can also restrict the type of the accepted event to a subtype of the initial event type (here `Event`)
334
via the `pattern.subtype(subClass)` method.
335

336 337
<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
338
{% highlight java %}
339
start.subtype(SubEvent.class).where(new SimpleCondition<SubEvent>() {
340 341 342 343 344 345
    @Override
    public boolean filter(SubEvent value) {
        return ... // some condition
    }
});
{% endhighlight %}
346 347 348 349
</div>

<div data-lang="scala" markdown="1">
{% highlight scala %}
350
start.subtype(classOf[SubEvent]).where(subEvent => ... /* some condition */)
351 352 353
{% endhighlight %}
</div>
</div>
354

355
**Combining Conditions:** As shown above, you can combine the `subtype` condition with additional conditions. This holds for every condition. You can arbitrarily combine conditions by sequentially calling `where()`. The final result will be the logical **AND** of the results of the individual conditions. To combine conditions using **OR**, you can use the `or()` method, as shown below.
356 357 358 359

<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
{% highlight java %}
360
pattern.where(new SimpleCondition<Event>() {
361 362 363 364
    @Override
    public boolean filter(Event value) {
        return ... // some condition
    }
365
}).or(new SimpleCondition<Event>() {
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    @Override
    public boolean filter(Event value) {
        return ... // or condition
    }
});
{% endhighlight %}
</div>

<div data-lang="scala" markdown="1">
{% highlight scala %}
pattern.where(event => ... /* some condition */).or(event => ... /* or condition */)
{% endhighlight %}
</div>
</div>

381 382 383 384 385 386 387 388 389 390 391 392 393 394

**Stop condition:** In case of looping patterns (`oneOrMore()` and `oneOrMore().optional()`) you can
also specify a stop condition, e.g. accept events with value larger than 5 until the sum of values is smaller than 50.

To better understand it, have a look at the following example. Given

* pattern like `"(a+ until b)"` (one or more `"a"` until `"b"`)

* a sequence of incoming events `"a1" "c" "a2" "b" "a3"`

* the library will output results: `{a1 a2} {a1} {a2} {a3}`.

As you can see `{a1 a2 a3}` or `{a2 a3}` are not returned due to the stop condition.

395 396 397 398
##### Conditions on Contiguity

FlinkCEP supports the following forms of contiguity between events:

399
 1. **Strict Contiguity**: Expects all matching events to appear strictly one after the other, without any non-matching events in-between.
400

401
 2. **Relaxed Contiguity**: Ignores non-matching events appearing in-between the matching ones.
402

403
 3. **Non-Deterministic Relaxed Contiguity**: Further relaxes contiguity, allowing additional matches
404 405
 that ignore some matching events.

406
To illustrate the above with an example, a pattern sequence `"a+ b"` (one or more `"a"`'s followed by a `"b"`) with
407 408
input `"a1", "c", "a2", "b"` will have the following results:

409
 1. **Strict Contiguity**: `{a2 b}` -- the `"c"` after `"a1"` causes `"a1"` to be discarded.
410

411
 2. **Relaxed Contiguity**: `{a1 b}` and `{a1 a2 b}` -- `c` is ignored.
412

413
 3. **Non-Deterministic Relaxed Contiguity**: `{a1 b}`, `{a2 b}`, and `{a1 a2 b}`.
414 415 416

For looping patterns (e.g. `oneOrMore()` and `times()`) the default is *relaxed contiguity*. If you want
strict contiguity, you have to explicitly specify it by using the `consecutive()` call, and if you want
417
*non-deterministic relaxed contiguity* you can use the `allowCombinations()` call.
418

419 420 421 422 423 424
{% warn Attention %}
In this section we are talking about contiguity *within* a single looping pattern, and the
`consecutive()` and `allowCombinations()` calls need to be understood in that context. Later when looking at
[Combining Patterns](#combining-patterns) we'll discuss other calls, such as `next()` and `followedBy()`,
that are used to specify contiguity conditions *between* patterns.

425 426
<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
427 428 429 430 431 432 433 434 435 436 437 438
<table class="table table-bordered">
    <thead>
        <tr>
            <th class="text-left" style="width: 25%">Pattern Operation</th>
            <th class="text-center">Description</th>
        </tr>
    </thead>
    <tbody>
       <tr>
            <td><strong>where(condition)</strong></td>
            <td>
                <p>Defines a condition for the current pattern. To match the pattern, an event must satisfy the condition.
439
                 Multiple consecutive where() clauses lead to their conditions being ANDed:</p>
440 441 442 443 444 445 446 447 448 449 450 451 452
{% highlight java %}
pattern.where(new IterativeCondition<Event>() {
    @Override
    public boolean filter(Event value, Context ctx) throws Exception {
        return ... // some condition
    }
});
{% endhighlight %}
            </td>
        </tr>
        <tr>
            <td><strong>or(condition)</strong></td>
            <td>
453
                <p>Adds a new condition which is ORed with an existing one. An event can match the pattern only if it
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
                passes at least one of the conditions:</p>
{% highlight java %}
pattern.where(new IterativeCondition<Event>() {
    @Override
    public boolean filter(Event value, Context ctx) throws Exception {
        return ... // some condition
    }
}).or(new IterativeCondition<Event>() {
    @Override
    public boolean filter(Event value, Context ctx) throws Exception {
        return ... // alternative condition
    }
});
{% endhighlight %}
                    </td>
469 470 471 472
       </tr>
              <tr>
                 <td><strong>until(condition)</strong></td>
                 <td>
473
                     <p>Specifies a stop condition for a looping pattern. Meaning if event matching the given condition occurs, no more
474 475 476 477 478 479 480 481 482 483 484 485 486
                     events will be accepted into the pattern.</p>
                     <p>Applicable only in conjunction with <code>oneOrMore()</code></p>
                     <p><b>NOTE:</b> It allows for cleaning state for corresponding pattern on event-based condition.</p>
{% highlight java %}
pattern.oneOrMore().until(new IterativeCondition<Event>() {
    @Override
    public boolean filter(Event value, Context ctx) throws Exception {
        return ... // alternative condition
    }
});
{% endhighlight %}
                 </td>
              </tr>
487 488 489
       <tr>
           <td><strong>subtype(subClass)</strong></td>
           <td>
490
               <p>Defines a subtype condition for the current pattern. An event can only match the pattern if it is
491 492 493 494 495 496 497 498 499 500
                of this subtype:</p>
{% highlight java %}
pattern.subtype(SubEvent.class);
{% endhighlight %}
           </td>
       </tr>
       <tr>
          <td><strong>oneOrMore()</strong></td>
          <td>
              <p>Specifies that this pattern expects at least one occurrence of a matching event.</p>
501 502
              <p>By default a relaxed internal contiguity (between subsequent events) is used. For more info on
              internal contiguity see <a href="#consecutive_java">consecutive</a>.</p>
503
              <p><b>NOTE:</b> It is advised to use either <code>until()</code> or <code>within()</code> to enable state clearing</p>
504 505 506
{% highlight java %}
pattern.oneOrMore();
{% endhighlight %}
507
          </td>
508 509 510 511 512 513 514 515 516 517 518 519
       </tr>
           <tr>
              <td><strong>timesOrMore(#times)</strong></td>
              <td>
                  <p>Specifies that this pattern expects at least <strong>#times</strong> occurrences
                  of a matching event.</p>
                  <p>By default a relaxed internal contiguity (between subsequent events) is used. For more info on
                  internal contiguity see <a href="#consecutive_java">consecutive</a>.</p>
{% highlight java %}
pattern.timesOrMore(2);
{% endhighlight %}
           </td>
520 521 522 523 524
       </tr>
       <tr>
          <td><strong>times(#ofTimes)</strong></td>
          <td>
              <p>Specifies that this pattern expects an exact number of occurrences of a matching event.</p>
525 526
              <p>By default a relaxed internal contiguity (between subsequent events) is used. For more info on
              internal contiguity see <a href="#consecutive_java">consecutive</a>.</p>
527
{% highlight java %}
528
pattern.times(2);
529 530 531 532 533 534 535 536 537 538 539 540
{% endhighlight %}
          </td>
       </tr>
       <tr>
          <td><strong>times(#fromTimes, #toTimes)</strong></td>
          <td>
              <p>Specifies that this pattern expects occurrences between <strong>#fromTimes</strong>
              and <strong>#toTimes</strong> of a matching event.</p>
              <p>By default a relaxed internal contiguity (between subsequent events) is used. For more info on
              internal contiguity see <a href="#consecutive_java">consecutive</a>.</p>
{% highlight java %}
pattern.times(2, 4);
541
{% endhighlight %}
542 543 544 545 546
          </td>
       </tr>
       <tr>
          <td><strong>optional()</strong></td>
          <td>
547
              <p>Specifies that this pattern is optional, i.e. it may not occur at all. This is applicable to all
548
              aforementioned quantifiers.</p>
549 550
{% highlight java %}
pattern.oneOrMore().optional();
551 552 553 554 555 556 557 558 559 560
{% endhighlight %}
          </td>
       </tr>
       <tr>
          <td><strong>greedy()</strong></td>
          <td>
              <p>Specifies that this pattern is greedy, i.e. it will repeat as many as possible. This is only applicable
              to quantifiers and it does not support group pattern currently.</p>
{% highlight java %}
pattern.oneOrMore().greedy();
561
{% endhighlight %}
562 563 564 565 566
          </td>
       </tr>
       <tr>
          <td><strong>consecutive()</strong><a name="consecutive_java"></a></td>
          <td>
567 568 569
              <p>Works in conjunction with <code>oneOrMore()</code> and <code>times()</code> and imposes strict contiguity between the matching
              events, i.e. any non-matching element breaks the match (as in <code>next()</code>).</p>
              <p>If not applied a relaxed contiguity (as in <code>followedBy()</code>) is used.</p>
570

571
              <p>E.g. a pattern like:</p>
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
{% highlight java %}
Pattern.<Event>begin("start").where(new SimpleCondition<Event>() {
  @Override
  public boolean filter(Event value) throws Exception {
    return value.getName().equals("c");
  }
})
.followedBy("middle").where(new SimpleCondition<Event>() {
  @Override
  public boolean filter(Event value) throws Exception {
    return value.getName().equals("a");
  }
}).oneOrMore().consecutive()
.followedBy("end1").where(new SimpleCondition<Event>() {
  @Override
  public boolean filter(Event value) throws Exception {
    return value.getName().equals("b");
  }
});
{% endhighlight %}
592
              <p>Will generate the following matches for an input sequence: C D A1 A2 A3 D A4 B</p>
593

594 595 596 597 598 599 600
              <p>with consecutive applied: {C A1 B}, {C A1 A2 B}, {C A1 A2 A3 B}</p>
              <p>without consecutive applied: {C A1 B}, {C A1 A2 B}, {C A1 A2 A3 B}, {C A1 A2 A3 A4 B}</p>
          </td>
       </tr>
       <tr>
       <td><strong>allowCombinations()</strong><a name="allow_comb_java"></a></td>
       <td>
601 602 603
              <p>Works in conjunction with <code>oneOrMore()</code> and <code>times()</code> and imposes non-deterministic relaxed contiguity
              between the matching events (as in <code>followedByAny()</code>).</p>
              <p>If not applied a relaxed contiguity (as in <code>followedBy()</code>) is used.</p>
604

605
              <p>E.g. a pattern like:</p>
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
{% highlight java %}
Pattern.<Event>begin("start").where(new SimpleCondition<Event>() {
  @Override
  public boolean filter(Event value) throws Exception {
    return value.getName().equals("c");
  }
})
.followedBy("middle").where(new SimpleCondition<Event>() {
  @Override
  public boolean filter(Event value) throws Exception {
    return value.getName().equals("a");
  }
}).oneOrMore().allowCombinations()
.followedBy("end1").where(new SimpleCondition<Event>() {
  @Override
  public boolean filter(Event value) throws Exception {
    return value.getName().equals("b");
  }
});
{% endhighlight %}
626
               <p>Will generate the following matches for an input sequence: C D A1 A2 A3 D A4 B</p>
627

628 629 630 631 632 633
               <p>with combinations enabled: {C A1 B}, {C A1 A2 B}, {C A1 A3 B}, {C A1 A4 B}, {C A1 A2 A3 B}, {C A1 A2 A4 B}, {C A1 A3 A4 B}, {C A1 A2 A3 A4 B}</p>
               <p>without combinations enabled: {C A1 B}, {C A1 A2 B}, {C A1 A2 A3 B}, {C A1 A2 A3 A4 B}</p>
       </td>
       </tr>
  </tbody>
</table>
634 635 636
</div>

<div data-lang="scala" markdown="1">
637 638 639 640 641 642
<table class="table table-bordered">
    <thead>
        <tr>
            <th class="text-left" style="width: 25%">Pattern Operation</th>
            <th class="text-center">Description</th>
        </tr>
643
	    </thead>
644
    <tbody>
645

646 647 648 649
        <tr>
            <td><strong>where(condition)</strong></td>
            <td>
              <p>Defines a condition for the current pattern. To match the pattern, an event must satisfy the condition.
650
                                  Multiple consecutive where() clauses lead to their conditions being ANDed:</p>
651 652 653 654 655 656 657 658
{% highlight scala %}
pattern.where(event => ... /* some condition */)
{% endhighlight %}
            </td>
        </tr>
        <tr>
            <td><strong>or(condition)</strong></td>
            <td>
659
                <p>Adds a new condition which is ORed with an existing one. An event can match the pattern only if it
660 661 662 663 664 665 666
                passes at least one of the conditions:</p>
{% highlight scala %}
pattern.where(event => ... /* some condition */)
    .or(event => ... /* alternative condition */)
{% endhighlight %}
                    </td>
                </tr>
667 668 669 670 671 672 673 674 675 676 677 678
<tr>
          <td><strong>until(condition)</strong></td>
          <td>
              <p>Specifies a stop condition for looping pattern. Meaning if event matching the given condition occurs, no more
              events will be accepted into the pattern.</p>
              <p>Applicable only in conjunction with <code>oneOrMore()</code></p>
              <p><b>NOTE:</b> It allows for cleaning state for corresponding pattern on event-based condition.</p>
{% highlight scala %}
pattern.oneOrMore().until(event => ... /* some condition */)
{% endhighlight %}
          </td>
       </tr>
679 680 681
       <tr>
           <td><strong>subtype(subClass)</strong></td>
           <td>
682
               <p>Defines a subtype condition for the current pattern. An event can only match the pattern if it is
683
               of this subtype:</p>
684
{% highlight scala %}
685
pattern.subtype(classOf[SubEvent])
686
{% endhighlight %}
687 688 689 690 691 692
           </td>
       </tr>
       <tr>
          <td><strong>oneOrMore()</strong></td>
          <td>
               <p>Specifies that this pattern expects at least one occurrence of a matching event.</p>
693 694
                            <p>By default a relaxed internal contiguity (between subsequent events) is used. For more info on
                            internal contiguity see <a href="#consecutive_scala">consecutive</a>.</p>
695
                            <p><b>NOTE:</b> It is advised to use either <code>until()</code> or <code>within()</code> to enable state clearing</p>
696 697 698
{% highlight scala %}
pattern.oneOrMore()
{% endhighlight %}
699 700
          </td>
       </tr>
701 702 703 704 705 706 707 708 709 710 711 712
       <tr>
          <td><strong>timesOrMore(#times)</strong></td>
          <td>
              <p>Specifies that this pattern expects at least <strong>#times</strong> occurrences
              of a matching event.</p>
              <p>By default a relaxed internal contiguity (between subsequent events) is used. For more info on
              internal contiguity see <a href="#consecutive_scala">consecutive</a>.</p>
{% highlight scala %}
pattern.timesOrMore(2)
{% endhighlight %}
           </td>
       </tr>
713 714 715 716
       <tr>
                 <td><strong>times(#ofTimes)</strong></td>
                 <td>
                     <p>Specifies that this pattern expects an exact number of occurrences of a matching event.</p>
717
                                   <p>By default a relaxed internal contiguity (between subsequent events) is used.
718 719 720 721
                                   For more info on internal contiguity see <a href="#consecutive_scala">consecutive</a>.</p>
{% highlight scala %}
pattern.times(2)
{% endhighlight %}
722 723
                 </td>
       </tr>
724 725 726 727 728 729 730 731
       <tr>
         <td><strong>times(#fromTimes, #toTimes)</strong></td>
         <td>
             <p>Specifies that this pattern expects occurrences between <strong>#fromTimes</strong>
             and <strong>#toTimes</strong> of a matching event.</p>
             <p>By default a relaxed internal contiguity (between subsequent events) is used. For more info on
             internal contiguity see <a href="#consecutive_java">consecutive</a>.</p>
{% highlight scala %}
732
pattern.times(2, 4)
733 734 735
{% endhighlight %}
         </td>
       </tr>
736 737 738
       <tr>
          <td><strong>optional()</strong></td>
          <td>
739
             <p>Specifies that this pattern is optional, i.e. it may not occur at all. This is applicable to all
740
                           aforementioned quantifiers.</p>
741 742
{% highlight scala %}
pattern.oneOrMore().optional()
743 744 745 746 747 748 749 750 751 752
{% endhighlight %}
          </td>
       </tr>
       <tr>
          <td><strong>greedy()</strong></td>
          <td>
             <p>Specifies that this pattern is greedy, i.e. it will repeat as many as possible. This is only applicable
             to quantifiers and it does not support group pattern currently.</p>
{% highlight scala %}
pattern.oneOrMore().greedy()
753
{% endhighlight %}
754 755 756 757 758
          </td>
       </tr>
       <tr>
          <td><strong>consecutive()</strong><a name="consecutive_scala"></a></td>
          <td>
759 760 761
            <p>Works in conjunction with <code>oneOrMore()</code> and <code>times()</code> and imposes strict contiguity between the matching
                          events, i.e. any non-matching element breaks the match (as in <code>next()</code>).</p>
                          <p>If not applied a relaxed contiguity (as in <code>followedBy()</code>) is used.</p>
762 763

      <p>E.g. a pattern like:</p>
764 765 766 767
{% highlight scala %}
Pattern.begin("start").where(_.getName().equals("c"))
  .followedBy("middle").where(_.getName().equals("a"))
                       .oneOrMore().consecutive()
768
  .followedBy("end1").where(_.getName().equals("b"))
769
{% endhighlight %}
770 771

            <p>Will generate the following matches for an input sequence: C D A1 A2 A3 D A4 B</p>
772

773 774 775 776 777 778 779
                          <p>with consecutive applied: {C A1 B}, {C A1 A2 B}, {C A1 A2 A3 B}</p>
                          <p>without consecutive applied: {C A1 B}, {C A1 A2 B}, {C A1 A2 A3 B}, {C A1 A2 A3 A4 B}</p>
          </td>
       </tr>
       <tr>
              <td><strong>allowCombinations()</strong><a name="allow_comb_java"></a></td>
              <td>
780 781 782
                <p>Works in conjunction with <code>oneOrMore()</code> and <code>times()</code> and imposes non-deterministic relaxed contiguity
                     between the matching events (as in <code>followedByAny()</code>).</p>
                     <p>If not applied a relaxed contiguity (as in <code>followedBy()</code>) is used.</p>
783

784
      <p>E.g. a pattern like:</p>
785 786 787 788
{% highlight scala %}
Pattern.begin("start").where(_.getName().equals("c"))
  .followedBy("middle").where(_.getName().equals("a"))
                       .oneOrMore().allowCombinations()
789
  .followedBy("end1").where(_.getName().equals("b"))
790
{% endhighlight %}
791

792
                      <p>Will generate the following matches for an input sequence: C D A1 A2 A3 D A4 B</p>
793

794 795 796 797 798 799
                      <p>with combinations enabled: {C A1 B}, {C A1 A2 B}, {C A1 A3 B}, {C A1 A4 B}, {C A1 A2 A3 B}, {C A1 A2 A4 B}, {C A1 A3 A4 B}, {C A1 A2 A3 A4 B}</p>
                      <p>without combinations enabled: {C A1 B}, {C A1 A2 B}, {C A1 A2 A3 B}, {C A1 A2 A3 A4 B}</p>
              </td>
              </tr>
  </tbody>
</table>
800
</div>
801

802
</div>
803

804 805
### Combining Patterns

806
Now that you've seen what an individual pattern can look like, it is time to see how to combine them
807 808 809
into a full pattern sequence.

A pattern sequence has to start with an initial pattern, as shown below:
810

811 812
<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
813
{% highlight java %}
814
Pattern<Event, ?> start = Pattern.<Event>begin("start");
815
{% endhighlight %}
816
</div>
817

818 819
<div data-lang="scala" markdown="1">
{% highlight scala %}
820
val start : Pattern[Event, _] = Pattern.begin("start")
821 822
{% endhighlight %}
</div>
823
</div>
824

825
Next, you can append more patterns to your pattern sequence by specifying the desired *contiguity conditions* between
826
them. In the [previous section](#conditions-on-contiguity) we described the different contiguity modes supported by
827 828
Flink, namely *strict*, *relaxed*, and *non-deterministic relaxed*, and how to apply them in looping patterns. To apply
them between consecutive patterns, you can use:
829

830 831
1. `next()`, for *strict*,
2. `followedBy()`, for *relaxed*, and
832 833
3. `followedByAny()`, for *non-deterministic relaxed* contiguity.

834
or
835 836 837 838

1. `notNext()`, if you do not want an event type to directly follow another
2. `notFollowedBy()`, if you do not want an event type to be anywhere between two other event types

839
{% warn Attention %} A pattern sequence cannot end in `notFollowedBy()`.
840

841
{% warn Attention %} A `NOT` pattern cannot be preceded by an optional one.
842 843 844 845

<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
{% highlight java %}
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861

// strict contiguity
Pattern<Event, ?> strict = start.next("middle").where(...);

// relaxed contiguity
Pattern<Event, ?> relaxed = start.followedBy("middle").where(...);

// non-deterministic relaxed contiguity
Pattern<Event, ?> nonDetermin = start.followedByAny("middle").where(...);

// NOT pattern with strict contiguity
Pattern<Event, ?> strictNot = start.notNext("not").where(...);

// NOT pattern with relaxed contiguity
Pattern<Event, ?> relaxedNot = start.notFollowedBy("not").where(...);

862 863 864 865 866
{% endhighlight %}
</div>

<div data-lang="scala" markdown="1">
{% highlight scala %}
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882

// strict contiguity
val strict: Pattern[Event, _] = start.next("middle").where(...)

// relaxed contiguity
val relaxed: Pattern[Event, _] = start.followedBy("middle").where(...)

// non-deterministic relaxed contiguity
val nonDetermin: Pattern[Event, _] = start.followedByAny("middle").where(...)

// NOT pattern with strict contiguity
val strictNot: Pattern[Event, _] = start.notNext("not").where(...)

// NOT pattern with relaxed contiguity
val relaxedNot: Pattern[Event, _] = start.notFollowedBy("not").where(...)

883 884
{% endhighlight %}
</div>
885
</div>
886

887
Relaxed contiguity means that only the first succeeding matching event will be matched, while
888
with non-deterministic relaxed contiguity, multiple matches will be emitted for the same beginning. As an example,
889
a pattern `a b`, given the event sequence `"a", "c", "b1", "b2"`, will give the following results:
890

891
1. Strict Contiguity between `a` and `b`: `{}` (no match), the `"c"` after `"a"` causes `"a"` to be discarded.
892

893
2. Relaxed Contiguity between `a` and `b`: `{a b1}`, as relaxed continuity is viewed as "skip non-matching events
894
till the next matching one".
895

896
3. Non-Deterministic Relaxed Contiguity between `a` and `b`: `{a b1}`, `{a b2}`, as this is the most general form.
897

898
It's also possible to define a temporal constraint for the pattern to be valid.
899
For example, you can define that a pattern should occur within 10 seconds via the `pattern.within()` method.
900
Temporal patterns are supported for both [processing and event time]({{site.baseurl}}/dev/event_time.html).
901

902
{% warn Attention %} A pattern sequence can only have one temporal constraint. If multiple such constraints are defined on different individual patterns, then the smallest is applied.
903

904 905
<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
906 907 908
{% highlight java %}
next.within(Time.seconds(10));
{% endhighlight %}
909 910 911 912 913 914 915 916
</div>

<div data-lang="scala" markdown="1">
{% highlight scala %}
next.within(Time.seconds(10))
{% endhighlight %}
</div>
</div>
917

918
It's also possible to define a pattern sequence as the condition for `begin`, `followedBy`, `followedByAny` and
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
`next`. The pattern sequence will be considered as the matching condition logically and a `GroupPattern` will be
returned and it is possible to apply `oneOrMore()`, `times(#ofTimes)`, `times(#fromTimes, #toTimes)`, `optional()`,
`consecutive()`, `allowCombinations()` to the `GroupPattern`.

<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
{% highlight java %}

Pattern<Event, ?> start = Pattern.begin(
    Pattern.<Event>begin("start").where(...).followedBy("start_middle").where(...)
);

// strict contiguity
Pattern<Event, ?> strict = start.next(
    Pattern.<Event>begin("next_start").where(...).followedBy("next_middle").where(...)
).times(3);

// relaxed contiguity
Pattern<Event, ?> relaxed = start.followedBy(
    Pattern.<Event>begin("followedby_start").where(...).followedBy("followedby_middle").where(...)
).oneOrMore();

// non-deterministic relaxed contiguity
Pattern<Event, ?> nonDetermin = start.followedByAny(
    Pattern.<Event>begin("followedbyany_start").where(...).followedBy("followedbyany_middle").where(...)
).optional();

{% endhighlight %}
</div>

<div data-lang="scala" markdown="1">
{% highlight scala %}

val start: Pattern[Event, _] = Pattern.begin(
    Pattern.begin[Event, _]("start").where(...).followedBy("start_middle").where(...)
)

// strict contiguity
val strict: Pattern[Event, _] = start.next(
    Pattern.begin[Event, _]("next_start").where(...).followedBy("next_middle").where(...)
).times(3)

// relaxed contiguity
val relaxed: Pattern[Event, _] = start.followedBy(
    Pattern.begin[Event, _]("followedby_start").where(...).followedBy("followedby_middle").where(...)
).oneOrMore()

// non-deterministic relaxed contiguity
val nonDetermin: Pattern[Event, _] = start.followedByAny(
    Pattern.begin[Event, _]("followedbyany_start").where(...).followedBy("followedbyany_middle").where(...)
).optional()

{% endhighlight %}
</div>
</div>

975 976
<br />

977 978
<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
979 980 981 982 983 984 985 986 987
<table class="table table-bordered">
    <thead>
        <tr>
            <th class="text-left" style="width: 25%">Pattern Operation</th>
            <th class="text-center">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
988
            <td><strong>begin(#name)</strong></td>
989
            <td>
990
            <p>Defines a starting pattern:</p>
991 992 993
{% highlight java %}
Pattern<Event, ?> start = Pattern.<Event>begin("start");
{% endhighlight %}
994 995 996
            </td>
        </tr>
        <tr>
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
            <td><strong>begin(#pattern_sequence)</strong></td>
            <td>
            <p>Defines a starting pattern:</p>
{% highlight java %}
Pattern<Event, ?> start = Pattern.<Event>begin(
    Pattern.<Event>begin("start").where(...).followedBy("middle").where(...)
);
{% endhighlight %}
            </td>
        </tr>
        <tr>
            <td><strong>next(#name)</strong></td>
1009
            <td>
1010
                <p>Appends a new pattern. A matching event has to directly succeed the previous matching event
1011
                (strict contiguity):</p>
1012
{% highlight java %}
1013
Pattern<Event, ?> next = start.next("middle");
1014 1015 1016 1017
{% endhighlight %}
            </td>
        </tr>
        <tr>
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
            <td><strong>next(#pattern_sequence)</strong></td>
            <td>
                <p>Appends a new pattern. A sequence of matching events have to directly succeed the previous matching event
                (strict contiguity):</p>
{% highlight java %}
Pattern<Event, ?> next = start.next(
    Pattern.<Event>begin("start").where(...).followedBy("middle").where(...)
);
{% endhighlight %}
            </td>
        </tr>
        <tr>
            <td><strong>followedBy(#name)</strong></td>
1031
            <td>
1032
                <p>Appends a new pattern. Other events can occur between a matching event and the previous
1033
                matching event (relaxed contiguity):</p>
1034
{% highlight java %}
1035
Pattern<Event, ?> followedBy = start.followedBy("middle");
1036 1037 1038 1039
{% endhighlight %}
            </td>
        </tr>
        <tr>
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
            <td><strong>followedBy(#pattern_sequence)</strong></td>
            <td>
                 <p>Appends a new pattern. Other events can occur between a sequence of matching events and the previous
                 matching event (relaxed contiguity):</p>
{% highlight java %}
Pattern<Event, ?> followedBy = start.followedBy(
    Pattern.<Event>begin("start").where(...).followedBy("middle").where(...)
);
{% endhighlight %}
            </td>
        </tr>
        <tr>
            <td><strong>followedByAny(#name)</strong></td>
1053
            <td>
1054 1055
                <p>Appends a new pattern. Other events can occur between a matching event and the previous
                matching event, and alternative matches will be presented for every alternative matching event
1056
                (non-deterministic relaxed contiguity):</p>
1057
{% highlight java %}
1058
Pattern<Event, ?> followedByAny = start.followedByAny("middle");
1059
{% endhighlight %}
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
             </td>
        </tr>
        <tr>
             <td><strong>followedByAny(#pattern_sequence)</strong></td>
             <td>
                 <p>Appends a new pattern. Other events can occur between a sequence of matching events and the previous
                 matching event, and alternative matches will be presented for every alternative sequence of matching events
                 (non-deterministic relaxed contiguity):</p>
{% highlight java %}
Pattern<Event, ?> followedByAny = start.followedByAny(
    Pattern.<Event>begin("start").where(...).followedBy("middle").where(...)
);
{% endhighlight %}
             </td>
1074
        </tr>
1075
        <tr>
1076 1077
                    <td><strong>notNext()</strong></td>
                    <td>
1078
                        <p>Appends a new negative pattern. A matching (negative) event has to directly succeed the
1079
                        previous matching event (strict contiguity) for the partial match to be discarded:</p>
1080 1081 1082
{% highlight java %}
Pattern<Event, ?> notNext = start.notNext("not");
{% endhighlight %}
1083 1084 1085 1086 1087 1088
                    </td>
                </tr>
                <tr>
                    <td><strong>notFollowedBy()</strong></td>
                    <td>
                        <p>Appends a new negative pattern. A partial matching event sequence will be discarded even
1089
                        if other events occur between the matching (negative) event and the previous matching event
1090
                        (relaxed contiguity):</p>
1091 1092 1093
{% highlight java %}
Pattern<Event, ?> notFollowedBy = start.notFllowedBy("not");
{% endhighlight %}
1094 1095
                    </td>
                </tr>
1096
       <tr>
1097
          <td><strong>within(time)</strong></td>
1098
          <td>
1099
              <p>Defines the maximum time interval for an event sequence to match the pattern. If a non-completed event
1100
              sequence exceeds this time, it is discarded:</p>
1101
{% highlight java %}
1102
pattern.within(Time.seconds(10));
1103 1104
{% endhighlight %}
          </td>
1105
       </tr>
1106 1107
  </tbody>
</table>
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
</div>

<div data-lang="scala" markdown="1">
<table class="table table-bordered">
    <thead>
        <tr>
            <th class="text-left" style="width: 25%">Pattern Operation</th>
            <th class="text-center">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
1120
            <td><strong>begin()</strong></td>
1121
            <td>
1122
            <p>Defines a starting pattern:</p>
1123
{% highlight scala %}
1124
val start = Pattern.begin[Event]("start")
1125 1126 1127 1128
{% endhighlight %}
            </td>
        </tr>
        <tr>
1129
            <td><strong>next(#name)</strong></td>
1130
            <td>
1131
                <p>Appends a new pattern. A matching event has to directly succeed the previous matching event
1132
                (strict contiguity):</p>
1133
{% highlight scala %}
1134
val next = start.next("middle")
1135 1136 1137 1138
{% endhighlight %}
            </td>
        </tr>
        <tr>
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
            <td><strong>next(#pattern_sequence)</strong></td>
            <td>
                <p>Appends a new pattern. A sequence of matching events have to directly succeed the previous matching event
                (strict contiguity):</p>
{% highlight scala %}
val next = start.next(
    Pattern.begin[Event]("start").where(...).followedBy("middle").where(...)
)
{% endhighlight %}
            </td>
        </tr>
        <tr>
            <td><strong>followedBy(#name)</strong></td>
1152
            <td>
1153
                <p>Appends a new pattern. Other events can occur between a matching event and the previous
1154
                matching event (relaxed contiguity) :</p>
1155
{% highlight scala %}
1156
val followedBy = start.followedBy("middle")
1157 1158 1159 1160
{% endhighlight %}
            </td>
        </tr>
        <tr>
1161 1162 1163 1164
            <td><strong>followedBy(#pattern_sequence)</strong></td>
            <td>
                <p>Appends a new pattern. Other events can occur between a sequence of matching events and the previous
                matching event (relaxed contiguity) :</p>
1165
{% highlight scala %}
1166 1167 1168
val followedBy = start.followedBy(
    Pattern.begin[Event]("start").where(...).followedBy("middle").where(...)
)
1169
{% endhighlight %}
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
            </td>
        </tr>
        <tr>
            <td><strong>followedByAny(#name)</strong></td>
            <td>
                <p>Appends a new pattern. Other events can occur between a matching event and the previous
                matching event, and alternative matches will be presented for every alternative matching event
                (non-deterministic relaxed contiguity):</p>
{% highlight scala %}
val followedByAny = start.followedByAny("middle")
{% endhighlight %}
            </td>
         </tr>
         <tr>
             <td><strong>followedByAny(#pattern_sequence)</strong></td>
             <td>
                 <p>Appends a new pattern. Other events can occur between a sequence of matching events and the previous
                 matching event, and alternative matches will be presented for every alternative sequence of matching events
                 (non-deterministic relaxed contiguity):</p>
{% highlight scala %}
val followedByAny = start.followedByAny(
    Pattern.begin[Event]("start").where(...).followedBy("middle").where(...)
)
{% endhighlight %}
             </td>
         </tr>
1196

1197 1198 1199
                <tr>
                                    <td><strong>notNext()</strong></td>
                                    <td>
1200
                                        <p>Appends a new negative pattern. A matching (negative) event has to directly succeed the
1201
                                        previous matching event (strict contiguity) for the partial match to be discarded:</p>
1202 1203 1204
{% highlight scala %}
val notNext = start.notNext("not")
{% endhighlight %}
1205 1206 1207 1208 1209 1210
                                    </td>
                                </tr>
                                <tr>
                                    <td><strong>notFollowedBy()</strong></td>
                                    <td>
                                        <p>Appends a new negative pattern. A partial matching event sequence will be discarded even
1211
                                        if other events occur between the matching (negative) event and the previous matching event
1212
                                        (relaxed contiguity):</p>
1213 1214 1215
{% highlight scala %}
val notFollowedBy = start.notFllowedBy("not")
{% endhighlight %}
1216 1217
                                    </td>
                                </tr>
1218

1219
       <tr>
1220
          <td><strong>within(time)</strong></td>
1221
          <td>
1222
              <p>Defines the maximum time interval for an event sequence to match the pattern. If a non-completed event
1223
              sequence exceeds this time, it is discarded:</p>
1224
{% highlight scala %}
1225
pattern.within(Time.seconds(10))
1226 1227 1228 1229 1230 1231 1232 1233
{% endhighlight %}
          </td>
      </tr>
  </tbody>
</table>
</div>

</div>
1234

1235 1236
### After Match Skip Strategy

1237
For a given pattern, the same event may be assigned to multiple successful matches. To control to how many matches an event will be assigned, you need to specify the skip strategy called `AfterMatchSkipStrategy`. There are four types of skip strategies, listed as follows:
1238 1239 1240 1241 1242 1243 1244 1245

* <strong>*NO_SKIP*</strong>: Every possible match will be emitted.
* <strong>*SKIP_PAST_LAST_EVENT*</strong>: Discards every partial match that contains event of the match.
* <strong>*SKIP_TO_FIRST*</strong>: Discards every partial match that contains event of the match preceding the first of *PatternName*.
* <strong>*SKIP_TO_LAST*</strong>: Discards every partial match that contains event of the match preceding the last of *PatternName*.

Notice that when using *SKIP_TO_FIRST* and *SKIP_TO_LAST* skip strategy, a valid *PatternName* should also be specified.

1246
For example, for a given pattern `a b{2}` and a data stream `ab1, ab2, ab3, ab4, ab5, ab6`, the differences between these four skip strategies are as follows:
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332

<table class="table table-bordered">
    <tr>
        <th class="text-left" style="width: 25%">Skip Strategy</th>
        <th class="text-center" style="width: 25%">Result</th>
        <th class="text-center"> Description</th>
    </tr>
    <tr>
        <td><strong>NO_SKIP</strong></td>
        <td>
            <code>ab1 ab2 ab3</code><br>
            <code>ab2 ab3 ab4</code><br>
            <code>ab3 ab4 ab5</code><br>
            <code>ab4 ab5 ab6</code><br>
        </td>
        <td>After found matching <code>ab1 ab2 ab3</code>, the match process will not discard any result.</td>
    </tr>
    <tr>
        <td><strong>SKIP_PAST_LAST_EVENT</strong></td>
        <td>
            <code>ab1 ab2 ab3</code><br>
            <code>ab4 ab5 ab6</code><br>
        </td>
        <td>After found matching <code>ab1 ab2 ab3</code>, the match process will discard all started partial matches.</td>
    </tr>
    <tr>
        <td><strong>SKIP_TO_FIRST</strong>[<code>b</code>]</td>
        <td>
            <code>ab1 ab2 ab3</code><br>
            <code>ab2 ab3 ab4</code><br>
            <code>ab3 ab4 ab5</code><br>
            <code>ab4 ab5 ab6</code><br>
        </td>
        <td>After found matching <code>ab1 ab2 ab3</code>, the match process will discard all partial matches containing <code>ab1</code>, which is the only event that comes before the first <code>b</code>.</td>
    </tr>
    <tr>
        <td><strong>SKIP_TO_LAST</strong>[<code>b</code>]</td>
        <td>
            <code>ab1 ab2 ab3</code><br>
            <code>ab3 ab4 ab5</code><br>
        </td>
        <td>After found matching <code>ab1 ab2 ab3</code>, the match process will discard all partial matches containing <code>ab1</code> and <code>ab2</code>, which are events that comes before the last <code>b</code>.</td>
    </tr>
</table>

To specify which skip strategy to use, just create an `AfterMatchSkipStrategy` by calling:
<table class="table table-bordered">
    <tr>
        <th class="text-left" width="25%">Function</th>
        <th class="text-center">Description</th>
    </tr>
    <tr>
        <td><code>AfterMatchSkipStrategy.noSkip()</code></td>
        <td>Create a <strong>NO_SKIP</strong> skip strategy </td>
    </tr>
    <tr>
        <td><code>AfterMatchSkipStrategy.skipPastLastEvent()</code></td>
        <td>Create a <strong>SKIP_PAST_LAST_EVENT</strong> skip strategy </td>
    </tr>
    <tr>
        <td><code>AfterMatchSkipStrategy.skipToFirst(patternName)</code></td>
        <td>Create a <strong>SKIP_TO_FIRST</strong> skip strategy with the referenced pattern name <i>patternName</i></td>
    </tr>
    <tr>
        <td><code>AfterMatchSkipStrategy.skipToLast(patternName)</code></td>
        <td>Create a <strong>SKIP_TO_LAST</strong> skip strategy with the referenced pattern name <i>patternName</i></td>
    </tr>
</table>

Then apply the skip strategy to a pattern by calling:

<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
{% highlight java %}
AfterMatchSkipStrategy skipStrategy = ...
Pattern.begin("patternName", skipStrategy);
{% endhighlight %}
</div>
<div data-lang="scala" markdown="1">
{% highlight scala %}
val skipStrategy = ...
Pattern.begin("patternName", skipStrategy)
{% endhighlight %}
</div>
</div>

1333
## Detecting Patterns
1334

1335
After specifying the pattern sequence you are looking for, it is time to apply it to your input stream to detect
1336 1337
potential matches. To run a stream of events against your pattern sequence, you have to create a `PatternStream`.
Given an input stream `input`, a pattern `pattern` and an optional comparator `comparator` used to sort events with the same timestamp in case of EventTime or that arrived at the same moment, you create the `PatternStream` by calling:
1338

1339 1340
<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
1341 1342 1343
{% highlight java %}
DataStream<Event> input = ...
Pattern<Event, ?> pattern = ...
1344
EventComparator<Event> comparator = ... // optional
1345

1346
PatternStream<Event> patternStream = CEP.pattern(input, pattern, comparator);
1347
{% endhighlight %}
1348
</div>
1349

1350 1351 1352 1353
<div data-lang="scala" markdown="1">
{% highlight scala %}
val input : DataStream[Event] = ...
val pattern : Pattern[Event, _] = ...
1354
var comparator : EventComparator[Event] = ... // optional
1355

1356
val patternStream: PatternStream[Event] = CEP.pattern(input, pattern, comparator)
1357 1358 1359
{% endhighlight %}
</div>
</div>
1360

1361 1362
The input stream can be *keyed* or *non-keyed* depending on your use-case.

1363
{% warn Attention %} Applying your pattern on a non-keyed stream will result in a job with parallelism equal to 1.
1364

1365
### Selecting from Patterns
1366

1367
Once you have obtained a `PatternStream` you can select from detected event sequences via the `select` or `flatSelect` methods.
1368 1369 1370

<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
1371
The `select()` method requires a `PatternSelectFunction` implementation.
1372
A `PatternSelectFunction` has a `select` method which is called for each matching event sequence.
1373 1374 1375
It receives a match in the form of `Map<String, List<IN>>` where the key is the name of each pattern in your pattern
sequence and the value is a list of all accepted events for that pattern (`IN` is the type of your input elements).
The events for a given pattern are ordered by timestamp. The reason for returning a list of accepted events for each
1376
pattern is that when using looping patterns (e.g. `oneToMany()` and `times()`), more than one event may be accepted for a given pattern. The selection function returns exactly one result.
1377 1378 1379 1380

{% highlight java %}
class MyPatternSelectFunction<IN, OUT> implements PatternSelectFunction<IN, OUT> {
    @Override
1381 1382 1383
    public OUT select(Map<String, List<IN>> pattern) {
        IN startEvent = pattern.get("start").get(0);
        IN endEvent = pattern.get("end").get(0);
1384 1385 1386 1387 1388
        return new OUT(startEvent, endEvent);
    }
}
{% endhighlight %}

1389
A `PatternFlatSelectFunction` is similar to the `PatternSelectFunction`, with the only distinction that it can return an
1390
arbitrary number of results. To do this, the `select` method has an additional `Collector` parameter which is
1391
used to forward your output elements downstream.
1392 1393 1394 1395

{% highlight java %}
class MyPatternFlatSelectFunction<IN, OUT> implements PatternFlatSelectFunction<IN, OUT> {
    @Override
1396
    public void flatSelect(Map<String, List<IN>> pattern, Collector<OUT> collector) {
1397 1398
        IN startEvent = pattern.get("start").get(0);
        IN endEvent = pattern.get("end").get(0);
1399

1400 1401 1402 1403 1404 1405
        for (int i = 0; i < startEvent.getValue(); i++ ) {
            collector.collect(new OUT(startEvent, endEvent));
        }
    }
}
{% endhighlight %}
1406 1407 1408
</div>

<div data-lang="scala" markdown="1">
1409
The `select()` method takes a selection function as argument, which is called for each matching event sequence.
1410 1411
It receives a match in the form of `Map[String, Iterable[IN]]` where the key is the name of each pattern in your pattern
sequence and the value is an Iterable over all accepted events for that pattern (`IN` is the type of your input elements).
1412 1413

The events for a given pattern are ordered by timestamp. The reason for returning an iterable of accepted events for each pattern is that when using looping patterns (e.g. `oneToMany()` and `times()`), more than one event may be accepted for a given pattern. The selection function returns exactly one result per call.
1414 1415

{% highlight scala %}
1416 1417 1418
def selectFn(pattern : Map[String, Iterable[IN]]): OUT = {
    val startEvent = pattern.get("start").get.next
    val endEvent = pattern.get("end").get.next
1419 1420 1421 1422
    OUT(startEvent, endEvent)
}
{% endhighlight %}

1423 1424
The `flatSelect` method is similar to the `select` method. Their only difference is that the function passed to the
`flatSelect` method can return an arbitrary number of results per call. In order to do this, the function for
1425
`flatSelect` has an additional `Collector` parameter which is used to forward your output elements downstream.
1426 1427

{% highlight scala %}
1428 1429 1430
def flatSelectFn(pattern : Map[String, Iterable[IN]], collector : Collector[OUT]) = {
    val startEvent = pattern.get("start").get.next
    val endEvent = pattern.get("end").get.next
1431 1432 1433 1434 1435 1436 1437
    for (i <- 0 to startEvent.getValue) {
        collector.collect(OUT(startEvent, endEvent))
    }
}
{% endhighlight %}
</div>
</div>
1438

1439 1440
### Handling Timed Out Partial Patterns

1441
Whenever a pattern has a window length attached via the `within` keyword, it is possible that partial event sequences
1442 1443
are discarded because they exceed the window length. To react to these timed out partial matches the `select`
and `flatSelect` API calls allow you to specify a timeout handler. This timeout handler is called for each timed out
1444
partial event sequence. The timeout handler receives all the events that have been matched so far by the pattern, and
1445
the timestamp when the timeout was detected.
1446

1447
To treat partial patterns, the `select` and `flatSelect` API calls offer an overloaded version which takes as
1448 1449 1450 1451 1452 1453
parameters

 * `PatternTimeoutFunction`/`PatternFlatTimeoutFunction`
 * [OutputTag]({{ site.baseurl }}/dev/stream/side_output.html) for the side output in which the timeouted matches will be returned
 * and the known `PatternSelectFunction`/`PatternFlatSelectFunction`.

1454 1455 1456
<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">

1457
~~~java
1458 1459
PatternStream<Event> patternStream = CEP.pattern(input, pattern);

1460 1461 1462
OutputTag<String> outputTag = new OutputTag<String>("side-output"){};

SingleOutputStreamOperator<ComplexEvent> result = patternStream.select(
1463
    new PatternTimeoutFunction<Event, TimeoutEvent>() {...},
1464
    outputTag,
1465 1466 1467
    new PatternSelectFunction<Event, ComplexEvent>() {...}
);

1468 1469 1470
DataStream<TimeoutEvent> timeoutResult = result.getSideOutput(outputTag);

SingleOutputStreamOperator<ComplexEvent> flatResult = patternStream.flatSelect(
1471
    new PatternFlatTimeoutFunction<Event, TimeoutEvent>() {...},
1472
    outputTag,
1473 1474
    new PatternFlatSelectFunction<Event, ComplexEvent>() {...}
);
1475 1476 1477

DataStream<TimeoutEvent> timeoutFlatResult = flatResult.getSideOutput(outputTag);
~~~
1478 1479 1480 1481 1482

</div>

<div data-lang="scala" markdown="1">

1483
~~~scala
1484 1485
val patternStream: PatternStream[Event] = CEP.pattern(input, pattern)

1486 1487 1488
val outputTag = OutputTag[String]("side-output")

val result: SingleOutputStreamOperator[ComplexEvent] = patternStream.select(outputTag){
1489
    (pattern: Map[String, Iterable[Event]], timestamp: Long) => TimeoutEvent()
1490
} {
1491
    pattern: Map[String, Iterable[Event]] => ComplexEvent()
1492
}
1493

1494
val timeoutResult: DataStream<TimeoutEvent> = result.getSideOutput(outputTag)
1495
~~~
1496 1497

The `flatSelect` API call offers the same overloaded version which takes as the first parameter a timeout function and as second parameter a selection function.
1498
In contrast to the `select` functions, the `flatSelect` functions are called with a `Collector`. You can use the collector to emit an arbitrary number of events.
1499

1500
~~~scala
1501 1502
val patternStream: PatternStream[Event] = CEP.pattern(input, pattern)

1503 1504 1505
val outputTag = OutputTag[String]("side-output")

val result: SingleOutputStreamOperator[ComplexEvent] = patternStream.flatSelect(outputTag){
1506
    (pattern: Map[String, Iterable[Event]], timestamp: Long, out: Collector[TimeoutEvent]) =>
1507 1508
        out.collect(TimeoutEvent())
} {
1509
    (pattern: mutable.Map[String, Iterable[Event]], out: Collector[ComplexEvent]) =>
1510 1511
        out.collect(ComplexEvent())
}
1512

1513
val timeoutResult: DataStream<TimeoutEvent> = result.getSideOutput(outputTag)
1514
~~~
1515 1516 1517 1518

</div>
</div>

1519
## Handling Lateness in Event Time
1520

1521
In `CEP` the order in which elements are processed matters. To guarantee that elements are processed in the correct order when working in event time, an incoming element is initially put in a buffer where elements are *sorted in ascending order based on their timestamp*, and when a watermark arrives, all the elements in this buffer with timestamps smaller than that of the watermark are processed. This implies that elements between watermarks are processed in event-time order.
1522

1523
{% warn Attention %} The library assumes correctness of the watermark when working in event time.
1524

1525
To guarantee that elements across watermarks are processed in event-time order, Flink's CEP library assumes
1526
*correctness of the watermark*, and considers as *late* elements whose timestamp is smaller than that of the last
1527
seen watermark. Late elements are not further processed.
1528

1529 1530
## Examples

1531
The following example detects the pattern `start, middle(name = "error") -> end(name = "critical")` on a keyed data
1532
stream of `Events`. The events are keyed by their `id`s and a valid pattern has to occur within 10 seconds.
1533 1534
The whole processing is done with event time.

1535 1536
<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
{% highlight java %}
StreamExecutionEnvironment env = ...
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

DataStream<Event> input = ...

DataStream<Event> partitionedInput = input.keyBy(new KeySelector<Event, Integer>() {
	@Override
	public Integer getKey(Event value) throws Exception {
		return value.getId();
	}
});

Pattern<Event, ?> pattern = Pattern.<Event>begin("start")
1551
	.next("middle").where(new SimpleCondition<Event>() {
1552 1553
		@Override
		public boolean filter(Event value) throws Exception {
1554
			return value.getName().equals("error");
1555
		}
1556
	}).followedBy("end").where(new SimpleCondition<Event>() {
1557 1558 1559 1560 1561 1562
		@Override
		public boolean filter(Event value) throws Exception {
			return value.getName().equals("critical");
		}
	}).within(Time.seconds(10));

1563
PatternStream<Event> patternStream = CEP.pattern(partitionedInput, pattern);
1564 1565 1566

DataStream<Alert> alerts = patternStream.select(new PatternSelectFunction<Event, Alert>() {
	@Override
1567
	public Alert select(Map<String, List<Event>> pattern) throws Exception {
1568
		return createAlert(pattern);
1569 1570 1571
	}
});
{% endhighlight %}
1572 1573 1574 1575 1576 1577 1578 1579 1580
</div>

<div data-lang="scala" markdown="1">
{% highlight scala %}
val env : StreamExecutionEnvironment = ...
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)

val input : DataStream[Event] = ...

1581
val partitionedInput = input.keyBy(event => event.getId)
1582

1583 1584 1585
val pattern = Pattern.begin("start")
  .next("middle").where(_.getName == "error")
  .followedBy("end").where(_.getName == "critical")
1586 1587
  .within(Time.seconds(10))

1588
val patternStream = CEP.pattern(partitionedInput, pattern)
1589

1590
val alerts = patternStream.select(createAlert(_)))
1591 1592 1593
{% endhighlight %}
</div>
</div>
1594 1595 1596

## Migrating from an older Flink version

1597 1598 1599
The CEP library in Flink-1.3 ships with a number of new features which have led to some changes in the API. Here we
describe the changes that you need to make to your old CEP jobs, in order to be able to run them with Flink-1.3. After
making these changes and recompiling your job, you will be able to resume its execution from a savepoint taken with the
1600 1601 1602 1603
old version of your job, *i.e.* without having to re-process your past data.

The changes required are:

1604
1. Change your conditions (the ones in the `where(...)` clause) to extend the `SimpleCondition` class instead of
1605 1606 1607 1608 1609 1610
implementing the `FilterFunction` interface.

2. Change your functions provided as arguments to the `select(...)` and `flatSelect(...)` methods to expect a list of
events associated with each pattern (`List` in `Java`, `Iterable` in `Scala`). This is because with the addition of
the looping patterns, multiple input events can match a single (looping) pattern.

1611 1612 1613
3. The `followedBy()` in Flink 1.1 and 1.2 implied `non-deterministic relaxed contiguity` (see
[here](#conditions-on-contiguity)). In Flink 1.3 this has changed and `followedBy()` implies `relaxed contiguity`,
while `followedByAny()` should be used if `non-deterministic relaxed contiguity` is required.
1614 1615

{% top %}