什么时候可能会碰到支持模式匹配涉及先前事件的字段?

时间:2017-02-06 10:23:24

标签: apache-flink flink-cep

能够根据匹配单独条件的事件创建模式的当前能力来匹配事件,这将非常棒。例如,如https://flink.apache.org/news/2016/04/06/cep-monitoring.html所述,我们可以这样做:

Pattern<MonitoringEvent, ?> warningPattern = Pattern.<MonitoringEvent>begin("First Event")
    .subtype(TemperatureEvent.class)
    .where(evt -> evt.getTemperature() >= TEMPERATURE_THRESHOLD)
    .next("Second Event")
    .subtype(TemperatureEvent.class)
    .where(evt -> evt.getTemperature() >= TEMPERATURE_THRESHOLD)
    .within(Time.seconds(10));

然而,用以下功能创建Pattern会很棒:.where(second_evt->evt.getTemperature() == first_evt->evt.getTemperature()

1 个答案:

答案 0 :(得分:0)

如果要比较不同事件中字段的值,可以使用flatSelect方法进行比较,只使用一个非常简单的模式而不使用任何where表达式:

  1. 创建模式:

    Pattern<MonitoringEvent, ?> warningPattern = Pattern.<MonitoringEvent>begin("First Event")
        .subtype(TemperatureEvent.class)
        .next("Second Event")
        .subtype(TemperatureEvent.class)
        .within(Time.seconds(10));
    
  2. 将模式应用于数据流:

    PatternStream<MonitoringEvent> tempPatternStream = CEP.pattern(
        inputEventStream.keyBy("rackID"),
        warningPattern);
    
  3. 检查值并通过flatSelect方法生成新的复杂事件:

    DataStream<TemperatureWarning> warnings = tempPatternStream.flatSelect(
        (Map<String, MonitoringEvent> pattern, Collector<TemperatureAlert> out) -> {
            TemperatureEvent first = (TemperatureEvent) pattern.get("First Event");
            TemperatureEvent second = (TemperatureEvent) pattern.get("Second Event");
    
            if (first.getTemperature() <= second.getTemperature()) {
                out.collect(new TemperatureWarning(
                    first.getRackID(), 
                    (first.getTemperature() + second.getTemperature()) / 2));
            }
        });