<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Amirreza Soudi on Medium]]></title>
        <description><![CDATA[Stories by Amirreza Soudi on Medium]]></description>
        <link>https://medium.com/@amirreza.soudi?source=rss-38641a47824a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qAl53s-OhmQ2Afq-.jpg</url>
            <title>Stories by Amirreza Soudi on Medium</title>
            <link>https://medium.com/@amirreza.soudi?source=rss-38641a47824a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 11:53:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amirreza.soudi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Convert Apache Spark DataFrame into Nested JSON]]></title>
            <link>https://medium.com/@amirreza.soudi/convert-apache-spark-dataframe-into-nested-json-fd2e8576efe1?source=rss-38641a47824a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd2e8576efe1</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[dataframes]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Amirreza Soudi]]></dc:creator>
            <pubDate>Tue, 19 May 2020 04:11:47 GMT</pubDate>
            <atom:updated>2020-05-19T04:11:47.646Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*7FXcww3yHPvo9O7AA5V_Zg.png" /></figure><p>One day I was assigned a task that required me to read some log files via Spark, extract some metrics, and send them to our Kafka cluster.</p><p>It was a pretty easy and straightforward task until I dug deeper and noticed the Kafka consumer expects a specific schema (Nested JSON). I needed to find a way to convert my DataFrame into a nested JSON and then send it to Kafka so the consumer can consume it and write it into DynamoDB.</p><p>To better understand it let me give you an example of input and expected output.</p><blockquote>Example of extracted metrics:</blockquote><pre>+------------+--------------+---------------+-------------+-------+<br>|entity_id   |days_active_7d|days_active_30d|timestamp    |deletes|<br>+------------+--------------+---------------+-------------+-------+<br>|a12sad123123|0             |3              |1589611991631|[]     |<br>+------------+--------------+---------------+-------------+-------+</pre><blockquote>DataFrame Schema:</blockquote><pre>root<br> |-- user_id: string (nullable = true)<br> |-- days_active_7d: long (nullable = true)<br> |-- days_active_30d: long (nullable = true) <br> |-- timestamp: long (nullable = false) <br> |-- deletes: array (nullable = false)<br> |    |-- element: string (containsNull = false)</pre><blockquote>Format that Kafka consumer expects:</blockquote><pre>{<br>  &quot;entity_id&quot;: &quot;a12sad123123&quot;,<br>  &quot;timestamp&quot;: 1589611991631,  <br>  &quot;updates&quot;: {<br>   &quot;days_active_7d&quot;: 0,<br>   &quot;days_active_30d&quot;: 3<br>  },<br>  &quot;deleted&quot;: []<br> }</pre><p>To achieve this, I take advantage of the Scala case classand Spark Datasetand<strong> </strong>to_json<strong>.</strong></p><p>DataFrame needed to convert into a Dataset (<strong><em>strongly-typed</em></strong>)</p><blockquote><strong>val </strong>intermediate: Dataset[EntityNested] = df.as[Entity].map(_.toNested)</blockquote><p>And to do that, we need to specify the schema. This is where the Case classes come into play. By defining case classes, we can manipulate the DataFrame to its final form.</p><p><a href="https://spark.apache.org/docs/2.1.0/api/java/org/apache/spark/sql/functions.html#to_json(org.apache.spark.sql.Column)"><strong><em>to_json</em></strong></a><strong> </strong>Converts a column containing a StructType or ArrayType of StructTypes into a JSON string with the specified schema</p><blockquote>This is a sample code that illustrates the steps</blockquote><pre><strong>import </strong>org.apache.spark.sql.SparkSession<br><strong>import </strong>org.apache.spark.sql.functions.{struct, to_json}<br><strong>import </strong>org.apache.spark.sql.Dataset</pre><pre><strong>object </strong>ConvertDataFrameToNestedJson {</pre><pre>  <strong>case class </strong>EntityNested(entity_id: String,  timestamp: Long, updates: Updates, deletes: Array[String])</pre><pre>  <strong>case class </strong>Updates(days_active_7d: Long, days_active_30d: Long)</pre><pre>  <strong>case class </strong>Entity(entity_id: String, days_active_7d: Long, days_active_30d: Long, timestamp: Long, deletes: Array[String]) {<br>    <strong>def </strong>toNested = <em>EntityNested</em>(entity_id, timestamp,  <em>Updates</em>(days_active_7d, days_active_30d), deletes)<br>  }</pre><pre>  <strong>def </strong>main(args: Array[String]): Unit = {</pre><pre>    <strong>val </strong>spark = SparkSession.<em>builder</em>()<br>      .appName(<strong>this</strong>.getClass.getName)<br>      .master(&quot;local&quot;)<br>      .config(&quot;spark.sql.warehouse.dir&quot;, &quot;file:///tmp/spark-warehouse&quot;)<br>      .config(&quot;spark.sql.shuffle.partitions&quot;, &quot;4&quot;)<br>      .getOrCreate()</pre><pre>    <strong>import </strong>spark.implicits._</pre><pre>    <strong>val </strong>df = <em>Seq</em>(<br>      (&quot;a12sad123123&quot;, 0, 3,  1589611991631l, Array.<em>empty</em>[String])<br>    ).toDF(&quot;entity_id&quot;, &quot;days_active_7d&quot;, &quot;days_active_30d&quot;, &quot;timestamp&quot;,  &quot;deletes&quot;)<br></pre><pre>    // Converting Dataframe to Dataset<br>    <strong>val </strong>intermediate: Dataset[EntityNested]  = df.as[Entity].map(_.toNested)</pre><pre>    // Create JSON formatted column<br>    <strong>val </strong>kafkaDf = intermediate.select($&quot;entity_id&quot;,<br>      <em>to_json</em>(<em>struct</em>($&quot;entity_id&quot;, $&quot;timestamp&quot;,  $&quot;updates&quot;, $&quot;deletes&quot;))<br>        .as(&quot;kafka_value&quot;))</pre><pre>    kafkaDf.show(1, <strong>false</strong>)</pre><pre>    // Writing into Kafka<br>    ...<br>    ...<br>  }<br>}</pre><blockquote>The output will be like this:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*vPV3Ojwyvyq7UjRUajcU2g.png" /><figcaption>Converted DataFrame</figcaption></figure><h3>Write DataFrame Into Kafka</h3><p>We are using AWS EMR with <strong><em>Apache Spark version</em></strong><em> </em><strong><em>2.1.0. </em></strong><em>Since</em> <em>Spark 2.1.0</em> doesn’t support Structured Streaming for Kafka (<a href="https://spark.apache.org/docs/2.1.0/structured-streaming-kafka-integration.html"><strong>2.1.0</strong> Only supports <strong>load</strong></a> not write, they introduce the <a href="https://spark.apache.org/docs/2.2.0/structured-streaming-kafka-integration.html"><strong>write</strong> in <strong>2.2.0</strong></a>), I have decided to write my own Kafka producer (with some inspiration from the internet).</p><p><a href="http://partitionofrecords/">This Post</a> explains how to use <strong>Apache Kafka Clients API </strong>or <strong>Spark Structured Streaming API</strong></p><p>To instantiate the KafkaProducer (which is <strong>not serializable</strong>) on the executors, we need to create a <strong><em>lazy</em></strong> wrapper and <strong><em>broadcast</em></strong> it to each executor. This way, we offload the high-cost action to each executor (<em>Kafka producer is asynchronous and buffers data heavily before sending</em>).</p><pre><strong>import </strong>java.util.Properties<br><strong>import </strong>org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}</pre><pre><strong>class </strong>KafkaProducerWrapper(createProducer: () =&gt; KafkaProducer[String, Any]) <strong>extends </strong>Serializable {</pre><pre><strong>lazy val </strong><em>producer </em>= createProducer()</pre><pre><strong>def </strong>send(topic: String, key: String, value: Any): Unit =<br>    value <strong>match </strong>{<br>      <strong>case </strong>str: String =&gt; <em>producer</em>.send(<strong>new </strong>ProducerRecord(topic, key, str))<br>      <strong>case </strong>bytes: Array[Byte] =&gt; <em>producer</em>.send(<strong>new </strong>ProducerRecord(topic, key, bytes))<br>      <strong>case </strong>_ =&gt; <strong>throw new </strong>Exception(&quot;Kafka Record for this type is not supported&quot;)<br>    }<br>}</pre><pre><strong>object </strong>KafkaProducerWrapper {<br>  <strong>def </strong>apply(properties: Properties): KafkaProducerWrapper = {<br>    <strong>val </strong>f = () =&gt; {<br>      <strong>val </strong>producer = <strong>new </strong>KafkaProducer[String, Any](properties)<br>      sys.<em>addShutdownHook </em>{<br>        producer.close()<br>      }<br>      producer<br>    }<br>    <strong>new </strong>KafkaProducerWrapper(f)<br>  }</pre><p>Another critical point is to use <strong><em>foreachPartition</em></strong> instead of <strong><em>foreach </em></strong>to only initialize Kafka Producer once per partition instead of each record.</p><pre><strong>import </strong>java.util.Properties</pre><pre><strong>import </strong>com.uken.etl.common.KafkaConfig<br><strong>import </strong>org.apache.kafka.clients.CommonClientConfigs<br><strong>import </strong>org.apache.kafka.clients.producer.ProducerConfig<br><strong>import </strong>org.apache.spark.sql.{DataFrame, Row}</pre><pre><strong>object </strong>KafkaProducer {</pre><pre><strong>private def </strong>getKafkaProducerProperties(bootstrap: String): Properties = {</pre><pre><strong>val </strong>p = <strong>new </strong>Properties()<br>    p.setProperty(CommonClientConfigs.<em>BOOTSTRAP_SERVERS_CONFIG</em>, bootstrap)</pre><pre>p.setProperty(ProducerConfig.<em>KEY_SERIALIZER_CLASS_CONFIG</em>, &quot;org.apache.kafka.common.serialization.StringSerializer&quot;)<br>    p.setProperty(ProducerConfig.<em>VALUE_SERIALIZER_CLASS_CONFIG</em>, &quot;org.apache.kafka.common.serialization.StringSerializer&quot;)<br>    p<br>  }</pre><pre><strong>def </strong>writeDataFrameToKafka(df: DataFrame, config: KafkaConfig, key: String, value: String): Unit = {</pre><pre><strong>val </strong>properties = <em>getKafkaProducerProperties</em>(config.<em>kafkaBootstrap</em>)<br>    <strong>val </strong>kafkaProducer = df.sparkSession.sparkContext.broadcast(<em>KafkaProducerWrapper</em>(properties))</pre><pre>df.foreachPartition { partitionOfRecords =&gt;      <br>      <strong>if </strong>(partitionOfRecords.take(1).nonEmpty) {<br>        partitionOfRecords.foreach { message : Row =&gt;<br>          kafkaProducer.value.send(config.<em>kafkaTopic</em>, message.getAs[String](key), message.getAs[String](value))<br>        }<br>      }<br>    }<br>  }<br>}</pre><blockquote>Kafka Config</blockquote><pre><strong>import </strong>org.kohsuke.args4j.Option</pre><pre><strong>trait </strong>KafkaConfig {<br>  @Option(name = &quot;--kafka-zookeeper&quot;, required = <strong>false</strong>, usage = &quot;e.g. localhost:2181&quot;)<br>  <strong>var </strong><em>kafkaZookeeper</em>: String = _</pre><pre>@Option(name = &quot;--kafka-bootstrap&quot;, required = <strong>false</strong>, usage = &quot;e.g.localhost:9092&quot;)<br>  <strong>var </strong><em>kafkaBootstrap</em>: String = _</pre><pre>@Option(name = &quot;--kafka-topic&quot;, required = <strong>false</strong>, usage = &quot;e.g. topic1&quot;)<br>  <strong>var </strong><em>kafkaTopic</em>: String = _<br>}</pre><p>In the end, we can use <strong>KafkaProducer </strong>to write DataFrame Into Kafka by specifying the message Key and the message content:</p><pre><em>/** <br>  * </em><strong><em>@param df </em></strong><em>DataFrame that needed to be written<br>  * </em><strong><em>@param config </em></strong><em>Kafka Cluster configuration (Zookeeper, Broker and Topic name)<br>  * </em><strong><em>@param key </em></strong><em>Kafka Message Key<br>  * </em><strong><em>@param value </em></strong><em>Kafka Message Value<br>  */</em></pre><pre>KafkaProducer.<em>writeDataFrameToKafka</em>(kafkaDf, config, &quot;entity_id&quot;, &quot;kafka_value&quot;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd2e8576efe1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>