3

I have three partitions for my Kafka topic and I was wondering if I could read from just one partition out of three. My consumer is spark structured streaming application.

Below is my existing kafka settings in spark.

  val inputDf = spark.readStream
  .format("kafka")
  .option("kafka.bootstrap.servers", brokers)
  .option("subscribe", topic)
  .option("startingOffsets", "latest")
  .load()
hampi2017
  • 701
  • 2
  • 13
  • 33

2 Answers2

5

Here is how you can read from specific partition.

 val inputDf = spark.readStream
  .format("kafka")
  .option("kafka.bootstrap.servers", brokers)
  .option("assign", """{"topic":[0]}""") 
  .option("startingOffsets", "latest")
  .load()

PS: To read from multiple partitions instead of 1--> """{"topic":[0,1,2..n]}"""

Venkata
  • 317
  • 3
  • 13
1

Similarly, How do you write to a specific partition. I tried this and it doesn't work.

        someDF
          .selectExpr("key", "value")
          .writeStream
          .format("kafka")
          .option("kafka.bootstrap.servers", kafkaServers)
          .option("topic", "someTopic")
          .option("partition", partIdx)
          .start()
Anand K
  • 293
  • 3
  • 12