4

flink流中是否可以知道本地窗口属于哪个子任务?我想getRuntimeContext().getIndexOfThisSubtask()在实现中使用该方法TriggerPolicy

4

1 回答 1

2

目前无法获取TriggerPolicy正在运行带有 的窗口操作符的子任务的索引。

但是,您可以通过在上游放置一个操作来解决它,该map操作为每个数据元素分配子任务的当前索引。

DataStream<Tuple2<Integer, String>> ds = env.fromElements(
        new Tuple2<Integer, String>(1, "a"),
        new Tuple2<Integer, String>(2, "b"),
        new Tuple2<Integer, String>(1, "c"),
        new Tuple2<Integer, String>(2, "d"));

ds.groupBy(0)
    .map(new RichMapFunction<Tuple2<Integer,String>, Tuple3<Integer, Integer, String>>() {
        @Override
        public Tuple3<Integer, Integer, String> map(Tuple2<Integer, String> integerStringTuple2) throws Exception {
            return new Tuple3<Integer, Integer, String>(
                getRuntimeContext().getIndexOfThisSubtask(),
                integerStringTuple2.f0,
                integerStringTuple2.f1);
        }
    })
    .window(new TestingTriggerPolicy(), new TestingEvictionPolicy())
    .mapWindow(new WindowMapFunction<Tuple3<Integer, Integer, String>, String>() {
        @Override
        public void mapWindow(Iterable<Tuple3<Integer, Integer, String>> iterable, Collector<String> collector) throws Exception {
            StringBuilder builder = new StringBuilder();

            for (Tuple3<Integer, Integer, String> element : iterable) {
                builder.append(element.toString() +"; ");
            }

            collector.collect(builder.toString());
        }
    })
于 2015-09-01T08:00:33.293 回答