我是Kafka Streams的新手。我想执行以下基于KStream-GlobalKTable纯DSL的左联接操作,而不使用map操作。
我有一个输入流a.topic
,它是
{
"b_obj": {
"b_value": "xyz",
"c_list": [
{
"d_obj": {
"d_id1": "value1",
"d_id2": "value2",
"d_value": "some value"
},
"c_value": "jkl"
},
{
"d_obj": {
"d_id1": "value3",
"d_id2": "value4",
"d_value": "some value 2"
},
"c_value": "pqr"
}
]
},
"a_value": "abcd"
}
另一个输入主题e.topic
是
{
"e_id1": "value1",
"e_id2": "value2",
"e_value": "some value"
}
我要执行左联接操作a.topic
是流,而主数据e.topic
是用于实现结果值的全局表
{
"b_obj": {
"b_value": "xyz",
"c_list": [
{
"d_obj": {
"d_id1": "value1",
"d_id2": "value2",
"d_value": "some value"
},
"e_obj": {
"e_id1": "value1",
"e_id2": "value2",
"e_value": "some value a"
},
"c_value": "jkl"
},
{
"d_obj": {
"d_id1": "value3",
"d_id2": "value4",
"d_value": "some value 2"
},
"e_obj": {
"e_id1": "value3",
"e_id2": "value4",
"e_value": "some value b"
},
"c_value": "pqr"
}
]
},
"a_value": "abcd"
}
,加入条件 为a.b.c[i].d.d_id1 == e.e_id1 && a.b.c[i].d.d_id2 == e.e_id2
代码:
public class ComplexBeanStream {
public static void main(String[] args) {
Serde<A> aSerde = new JsonSerde<>(A.class);
Serde<E> eSerde = new JsonSerde<>(E.class);
final Properties streamsConfiguration = new Properties();
streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, "complex-bean-app");
streamsConfiguration.put(StreamsConfig.CLIENT_ID_CONFIG, "complex-bean-client");
streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
StreamsBuilder builder = new StreamsBuilder();
final GlobalKTable<String, E> eGlobalTable =
builder.globalTable(
"e.topic",
Materialized.<String, E, KeyValueStore<Bytes, byte[]>>
as("E-STORE")
.withKeySerde(Serdes.String())
.withValueSerde(eSerde)
);
final KStream<String, A> aStream =
builder.stream(
"a.topic",
Consumed.with(Serdes.String(), aSerde));
// perform left-join here
Topology topology = builder.build();
System.out.println("\n\nComplexBeanStream Topology: \n" + topology.describe());
final KafkaStreams streams = new KafkaStreams(topology, streamsConfiguration);
streams.cleanUp();
streams.start();
Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
}
}
class A {
private B b_obj;
private String a_value;
}
class B {
private List<C> c_list;
private String b_value;
}
class C {
private D d_obj;
private E e_obj;
private String c_value;
}
class D {
private String d_id1;
private String d_id2;
private String d_value;
}
class E {
private String e_id1;
private String e_id2;
private String e_value;
}
答案 0 :(得分:1)
只要您的联接查找基于值而不是键,就不可能没有映射就联接。
Kafka-Streams只能基于双方相同的键来加入。这意味着,您应该在联接的两侧映射并选择新的密钥(重新密钥),以实现a.b.c[i].d.d_id1 == e.e_id1 && a.b.c[i].d.d_id2 == e.e_id2
。
在这种情况下,一侧可以具有[a.b.c[i].d.d_id1, a.b.c[i].d.d_id2]
作为其键,而另一侧可以具有[e.e_id1, e.e_id2]
。如果您有匹配项,则可以将这些值连接到新对象。也许您应该在重新键入键之前对c_list
进行平面映射。
阅读有关Joining的Kafka-Streams也很有帮助。