How to join a table and a table together

Problem:

you have two Kafka topics representing current state for keys — in other words, reference data. You want to join between two of these tables on a common key.

Edit this page

Example use case:

Suppose you have a set of data about movies and want to add further details such as who the lead actor was. In this tutorial, we'll write a program that joins each movie to another set of data holding information about who the lead actor was for movies.

Code example:

Try it

1
Initialize the project

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

mkdir join-table-and-table && cd join-table-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:5.3.0
    hostname: zookeeper
    container_name: zookeeper
    ports:
      - "2181:2181"
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  broker:
    image: confluentinc/cp-enterprise-kafka:5.3.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_METRIC_REPORTERS: io.confluent.metrics.reporter.ConfluentMetricsReporter
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      CONFLUENT_METRICS_REPORTER_BOOTSTRAP_SERVERS: broker:9092
      CONFLUENT_METRICS_REPORTER_ZOOKEEPER_CONNECT: zookeeper:2181
      CONFLUENT_METRICS_REPORTER_TOPIC_REPLICAS: 1
      CONFLUENT_METRICS_ENABLE: 'true'
      CONFLUENT_SUPPORT_CUSTOMER_ID: 'anonymous'

  schema-registry:
    image: confluentinc/cp-schema-registry:5.3.0
    hostname: schema-registry
    container_name: schema-registry
    depends_on:
      - zookeeper
      - broker
    ports:
      - "8081:8081"
    environment:
      SCHEMA_REGISTRY_HOST_NAME: schema-registry
      SCHEMA_REGISTRY_KAFKASTORE_CONNECTION_URL: 'zookeeper:2181'

  ksql-server:
    image: confluentinc/cp-ksql-server:5.3.0
    hostname: ksql-server
    container_name: ksql-server
    depends_on:
      - broker
      - schema-registry
    ports:
      - "8088:8088"
    environment:
      KSQL_CONFIG_DIR: "/etc/ksql"
      KSQL_LOG4J_OPTS: "-Dlog4j.configuration=file:/etc/ksql/log4j-rolling.properties"
      KSQL_BOOTSTRAP_SERVERS: "broker:9092"
      KSQL_HOST_NAME: ksql-server
      KSQL_LISTENERS: "http://0.0.0.0:8088"
      KSQL_CACHE_MAX_BYTES_BUFFERING: 0
      KSQL_KSQL_SCHEMA_REGISTRY_URL: "http://schema-registry:8081"
      KSQL_PRODUCER_INTERCEPTOR_CLASSES: "io.confluent.monitoring.clients.interceptor.MonitoringProducerInterceptor"
      KSQL_CONSUMER_INTERCEPTOR_CLASSES: "io.confluent.monitoring.clients.interceptor.MonitoringConsumerInterceptor"

  ksql-cli:
    image: confluentinc/cp-ksql-cli:5.3.0
    container_name: ksql-cli
    depends_on:
      - broker
      - ksql-server
    entrypoint: /bin/sh
    tty: true
    volumes:
      - ./src:/opt/app/src
      - ./test:/opt/app/test

And launch it by running:

docker-compose up

3
Write the program interactively using the CLI

To begin developing interactively, open up the KSQL CLI:

docker exec -it ksql-cli ksql http://ksql-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, title VARCHAR, release_year INT)
             WITH (KAFKA_TOPIC='movies',
                   PARTITIONS=1,
                   VALUE_FORMAT='avro');

Likewise, you’ll need a Kafka topic and a second table to represent the additional movie data about leading actor:

CREATE TABLE lead_actor (title VARCHAR, actor_name VARCHAR)
             WITH (KAFKA_TOPIC='lead_actors',
                   PARTITIONS=1,
                   VALUE_FORMAT='avro');

Then insert the following movies:

INSERT INTO MOVIES (ROWKEY, ID, TITLE, RELEASE_YEAR) VALUES ('Die Hard', 294, 'Die Hard', 1998);
INSERT INTO MOVIES (ROWKEY, ID, TITLE, RELEASE_YEAR) VALUES ('The Big Lebowski', 128, 'The Big Lebowski', 1998);
INSERT INTO MOVIES (ROWKEY, ID, TITLE, RELEASE_YEAR) VALUES ('The Godfather', 42, 'The Godfather', 1998);

In a similar manner, populate the lead actor information:

INSERT INTO LEAD_ACTOR (ROWKEY, TITLE, ACTOR_NAME) VALUES ('Die Hard','Die Hard','Bruce Willis');
INSERT INTO LEAD_ACTOR (ROWKEY, TITLE, ACTOR_NAME) VALUES ('The Big Lebowski','The Big Lebowski','Jeff Bridges');
INSERT INTO LEAD_ACTOR (ROWKEY, TITLE, ACTOR_NAME) VALUES ('The Godfather','The Godfather','Al Pacino');

Now that you have events in both tables, let’s join them up to obtain an enriched table of movie information. 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 movie data with more information about who the lead actor in the movie is. The following query does a left join between the movie table and the lead actor table. This will block and continue to return results until it’s limit is reached or you tell it to stop.

SELECT M.ID, M.TITLE, M.RELEASE_YEAR, L.ACTOR_NAME
FROM MOVIES M
INNER JOIN LEAD_ACTOR L
ON M.ROWKEY=L.ROWKEY
LIMIT 3;

This should yield the following output:

294 | Die Hard | 1998 | Bruce Willis
128 | The Big Lebowski | 1998 | Jeff Bridges
42 | The Godfather | 1998 | Al Pacino
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 table that is continuously populated by its query:

CREATE TABLE MOVIES_ENRICHED AS
    SELECT M.ID, M.TITLE, M.RELEASE_YEAR, L.ACTOR_NAME
    FROM MOVIES M
    INNER JOIN LEAD_ACTOR L
    ON M.ROWKEY=L.ROWKEY;

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

PRINT MOVIES_ENRICHED FROM BEGINNING LIMIT 3;

This should yield the following output:

Format:AVRO
7/23/19 11:21:32 AM UTC, Die Hard, {"ID": 294, "M_TITLE": "Die Hard", "RELEASE_YEAR": 1998, "ACTOR_NAME": "Bruce Willis"}
7/23/19 11:21:32 AM UTC, The Big Lebowski, {"ID": 128, "M_TITLE": "The Big Lebowski", "RELEASE_YEAR": 1998, "ACTOR_NAME": "Jeff Bridges"}
7/23/19 11:21:32 AM UTC, The Godfather, {"ID": 42, "M_TITLE": "The Godfather", "RELEASE_YEAR": 1998, "ACTOR_NAME": "Al Pacino"}

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, title VARCHAR, release_year INT)
             WITH (KAFKA_TOPIC='movies',
                   PARTITIONS=1,
                   VALUE_FORMAT='avro');

CREATE TABLE lead_actor (title VARCHAR, actor_name VARCHAR)
             WITH (KAFKA_TOPIC='lead_actors',
                   PARTITIONS=1,
                   VALUE_FORMAT='avro');

CREATE TABLE MOVIES_ENRICHED AS
  SELECT M.ID, M.TITLE, M.RELEASE_YEAR, L.ACTOR_NAME
  FROM MOVIES M
  INNER JOIN LEAD_ACTOR L
  ON M.ROWKEY=L.ROWKEY;

Test it

1
Create the test data

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

{
  "inputs": [
    {
      "topic": "movies",
      "key": "Die Hard",
      "value": {
        "ID": 294,
        "TITLE": "Die Hard",
        "RELEASE_YEAR": 1998
      }
    },
    {
      "topic": "movies",
      "key": "The Big Lebowski",
      "value": {
        "ID": 128,
        "TITLE": "The Big Lebowski",
        "RELEASE_YEAR": 1998
      }
    },
    {
      "topic": "movies",
      "key": "The Godfather",
      "value": {
        "ID": 128,
        "TITLE": "The Godfather",
        "RELEASE_YEAR": 1998
      }
    },
    {
      "topic": "lead_actors",
      "key": "Die Hard",
      "value": {
        "TITLE": "Die Hard",
        "ACTOR_NAME": "Bruce Willis"
      }
    },
    {
      "topic": "lead_actors",
      "key": "The Big Lebowski",
      "value": {
        "TITLE": "The Big Lebowski",
        "ACTOR_NAME": "Jeff Bridges"
      }
    },
    {
      "topic": "lead_actors",
      "key": "The Godfather",
      "value": {
        "TITLE": "The Godfather",
        "ACTOR_NAME": "Al Pacino"
      }
    }
  ]
}

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

{
  "outputs": [
    {
      "topic": "MOVIES_ENRICHED",
      "key": "Die Hard",
      "value": {
        "ID": 294,
        "M_TITLE": "Die Hard",
        "RELEASE_YEAR": 1998,
        "ACTOR_NAME": "Bruce Willis"
      }
    },
    {
      "topic": "MOVIES_ENRICHED",
      "key": "The Big Lebowski",
      "value": {
        "ID": 128,
        "M_TITLE": "The Big Lebowski",
        "RELEASE_YEAR": 1998,
        "ACTOR_NAME": "Jeff Bridges"
      }
    },
    {
      "topic": "MOVIES_ENRICHED",
      "key": "The Godfather",
      "value": {
        "ID": 128,
        "M_TITLE": "The Godfather",
        "RELEASE_YEAR": 1998,
        "ACTOR_NAME": "Al Pacino"
      }
    }
  ]
}

2
Invoke the tests

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

docker exec ksql-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:

statements=$(< src/statements.sql) && \
    echo '{"ksql":"'$statements'", "streamsProperties": {}}' | \
        curl -X "POST" "http://localhost:8088/ksql" \
             -H "Content-Type: application/vnd.ksql.v1+json; charset=utf-8" \
             -d @- | \
        jq