首页 > 解决方案 > Kafka-stream:如何通过从值列表中选择键来重新设置流的键

问题描述

我有一个对象 A :

public class A {
  String id;
  List<String> otherIds;
  SomeOtherObject object;
}

我有一个 kafka 流,看起来像:

KStream<Integer, A> inputStream

我需要重新键入这个inputStream流,以便它现在应该是:

KStream<String, A> newStream

newStream 的关键部分是 来自A.otherIds的otherId

举个例子

Let's say, A is like : { id:1, otherIds:[ "ab","bc","ca"],OtherObject: obj1}.

And inputStream if like <1,A>,

Then the newStream should have:
<"ab",A>
<"bc", A>
<"ca",A>

粗略地说,要了解我正在尝试的是:

 KStream<String,  A> newStream =
        inputStream
                .map((key,val) ->
                                val.getOtherIds().stream().forEach(e->
                        KeyValue.pair(e,val))
                );

有没有办法做到这一点(通过从值列表中选择键来重新键入)?

标签: lambdaapache-kafka-streams

解决方案


由于要将单个记录拆分为多个,因此应使用flatMap()而不是map(). map()是 1:1 操作,而flatMap()是 1:n。

要返回多KeyValue对,您flatMap()可以return使用List<KevValue>例如(任何其他Collection<KeyValue>类型也可以)。


推荐阅读