huny
huny

Reputation: 81

How to convert spark streaming output into dataframe or storing in table

My code is:

val lines = KafkaUtils.createStream(ssc, "localhost:2181", "spark-streaming-consumer-group", Map("hello" -> 5))
val data=lines.map(_._2)
data.print()

My output has 50 different values in a format as below

{"id:st04","data:26-02-2018 20:30:40","temp:30", "press:20"}

Can anyone help me in storing this data in a table form as

| id |date               |temp|press|   
|st01|26-02-2018 20:30:40| 30 |20   |  
|st01|26-02-2018 20:30:45| 80 |70   |  

I will really appreciate.

Upvotes: 1

Views: 6056

Answers (1)

T. Gawęda
T. Gawęda

Reputation: 16096

You can use foreachRDD function, together with normal Dataset API:

data.foreachRDD(rdd => {
    // rdd is RDD[String]
    // foreachRDD is executed on the  driver, so you can use SparkSession here; spark is SparkSession, for Spark 1.x use SQLContext
    val df = spark.read.json(rdd); // or sqlContext.read.json(rdd)
    df.show(); 
    df.write.saveAsTable("here some unique table ID");
});

However, if you use Spark 2.x, I would suggest to use Structured Streaming:

val stream = spark.readStream.format("kafka").load()
val data = stream
            .selectExpr("cast(value as string) as value")
            .select(from_json(col("value"), schema))
data.writeStream.format("console").start();

You must manually specify schema, but it's quite simple :) Also import org.apache.spark.sql.functions._ before any processing

Upvotes: 5

Related Questions