Apache Kafka – Create Topic – Syntax and Examples

Kafka – Create Topic

All the information about Kafka Topics is stored in Zookeeper (Cluster Manager). For each Topic, you may specify the replication factor and the number of partitions. A topic is identified by its name. All these information has to be provided as arguments to the shell script, /kafka-topics.sh, while creating a new Kafka Topic.

Syntax to create Kafka Topic

Following is the syntax to create a topic :

where the arguments are :

<ZOOKEEPER_URL:PORT>IP and port at which zookeeper is running.
<NO_OF_REPLICATIONS>Number of replications that the topic has to maintain in the Kafka Cluster.
<NO_OF_PARTITIONS>Number of partitions into which the Topic has to be partitioned.
<TOPIC_NAME> Name of the Kafka Topic to be created.


Example to Create a Kafka Topic named sampleTopic

To create a topic in Apache Kafka, Zookeeper and Kafka have to be up and running.

Start Zookeeper and Kafka Cluster

Navigate to the root of Kafka directory and run each of the following commands in separate terminals to start Zookeeper and Kafka Cluster.

Run kafka-topics.sh with required arguments

Kafka provides a script, kafka-topics.sh, in the <KAFKA_HOME>/bin/ directory, to create a topic in the Kafka cluster.

An example is given below :

Running the script creates a Topic named sampleTopic  with  replication and  1  partition maintaining metadata in the Zookeeper live at localhost:2181.

Open a terminal from bin directory and run the shell script kafka-topics.sh  as shown below :

create a Topic in Apache Kafka - Apache Kafka Tutorial - www.tutorialkart.com

Created topic “sampleTopic”. : sampleTopic has been created.

Error : Topic already exists.

When you try to create a duplicate topic, you could get an error saying the topic already exists. An example is given below :


Conclusion :

In this Apache Kafka TutorialKafka Create Topic, we have successfully created a Topic in the Kafka cluster.