스트림의 조인 및 집계
스트림과 테이블 간의 복잡한 조인을 수행하고 데이터를 집계하여 실시간으로 의미 있는 정보를 도출합니다.
스트림의 조인 및 집계은(는) CoddyKit의 무료 Apache Kafka & Stream Processing Fundamentals 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 12
- 레슨
- 48
자주 묻는 질문
“스트림의 조인 및 집계” 강의는 무료인가요?
네 — “스트림의 조인 및 집계” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Apache Kafka & Stream Processing Fundamentals 강의 전체를 잠금 해제할 수 있습니다. Apache Kafka & Stream Processing Fundamentals 강의에는 총 4개의 강의가 포함되어 있습니다.
“스트림의 조인 및 집계”에서 뭘 배우나요?
스트림과 테이블 간의 복잡한 조인을 수행하고 데이터를 집계하여 실시간으로 의미 있는 정보를 도출합니다. 브라우저에서 직접 실행하는 실습 코드로 Apache Kafka & Stream Processing Fundamentals을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Apache Kafka & Stream Processing Fundamentals을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Apache Kafka & Stream Processing Fundamentals은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“스트림의 조인 및 집계” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Apache Kafka & Stream Processing Fundamentals 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Apache Kafka & Stream Processing Fundamentals 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.