0Pricing
Apache Kafka & Stream Processing Fundamentals · บทเรียน

แนวคิด KStream และ KTable

แยกแยะ KStream (สตรีมที่ประกอบด้วยระเบียนต่อระเบียน) และ KTable (สตรีมบันทึกการเปลี่ยนแปลงที่แสดงมุมมองแบบจัดเก็บจริง) ใน Kafka Streams

แนวคิด KStream และ KTable เป็นบทเรียน Apache Kafka & Stream Processing Fundamentals ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Apache Kafka & Stream Processing Fundamentals และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Apache Kafka & Stream Processing Fundamentals มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

KStream & KTable Unveiled

In Kafka Streams, KStream and KTable are fundamental data abstractions. They represent different ways to view and process your data.

Understanding their differences is key to building powerful, real-time stream processing applications.

KStream: A Stream of Events

A KStream represents an unbounded, immutable sequence of data records. Think of it like a traditional log or event stream.

  • Each record is treated as a distinct, independent event.
  • Records are processed one by one, in the order they arrive.
  • It never "updates" a previous record; new records are always additions.

It's perfect for handling events like clicks, sensor readings, or financial transactions.

KStream in Action: Filtering

Here's a simple Kafka Streams application that uses a KStream to filter messages. It processes each record individually.

This example will filter a stream of text messages, keeping only those that contain the word "event".

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 java.util.Properties;

public class KStreamFilter {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "kstream-filter-app");
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_BY_KEY_CLASS_CONFIG, Serdes.String().getClass());
        props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_BY_KEY_CLASS_CONFIG, Serdes.String().getClass());

        StreamsBuilder builder = new StreamsBuilder();
        KStream<String, String> sourceStream = builder.stream("input-topic");

        KStream<String, String> filteredStream = sourceStream
            .filter((key, value) -> value.contains("event"));

        filteredStream.to("output-topic");

        KafkaStreams streams = new KafkaStreams(builder.build(), props);
        System.out.println("KStream filter topology created.");
        System.out.println("It filters messages containing 'event'.");
        // In a real application, you would call streams.start();
        // and manage its lifecycle, e.g., using a shutdown hook.
    }
}

KTable: A Dynamic View

A KTable represents a changelog stream, where each record signifies an update or deletion to a row in a table. It's like a database table that's constantly being updated.

  • Each record's value is considered the "latest" value for its key.
  • When a new record arrives with an existing key, it overwrites the previous value.
  • Perfect for maintaining the current state of data.

Think of user profiles, stock prices, or current inventory levels.

KTable in Action: Latest State

This example demonstrates a KTable maintaining the latest value for each key. Imagine tracking the most recent status for various sensors.

When a new message arrives for a sensor, its status in the KTable is updated to the new value.

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 org.apache.kafka.streams.kstream.Materialized;

import java.util.Properties;

public class KTableLatestState {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "ktable-latest-state-app");
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_BY_KEY_CLASS_CONFIG, Serdes.String().getClass());
        props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_BY_KEY_CLASS_CONFIG, Serdes.String().getClass());

        StreamsBuilder builder = new StreamsBuilder();
        KTable<String, String> latestStatusTable = builder
            .table("sensor-updates", Materialized.as("latest-sensor-status"));

        // The KTable is defined. In a real app, you might print
        // its contents to another topic or join it with a KStream.
        // latestStatusTable.toStream().to("latest-status-output-topic");

        KafkaStreams streams = new KafkaStreams(builder.build(), props);
        System.out.println("KTable latest state topology created.");
        System.out.println("It tracks the most recent status for each sensor.");
    }
}

KStream vs. KTable: Key Differences

While both process data, their fundamental nature differs significantly:

  • KStream: Each record is an event. It's a sequence of facts. "Something happened."
  • KTable: Each record is an update. It represents the current state. "This is the current value."

Think of KStream as a transaction log and KTable as the current balance sheet.

When to Use KStream

KStreams are ideal when you need to react to individual events or process data without maintaining a long-term state based on keys.

  • Event logging: Storing every user action.
  • Real-time alerts: Notifying immediately when a specific event occurs.
  • Data enrichment (stateless): Adding information to each event based on its content.
  • Filtering and mapping: Transforming events one by one.

When to Use KTable

KTables are perfect for applications that need to maintain and query the latest state of data, often for aggregations or joins.

  • Current inventory: Tracking stock levels for products.
  • User profiles: Storing the most recent profile details.
  • Aggregations: Counting unique users, summing sales over time (when aggregated results are stored as a KTable).
  • Joining streams with tables: Enriching a KStream with current KTable data.

From Stream to Table: Aggregation

You can transform a KStream into a KTable using stateful operations like aggregation. This converts a series of events into a continuously updated state.

For example, counting occurrences of words from a stream of sentences will result in a KTable where the key is the word and the value is its current count.

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 org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.Produced;

import java.util.Arrays;
import java.util.Properties;

public class KStreamToKTable {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "word-count-app");
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_BY_KEY_CLASS_CONFIG, Serdes.String().getClass());
        props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_BY_KEY_CLASS_CONFIG, Serdes.String().getClass());

        StreamsBuilder builder = new StreamsBuilder();
        KStream<String, String> textLines = builder.stream("text-input");

        KTable<String, Long> wordCounts = textLines
            .flatMapValues(value -> Arrays.asList(value.toLowerCase().split("\\W+")))
            .groupBy((key, word) -> word)
            .count(Materialized.as("counts-store"));

        wordCounts.toStream().to("word-counts-output", Produced.with(Serdes.String(), Serdes.Long()));

        KafkaStreams streams = new KafkaStreams(builder.build(), props);
        System.out.println("KStream to KTable topology created (Word Count).");
        System.out.println("Counts words from 'text-input' and stores counts in a KTable.");
    }
}

KStream vs. KTable Quiz

Which of the following statements accurately describe a KTable?

KStream & KTable Recap

You've learned the core differences between KStream and KTable in Kafka Streams!

  • KStream: An event stream, processing individual, immutable records.
  • KTable: A changelog stream representing a materialized, updatable view of data.

Choosing the right abstraction is crucial for efficient and meaningful real-time data processing. Next, we'll explore stateless vs. stateful operations in Kafka Streams.

คำถามที่พบบ่อย

บทเรียน “แนวคิด KStream และ KTable” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “แนวคิด KStream และ KTable” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Apache Kafka & Stream Processing Fundamentals ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Apache Kafka & Stream Processing Fundamentals มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “แนวคิด KStream และ KTable”

แยกแยะ KStream (สตรีมที่ประกอบด้วยระเบียนต่อระเบียน) และ KTable (สตรีมบันทึกการเปลี่ยนแปลงที่แสดงมุมมองแบบจัดเก็บจริง) ใน Kafka Streams คุณปฏิบัติ Apache Kafka & Stream Processing Fundamentals ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Apache Kafka & Stream Processing Fundamentals หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Apache Kafka & Stream Processing Fundamentals บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “แนวคิด KStream และ KTable” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Apache Kafka & Stream Processing Fundamentals นี้ได้ไหม

ได้ บทเรียน Apache Kafka & Stream Processing Fundamentals ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การสร้างแอป Kafka Streams อย่างง่าย
  2. แนวคิด KStream และ KTable
  3. การดำเนินการแบบไร้สถานะเทียบกับแบบมีสถานะ
  4. Serdes และการทำให้ข้อมูลเป็นอนุกรมใน Kafka Streams
← กลับไปที่ Apache Kafka & Stream Processing Fundamentals