How to Convert DataSet<Row> to DataSet of JSON messages to write to Kafka?

Viewed 1963

I use Spark 2.1.1.

I have the following DataSet<Row> ds1;

 name   | ratio | count  // column names
"hello" |  1.56 | 34 

(ds1.isStreaming gives true)

and I am trying to generate DataSet<String> ds2. other words when I write to a kafka sink I want to write something like this

{"name": "hello", "ratio": 1.56, "count": 34}

I have tried something like this df2.toJSON().writeStream().foreach(new KafkaSink()).start() but then it gives the following error

Queries with streaming sources must be executed with writeStream.start()

There are to_json and json_tuple however I am not sure how to leverage them here ?


I tried the following using json_tuple() function

 Dataset<String> df4 = df3.select(json_tuple(new Column("result"), " name", "ratio", "count")).as(Encoders.STRING());

and I get the following error:

cannot resolve 'result' given input columns: [name, ratio, count];;

1 Answers
Related