How to join a stream and a lookup table

Question:

If I have events in a Kafka topic and a table of reference data (aka a lookup table), how can I join each event in the stream to a piece of data in the table based on a common key?

Edit this page

Example use case:

Suppose you have a set of movies that have been released and a stream of ratings from movie-goers about how entertaining they are. In this tutorial, we'll write a program that joins each rating with content about the movie.

Code example:

Try it

1
Initialize the project

To get started, make a new directory anywhere you’d like for this project:

mkdir join-stream-and-table && cd join-stream-and-table

Then make the following directories to set up its structure:

mkdir src test

2
Get Confluent Platform

Next, create the following docker-compose.yml file to obtain Confluent Platform:

---
version: '2'

services:
  zookeeper:
    image: confluentinc/cp-zookeeper:6.1.0
    hostname: zookeeper
    container_name: zookeeper
    ports:
      - "2181:2181"
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  broker:
    image: confluentinc/cp-kafka:6.1.0
    hostname: broker
    container_name: broker
    depends_on:
      - zookeeper
    ports:
      - "29092:29092"
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:9092,PLAINTEXT_HOST://localhost:29092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0

  schema-registry:
    image: confluentinc/cp-schema-registry:6.1.0
    hostname: schema-registry
    container_name: schema-registry
    depends_on:
      - broker
    ports:
      - "8081:8081"
    environment:
      SCHEMA_REGISTRY_HOST_NAME: schema-registry
      SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS: 'broker:9092'

  ksqldb-server:
    image: confluentinc/ksqldb-server:0.17.0
    hostname: ksqldb-server
    container_name: ksqldb-server
    depends_on:
      - broker
      - schema-registry
    ports:
      - "8088:8088"
    environment:
      KSQL_CONFIG_DIR: "/etc/ksqldb"
      KSQL_LOG4J_OPTS: "-Dlog4j.configuration=file:/etc/ksqldb/log4j.properties"
      KSQL_BOOTSTRAP_SERVERS: "broker:9092"
      KSQL_HOST_NAME: ksqldb-server
      KSQL_LISTENERS: "http://0.0.0.0:8088"
      KSQL_CACHE_MAX_BYTES_BUFFERING: 0
      KSQL_KSQL_SCHEMA_REGISTRY_URL: "http://schema-registry:8081"

  ksqldb-cli:
    image: confluentinc/ksqldb-cli:0.17.0
    container_name: ksqldb-cli
    depends_on:
      - broker
      - ksqldb-server
    entrypoint: /bin/sh
    tty: true
    environment:
      KSQL_CONFIG_DIR: "/etc/ksqldb"
    volumes:
      - ./src:/opt/app/src
      - ./test:/opt/app/test

And launch it by running:

docker-compose up -d

3
Write the program interactively using the CLI

To begin developing interactively, open up the ksqlDB CLI:

docker exec -it ksqldb-cli ksql http://ksqldb-server:8088

First, you’ll need to create a Kafka topic and table to represent the movie reference data. The following creates both in one shot:

CREATE TABLE movies (ID INT PRIMARY KEY, title VARCHAR, release_year INT)
    WITH (kafka_topic='movies', partitions=1, value_format='avro');

Likewise, you’ll need a Kafka topic and a stream to represent the ratings of those movies:

CREATE STREAM ratings (MOVIE_ID INT KEY, rating DOUBLE)
    WITH (kafka_topic='ratings', partitions=1, value_format='avro');

Then insert the following movies:

INSERT INTO movies (id, title, release_year) VALUES (294, 'Die Hard', 1998);
INSERT INTO movies (id, title, release_year) VALUES (354, 'Tree of Life', 2011);
INSERT INTO movies (id, title, release_year) VALUES (782, 'A Walk in the Clouds', 1995);
INSERT INTO movies (id, title, release_year) VALUES (128, 'The Big Lebowski', 1998);
INSERT INTO movies (id, title, release_year) VALUES (780, 'Super Mario Bros.', 1993);

In a similar manner, populate the ratings stream:

INSERT INTO ratings (movie_id, rating) VALUES (294, 8.2);
INSERT INTO ratings (movie_id, rating) VALUES (294, 8.5);
INSERT INTO ratings (movie_id, rating) VALUES (354, 9.9);
INSERT INTO ratings (movie_id, rating) VALUES (354, 9.7);
INSERT INTO ratings (movie_id, rating) VALUES (782, 7.8);
INSERT INTO ratings (movie_id, rating) VALUES (782, 7.7);
INSERT INTO ratings (movie_id, rating) VALUES (128, 8.7);
INSERT INTO ratings (movie_id, rating) VALUES (128, 8.4);
INSERT INTO ratings (movie_id, rating) VALUES (780, 2.1);
Populating Data

One fundamental operation for working with tables is populating them with data. There are a number of ways to do this:

  • Use ksqlDB’s INSERT INTO VALUES syntax.

  • Use the Apache Kafka® clients to write data to the underlying topics.

  • Use connectors to source data from external systems.

This tutorial uses ksqlDB INSERT INTO VALUES syntax. For an example on how to use the Apache Kafka® clients to write data to the underlying topics, see building your first Kafka producer application and for an example on how to use connectors to source data from external systems, see creating a ksqlDB table from PostgresSQL data using Kafka Connect.

Now that you events in both the stream and the table, let’s join them up to obtain a stream of rated movies. The first thing to do is set the following properties to ensure that you’re reading from the beginning of the stream:

SET 'auto.offset.reset' = 'earliest';

Let’s enrich the ratings stream with more information about the movie that it refers to. The following query does a left join between the ratings stream and the movies table on the movie id. This will block and continue to return results until it’s limit is reached or you tell it to stop.

SELECT ratings.movie_id AS ID, title, release_year, rating
   FROM ratings
   LEFT JOIN movies ON ratings.movie_id = movies.id
   EMIT CHANGES LIMIT 9;

This should yield the following output:

+--------------------+--------------------+--------------------+--------------------+
|ID                  |TITLE               |RELEASE_YEAR        |RATING              |
+--------------------+--------------------+--------------------+--------------------+
|294                 |Die Hard            |1998                |8.2                 |
|294                 |Die Hard            |1998                |8.5                 |
|354                 |Tree of Life        |2011                |9.9                 |
|354                 |Tree of Life        |2011                |9.7                 |
|782                 |A Walk in the Clouds|1995                |7.8                 |
|782                 |A Walk in the Clouds|1995                |7.7                 |
|128                 |The Big Lebowski    |1998                |8.7                 |
|128                 |The Big Lebowski    |1998                |8.4                 |
|780                 |Super Mario Bros.   |1993                |2.1                 |
Limit Reached
Query terminated

Since the output looks right, the next step is to make the query continuous. Issue the following to create a new stream that is continuously populated by its query:

CREATE STREAM rated_movies
    WITH (kafka_topic='rated_movies',
          value_format='avro') AS
    SELECT ratings.movie_id as id, title, rating
    FROM ratings
    LEFT JOIN movies ON ratings.movie_id = movies.id;

To check that it’s working, print out the contents of the output stream’s underlying topic:

PRINT rated_movies FROM BEGINNING LIMIT 9;

This should yield the following output:

Key format: KAFKA_INT
Value format: AVRO
rowtime: 2020/05/04 21:49:12.099 Z, key: 294, value: {"TITLE": "Die Hard", "RATING": 8.2}, partition: 0
rowtime: 2020/05/04 21:49:12.174 Z, key: 294, value: {"TITLE": "Die Hard", "RATING": 8.5}, partition: 0
rowtime: 2020/05/04 21:49:12.245 Z, key: 354, value: {"TITLE": "Tree of Life", "RATING": 9.9}, partition: 0
rowtime: 2020/05/04 21:49:12.307 Z, key: 354, value: {"TITLE": "Tree of Life", "RATING": 9.7}, partition: 0
rowtime: 2020/05/04 21:49:12.371 Z, key: 782, value: {"TITLE": "A Walk in the Clouds", "RATING": 7.8}, partition: 0
rowtime: 2020/05/04 21:49:12.446 Z, key: 782, value: {"TITLE": "A Walk in the Clouds", "RATING": 7.7}, partition: 0
rowtime: 2020/05/04 21:49:12.503 Z, key: 128, value: {"TITLE": "The Big Lebowski", "RATING": 8.7}, partition: 0
rowtime: 2020/05/04 21:49:12.576 Z, key: 128, value: {"TITLE": "The Big Lebowski", "RATING": 8.4}, partition: 0
rowtime: 2020/05/04 21:49:12.634 Z, key: 780, value: {"TITLE": "Super Mario Bros.", "RATING": 2.1}, partition: 0
Topic printing ceased

Type 'exit' and hit enter to exit the ksqlDB cli.

4
Write your statements to a file

Now that you have a series of statements that’s doing the right thing, the last step is to put them into a file so that they can be used outside the CLI session. Create a file at src/statements.sql with the following content:

CREATE TABLE movies (ID INT PRIMARY KEY, title VARCHAR, release_year INT)
    WITH (kafka_topic='movies', partitions=1, value_format='avro');

CREATE STREAM ratings (MOVIE_ID INT KEY, rating DOUBLE)
    WITH (kafka_topic='ratings', partitions=1, value_format='avro');

CREATE STREAM rated_movies
    WITH (kafka_topic='rated_movies',
          value_format='avro') AS
    SELECT ratings.movie_id AS id, title, release_year, rating
    FROM ratings
    LEFT JOIN movies ON ratings.movie_id = movies.id;

Test it

1
Create the test data

Create a file at test/input.json with the inputs for testing:

{
  "inputs": [
    {
      "topic": "movies",
      "key": 294,
      "value": {
        "title": "Die Hard",
        "release_year": 1998
      }
    },
    {
      "topic": "movies",
      "key": 354,
      "value": {
        "title": "Tree of Life",
        "release_year": 2011
      }
    },
    {
      "topic": "movies",
      "key": 782,
      "value": {
        "title": "A Walk in the Clouds",
        "release_year": 1995
      }
    },
    {
      "topic": "movies",
      "key": 128,
      "value": {
        "title": "The Big Lebowski",
        "release_year": 1998
      }
    },
    {
      "topic": "movies",
      "key": 780,
      "value": {
        "title": "Super Mario Bros.",
        "release_year": 1993
      }
    },
    {
      "topic": "ratings",
      "key": 294,
      "value": {
        "rating": 8.2
      }
    },
    {
      "topic": "ratings",
      "key": 294,
      "value": {
        "rating": 8.5
      }
    },
    {
      "topic": "ratings",
      "key": 354,
      "value": {
        "rating": 9.9
      }
    },
    {
      "topic": "ratings",
      "key": 354,
      "value": {
        "rating": 9.7
      }
    },
    {
      "topic": "ratings",
      "key": 782,
      "value": {
        "rating": 7.8
      }
    },
    {
      "topic": "ratings",
      "key": 782,
      "value": {
        "rating": 7.7
      }
    },
    {
      "topic": "ratings",
      "key": 128,
      "value": {
        "rating": 8.7
      }
    },
    {
      "topic": "ratings",
      "key": 128,
      "value": {
        "rating": 8.4
      }
    },
    {
      "topic": "ratings",
      "key": 780,
      "value": {
        "rating": 2.1
      }
    }
  ]
}

Similarly, create a file at test/output.json with the expected outputs:

{
  "outputs": [
    {
      "topic": "rated_movies",
      "key": 294,
      "value": {
        "TITLE": "Die Hard",
        "RELEASE_YEAR": 1998,
        "RATING": 8.2
      }
    },
    {
      "topic": "rated_movies",
      "key": 294,
      "value": {
        "TITLE": "Die Hard",
        "RELEASE_YEAR": 1998,
        "RATING": 8.5
      }
    },
    {
      "topic": "rated_movies",
      "key": 354,
      "value": {
        "TITLE": "Tree of Life",
        "RELEASE_YEAR": 2011,
        "RATING": 9.9
      }
    },
    {
      "topic": "rated_movies",
      "key": 354,
      "value": {
        "TITLE": "Tree of Life",
        "RELEASE_YEAR": 2011,
        "RATING": 9.7
      }
    },
    {
      "topic": "rated_movies",
      "key": 782,
      "value": {
        "TITLE": "A Walk in the Clouds",
        "RELEASE_YEAR": 1995,
        "RATING": 7.8
      }
    },
    {
      "topic": "rated_movies",
      "key": 782,
      "value": {
        "TITLE": "A Walk in the Clouds",
        "RELEASE_YEAR": 1995,
        "RATING": 7.7
      }
    },
    {
      "topic": "rated_movies",
      "key": 128,
      "value": {
        "TITLE": "The Big Lebowski",
        "RELEASE_YEAR": 1998,
        "RATING": 8.7
      }
    },
    {
      "topic": "rated_movies",
      "key": 128,
      "value": {
        "TITLE": "The Big Lebowski",
        "RELEASE_YEAR": 1998,
        "RATING": 8.4
      }
    },
    {
      "topic": "rated_movies",
      "key": 780,
      "value": {
        "TITLE": "Super Mario Bros.",
        "RELEASE_YEAR": 1993,
        "RATING": 2.1
      }
    }
  ]
}

2
Invoke the tests

Lastly, invoke the tests using the test runner and the statements file that you created earlier:

docker exec ksqldb-cli ksql-test-runner -i /opt/app/test/input.json -s /opt/app/src/statements.sql -o /opt/app/test/output.json

Which should pass:

	 >>> Test passed!

Take it to production

1
Send the statements to the REST API

Launch your statements into production by sending them to the REST API with the following command:

tr '\n' ' ' < src/statements.sql | \
sed 's/;/;\'$'\n''/g' | \
while read stmt; do
    echo '{"ksql":"'$stmt'", "streamsProperties": {}}' | \
        curl -s -X "POST" "http://localhost:8088/ksql" \
             -H "Content-Type: application/vnd.ksql.v1+json; charset=utf-8" \
             -d @- | \
        jq
done

Deploy on Confluent Cloud

1
Run your app to Confluent Cloud

Instead of running a local Kafka cluster, you may use Confluent Cloud, a fully-managed Apache Kafka service.

  1. Sign up for Confluent Cloud, a fully-managed Apache Kafka service.

  2. After you log in to Confluent Cloud Console, click on Add cloud environment and name the environment learn-kafka. Using a new environment keeps your learning resources separate from your other Confluent Cloud resources.

  3. From the Billing & payment section in the Menu, apply the promo code CC100KTS to receive an additional $100 free usage on Confluent Cloud (details).

  4. Click on LEARN and follow the instructions to launch a Kafka cluster and to enable Schema Registry.

Confluent Cloud

Next, from the Confluent Cloud Console, click on Clients to get the cluster-specific configurations, e.g. Kafka cluster bootstrap servers and credentials, Confluent Cloud Schema Registry and credentials, etc., and set the appropriate parameters in your client application.

Now you’re all set to run your streaming application locally, backed by a Kafka cluster fully managed by Confluent Cloud.