0Pricing
Apache Kafka & Stream Processing Fundamentals · 课时

流连接与聚合

执行流与表之间的复杂连接,并聚合数据以实时提取有价值的信息

流连接与聚合 是 CoddyKit 上的免费 Apache Kafka & Stream Processing Fundamentals 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Apache Kafka & Stream Processing Fundamentals 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Apache Kafka & Stream Processing Fundamentals 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Combining Data Streams

In real-world data processing, you often need to combine information from different sources. Imagine tracking user clicks and matching them with user profiles, or correlating an order with its payment details.

Kafka Streams provides powerful operations to join different data streams (KStreams) and tables (KTables) based on a common key. This allows you to enrich your data and derive more complete insights in real-time.

KStream-KStream Joins

A KStream-KStream join combines records from two KStreams based on their shared key. Since KStreams represent unbounded, continuous event streams, these joins require a time window.

  • Events from both streams must arrive within this defined time window to be considered for a join.
  • If an event from one stream arrives outside the window of its matching event in the other stream, they won't be joined.
  • This is crucial for correlating events that happen close together, like a user clicking an ad and then visiting a product page.

KStream-KStream Join Example

This example demonstrates joining two KStreams, streamA and streamB, using a 10-second time window. Only records with the same key arriving within this window will be combined.

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.JoinWindows;
import org.apache.kafka.streams.kstream.KStream;
import java.time.Duration;
import java.util.Properties;

public class StreamStreamJoin {
  public static void main(String[] args) {
    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "stream-join-app");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_BY_KEY_CONFIG, Serdes.String().getClass());
    props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_BY_KEY_CONFIG, Serdes.String().getClass());

    StreamsBuilder builder = new StreamsBuilder();
    KStream<String, String> streamA = builder.stream("topic-A");
    KStream<String, String> streamB = builder.stream("topic-B");

    KStream<String, String> joined = streamA.join(
        streamB,
        (valA, valB) -> "Joined: " + valA + "-" + valB,
        JoinWindows.of(Duration.ofSeconds(10))
    );
    joined.to("joined-topic");

    KafkaStreams streams = new KafkaStreams(builder.build(), props);
    streams.start();
  }
}

KStream-KTable Joins

A KStream-KTable join combines an event stream (KStream) with a materialized view or state table (KTable). This is a very common pattern for data enrichment.

  • When a new record arrives on the KStream, it's joined with the current state of the KTable for the matching key.
  • No time window is explicitly needed for the KTable side, as it always represents the latest known state.
  • Think of it as looking up additional details for an event from a constantly updating database.

KStream-KTable Join Example

Here, a stream of transactions is enriched with data from a user-profiles KTable. Each transaction record gets the latest profile information for its user.

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KTable;
import java.util.Properties;

public class StreamTableJoin {
  public static void main(String[] args) {
    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "stream-table-join-app");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_BY_KEY_CONFIG, Serdes.String().getClass());
    props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_BY_KEY_CONFIG, Serdes.String().getClass());

    StreamsBuilder builder = new StreamsBuilder();
    KStream<String, String> transactions = builder.stream("transactions");
    KTable<String, String> userProfiles = builder.table("user-profiles");

    KStream<String, String> enrichedTransactions = transactions.join(
        userProfiles,
        (transactionVal, profileVal) -> "Tx: " + transactionVal + ", User: " + profileVal
    );
    enrichedTransactions.to("enriched-transactions");

    KafkaStreams streams = new KafkaStreams(builder.build(), props);
    streams.start();
  }
}

KTable-KTable Joins

A KTable-KTable join combines two materialized views (KTables) based on their shared key. This is similar to joining two constantly updating database tables.

  • Whenever a record in either KTable is updated, the join operation is re-evaluated for that key.
  • The output KTable will reflect the combined latest state of the matching records from both input KTables.
  • This is useful for combining different aspects of an entity, like product pricing and inventory levels.

KTable-KTable Join Example

This code joins product-prices and product-stocks KTables. Any update to a product's price or stock will trigger an update to the joined-products KTable.

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KTable;
import java.util.Properties;

public class TableTableJoin {
  public static void main(String[] args) {
    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "table-table-join-app");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_BY_KEY_CONFIG, Serdes.String().getClass());
    props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_BY_KEY_CONFIG, Serdes.String().getClass());

    StreamsBuilder builder = new StreamsBuilder();
    KTable<String, String> productPrices = builder.table("product-prices");
    KTable<String, String> productStocks = builder.table("product-stocks");

    KTable<String, String> joinedProducts = productPrices.join(
        productStocks,
        (price, stock) -> "Price: " + price + ", Stock: " + stock
    );
    joinedProducts.toStream().to("joined-products");

    KafkaStreams streams = new KafkaStreams(builder.build(), props);
    streams.start();
  }
}

Understanding Aggregations

Aggregations are operations that summarize data from a stream or table over a specific key or time window. Common aggregations include:

  • Counting: How many events occurred for a key?
  • Summing: What is the total value for a key?
  • Averaging: What is the average value for a key?
  • Reducing: Combining values using a custom logic.

Aggregations are fundamental for building real-time dashboards, metrics, and summary statistics from continuous data streams.

KStream Aggregation Example

This example demonstrates a simple aggregation: counting user events per user ID within 10-second tumbling windows. The groupByKey() and windowedBy() methods are key here.

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.TimeWindows;
import java.time.Duration;
import java.util.Properties;

public class StreamAggregation {
  public static void main(String[] args) {
    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "stream-aggregation-app");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_BY_KEY_CONFIG, Serdes.String().getClass());
    props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_BY_KEY_CONFIG, Serdes.String().getClass());

    StreamsBuilder builder = new StreamsBuilder();
    KStream<String, String> userEvents = builder.stream("user-events");

    userEvents
        .groupByKey()
        .windowedBy(TimeWindows.of(Duration.ofSeconds(10)))
        .count(Materialized.as("user-event-counts"))
        .toStream((windowedKey, count) -> windowedKey.key())
        .to("user-event-counts-output");

    KafkaStreams streams = new KafkaStreams(builder.build(), props);
    streams.start();
  }
}

Join & Aggregate Check

Which type of Kafka Streams join is typically used for data enrichment, where an incoming event stream is combined with the latest state of a dataset?

Joins & Aggregations Summary

You've learned how Kafka Streams allows you to combine and summarize data in powerful ways:

  • KStream-KStream Joins: Correlate events from two streams within a time window.
  • KStream-KTable Joins: Enrich stream events with the latest state from a table.
  • KTable-KTable Joins: Combine two continuously updating materialized views.
  • Aggregations: Summarize data (e.g., count, sum) over keys and windows to derive real-time insights.

These operations are key to building sophisticated real-time analytics and data processing pipelines with Kafka Streams.

常见问题解答

「流连接与聚合」课时是免费的吗?

是的 — 「流连接与聚合」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Apache Kafka & Stream Processing Fundamentals 课程的其余内容,请升级到 CoddyKit PRO。 Apache Kafka & Stream Processing Fundamentals 课程共包含 4 节课。

「流连接与聚合」这节课中我会学到什么?

执行流与表之间的复杂连接,并聚合数据以实时提取有价值的信息 你通过在浏览器中直接运行的动手代码来练习 Apache Kafka & Stream Processing Fundamentals,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Apache Kafka & Stream Processing Fundamentals 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Apache Kafka & Stream Processing Fundamentals 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「流连接与聚合」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Apache Kafka & Stream Processing Fundamentals 课中编写并运行代码吗?

能。每节 Apache Kafka & Stream Processing Fundamentals 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Kafka Streams 中的窗口操作
  2. 流连接与聚合
  3. Kafka 流分析中的 KSQL 简介
  4. 交互式查询与状态存储
← 返回 Apache Kafka & Stream Processing Fundamentals