<?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 Christophe Préaud on Medium]]></title>
        <description><![CDATA[Stories by Christophe Préaud on Medium]]></description>
        <link>https://medium.com/@aquilae?source=rss-1798a63227ad------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Christophe Préaud on Medium</title>
            <link>https://medium.com/@aquilae?source=rss-1798a63227ad------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 14:47:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aquilae/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[Null safe equi-join]]></title>
            <link>https://medium.com/@aquilae/null-safe-equi-join-a9d63bd2ba56?source=rss-1798a63227ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9d63bd2ba56</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[spark-sql]]></category>
            <category><![CDATA[sql-joins]]></category>
            <dc:creator><![CDATA[Christophe Préaud]]></dc:creator>
            <pubDate>Sun, 16 Feb 2025 22:21:35 GMT</pubDate>
            <atom:updated>2025-02-16T22:21:35.367Z</atom:updated>
            <content:encoded><![CDATA[<p><em>originally published on </em><a href="https://preaudc.github.io/tech-articles/NullSafeJoins.html"><em>github</em></a></p><p>The function <a href="https://spark.apache.org/docs/latest/api/scala/org/apache/spark/sql/Dataset.html#join(right:org.apache.spark.sql.Dataset[_],usingColumns:Seq[String],joinType:String):org.apache.spark.sql.DataFrame">join</a> def join(right: Dataset[_], usingColumns: Seq[String], joinType: String): DataFrame is an equi-join, meaning the join of two dataframes is made on a sequence of common columns of these two dataframes. In other words, doing an equi-join is only possible if the join columns of the two dataframes <strong>have the exact same name</strong>.</p><p>Let’s illustrate this with an example:</p><pre>val df1 = Seq(<br>  (&quot;1L&quot;, &quot;aaa&quot;, 111),<br>  (&quot;2L&quot;, &quot;bbb&quot;, 222),<br>  (&quot;3L&quot;, &quot;ccc&quot;, 333),<br>  (&quot;4L&quot;, &quot;ddd&quot;, 444),<br>  (&quot;5L&quot;, &quot;eee&quot;, 555),<br>  (&quot;6L&quot;, &quot;fff&quot;, 666),<br>  (&quot;7L&quot;, null, 777),<br>  (&quot;8L&quot;, &quot;hhh&quot;, 888)<br>).toDF(&quot;id1&quot;, &quot;col_a&quot;, &quot;col_b&quot;)<br>df1.show</pre><pre>+---+-----+-----+<br>|id1|col_a|col_b|<br>+---+-----+-----+<br>| 1L|  aaa|  111|<br>| 2L|  bbb|  222|<br>| 3L|  ccc|  333|<br>| 4L|  ddd|  444|<br>| 5L|  eee|  555|<br>| 6L|  fff|  666|<br>| 7L| NULL|  777|<br>| 8L|  hhh|  888|<br>+---+-----+-----+</pre><pre>val df2 = Seq(<br>  (&quot;11L&quot;, &quot;aaa&quot;, 111),<br>  (&quot;33L&quot;, &quot;ccc&quot;, 333),<br>  (&quot;55L&quot;, &quot;eee&quot;, 555),<br>  (&quot;77L&quot;, null, 777)<br>).toDF(&quot;id2&quot;, &quot;col_a&quot;, &quot;col_b&quot;)<br>df2.show</pre><pre>+---+-----+-----+<br>|id2|col_a|col_b|<br>+---+-----+-----+<br>|11L|  aaa|  111|<br>|33L|  ccc|  333|<br>|55L|  eee|  555|<br>|77L| NULL|  777|<br>+---+-----+-----+<br></pre><pre>// Equi-join between df1 and df2 using a sequence of columns.<br>df1.join(df2, Seq(&quot;col_a&quot;, &quot;col_b&quot;), &quot;inner&quot;).show</pre><pre>+-----+-----+---+---+<br>|col_a|col_b|id1|id2|<br>+-----+-----+---+---+<br>|  aaa|  111| 1L|11L|<br>|  ccc|  333| 3L|33L|<br>|  eee|  555| 5L|55L|<br>+-----+-----+---+---+</pre><p>This method has several advantages over the same join expressed using a join expression:</p><pre>df1.join(<br>  df2,<br>  df1(&quot;col_a&quot;) === df2(&quot;col_a&quot;) &amp;&amp; df1(&quot;col_b&quot;) === df2(&quot;col_b&quot;),<br>  &quot;inner&quot;<br>).show</pre><pre>+---+-----+-----+---+-----+-----+<br>|id1|col_a|col_b|id2|col_a|col_b|<br>+---+-----+-----+---+-----+-----+<br>| 1L|  aaa|  111|11L|  aaa|  111|<br>| 3L|  ccc|  333|33L|  ccc|  333|<br>| 5L|  eee|  555|55L|  eee|  555|<br>+---+-----+-----+---+-----+-----+</pre><ul><li>The syntax is clearer and more concise.</li><li>The join columns will only appear once in the output.</li></ul><p>However, the equality test is not <a href="https://spark.apache.org/docs/latest/api/scala/org/apache/spark/sql/Column.html#%3C=%3E(other:Any):org.apache.spark.sql.Column">null safe</a>, meaning in our example that the row of df1 with id1 == 7L will not be joined to the row of df2 with id2 == 77L (because for the <a href="https://spark.apache.org/docs/latest/api/scala/org/apache/spark/sql/Column.html#===(other:Any):org.apache.spark.sql.Column">standard equality test</a>, (null, 777) != (null, 777)).</p><p><strong>→ As a consequence, we will now try to implement a null safe equi-join.</strong></p><p>Let’s first try with a join expression using null safe equality tests:</p><pre>// Null safe join<br>// Join between df1 and df2 using a join expression<br>//   with null safe equality tests between columns.<br>df1.join(<br>  df2,<br>  df1(&quot;col_a&quot;) &lt;=&gt; df2(&quot;col_a&quot;) &amp;&amp; df1(&quot;col_b&quot;) &lt;=&gt; df2(&quot;col_b&quot;),<br>  &quot;inner&quot;<br>).show</pre><pre>+---+-----+-----+---+-----+-----+<br>|id1|col_a|col_b|id2|col_a|col_b|<br>+---+-----+-----+---+-----+-----+<br>| 1L|  aaa|  111|11L|  aaa|  111|<br>| 3L|  ccc|  333|33L|  ccc|  333|<br>| 5L|  eee|  555|55L|  eee|  555|<br>| 7L| NULL|  777|77L| NULL|  777|<br>+---+-----+-----+---+-----+-----+</pre><p>We can see that:</p><ul><li>The equality test is null safe, i.e. (null, 777) == (null, 777).</li><li>But the join columns appears twice in the output.</li></ul><p>Let’s now try to implement it so that:</p><ul><li>It can be generalized to any sequence of columns.</li><li>The join columns appears only once in the output.</li></ul><pre>import org.apache.spark.sql.DataFrame<br><br>def joinNullSafe(<br>    leftDF: DataFrame,<br>    rightDF: DataFrame,<br>    usingColumns: Seq[String],<br>    joinType: String): DataFrame = {<br>  val joinExprs = forall(<br>    array(usingColumns.map(c =&gt; leftDF(c) &lt;=&gt; rightDF(c)):_*),<br>    identity<br>  )<br>  leftDF.join(rightDF, joinExprs, joinType)<br>    .select((<br>      usingColumns.map(leftDF(_))<br>        ++ (leftDF.columns ++ rightDF.columns).filterNot(<br>          usingColumns.contains(_)<br>        ).map(col)<br>    ):_*)<br>}<br><br>joinNullSafe(df1, df2, Seq(&quot;col_a&quot;, &quot;col_b&quot;), &quot;inner&quot;).show</pre><pre>+-----+-----+---+---+<br>|col_a|col_b|id1|id2|<br>+-----+-----+---+---+<br>|  aaa|  111| 1L|11L|<br>|  ccc|  333| 3L|33L|<br>|  eee|  555| 5L|55L|<br>| NULL|  777| 7L|77L|<br>+-----+-----+---+---+</pre><p><strong>→ We now effectively have implemented a null safe equi-join!</strong></p><h3>Appendix</h3><p>Here is an alternative version of the null safe equi-join, which is based on the property that the equality test between two arrays of columns is null safe by default.</p><pre>// Null safe join - alternative solution<br>// Join between df1 and df2 using a join expression<br>//   with an equality test between array of columns.<br>df1.join(<br>  df2,<br>  array(df1(&quot;col_a&quot;), df1(&quot;col_b&quot;)) === array(df2(&quot;col_a&quot;), df2(&quot;col_b&quot;)),<br>  &quot;inner&quot;<br>).show</pre><pre>+---+-----+-----+---+-----+-----+<br>|id1|col_a|col_b|id2|col_a|col_b|<br>+---+-----+-----+---+-----+-----+<br>| 1L|  aaa|  111|11L|  aaa|  111|<br>| 3L|  ccc|  333|33L|  ccc|  333|<br>| 5L|  eee|  555|55L|  eee|  555|<br>| 7L| NULL|  777|77L| NULL|  777|<br>+---+-----+-----+---+-----+-----+</pre><p>We can see that:</p><ul><li>The equality test is null safe, i.e. (null, 777) == (null, 777).</li><li>But the join columns appears twice in the output.</li></ul><p>This can also be improved like the first solution, i.e. we can deduplicate the join columns and generalize them to any sequence of columns:</p><pre>import org.apache.spark.sql.DataFrame<br><br>def joinNullSafe(<br>    leftDF: DataFrame,<br>    rightDF: DataFrame,<br>    usingColumns: Seq[String],<br>    joinType: String): DataFrame = {<br>  val joinExprs = array(usingColumns.map(leftDF(_)):_*) ===<br>    array(usingColumns.map(rightDF(_)):_*)<br>  leftDF.join(rightDF, joinExprs, joinType)<br>    .select((<br>      usingColumns.map(leftDF(_))<br>        ++ (leftDF.columns ++ rightDF.columns).filterNot(<br>          usingColumns.contains(_)<br>        ).map(col)<br>    ):_*)<br>}<br><br>joinNullSafe(df1, df2, Seq(&quot;col_a&quot;, &quot;col_b&quot;), &quot;inner&quot;).show</pre><pre>+-----+-----+---+---+<br>|col_a|col_b|id1|id2|<br>+-----+-----+---+---+<br>|  aaa|  111| 1L|11L|<br>|  ccc|  333| 3L|33L|<br>|  eee|  555| 5L|55L|<br>| NULL|  777| 7L|77L|<br>+-----+-----+---+---+</pre><h3>A few final words</h3><p>There are many different ways to join dataframes in Spark. You need to focus on using a join implementation that suits your needs, while keeping the code as readable as possible.</p><h3>About the author</h3><p>Christophe Préaud is data architect at Verkor.</p><p>You can connect with him on <a href="https://www.linkedin.com/in/christophe-pr%C3%A9aud-184023155">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9d63bd2ba56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write a Flume Interceptor to modify events header on the fly]]></title>
            <link>https://medium.com/@aquilae/write-a-flume-interceptor-to-modify-events-header-on-the-fly-3546414e29cb?source=rss-1798a63227ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/3546414e29cb</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-architecture]]></category>
            <category><![CDATA[flume]]></category>
            <dc:creator><![CDATA[Christophe Préaud]]></dc:creator>
            <pubDate>Fri, 19 May 2023 19:43:51 GMT</pubDate>
            <atom:updated>2023-11-16T13:38:08.179Z</atom:updated>
            <content:encoded><![CDATA[<p><em>originally published on </em><a href="https://preaudc.github.io/tech-articles/FlumeFileChannel.html"><em>github</em></a></p><p>Apache Flume is an efficient and flexible tool for ingesting and processing large amounts of data in a distributed environment.</p><p>Flume operates in a client-server architecture, where the agents on each machine collect the data and transport it to a centralized Flume server, which then writes the data to the configured data sinks. It supports a variety of data sources, including log files, syslog, netcat, and more. Flume also provides a rich set of plugins and extensions, which makes it highly customizable and extensible.</p><p>Flume is especially suitable for moving large amounts of log data and other streaming data from various sources to a centralized data store such as HDFS.</p><p>This article describes an issue where several Flume agent get stuck for no apparent reason and stop writing data on HDFS.</p><p>I will show you how to investigate and identify the issue, and how to solve it using Flume Interceptors.</p><h3>Flume topology description</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*yCK2QurFrWe1XQk-ixlKSA.png" /></figure><p>rMyLogType is defined as an <a href="https://flume.apache.org/releases/content/1.11.0/FlumeUserGuide.html#avro-source">Avro Source</a>:</p><pre>a1.sources.rMyLogType.type = avro<br>a1.sources.rMyLogType.bind = flume.mycompany.com<br>a1.sources.rMyLogType.port = 44444<br>a1.sources.rMyLogType.channels = cMyLogType</pre><p>cMyLogType is a <a href="https://flume.apache.org/releases/content/1.11.0/FlumeUserGuide.html#file-channel">File Channel</a>. This Flume channel send its events from the rMyLogType source to the kMyLogType sink:</p><pre>a1.channels.cMyLogType.type = file</pre><p>Finally kMyLogType is an <a href="https://flume.apache.org/releases/content/1.11.0/FlumeUserGuide.html#hdfs-sink">HDFS Sink</a>. This Flume sink uses the country header to set the directory path of the file in which the events are written (see %{country} in the a1.sinks.kMyLogType.hdfs.path property below):</p><pre>a1.sinks.kMyLogType.channel = cMyLogType<br>a1.sinks.kMyLogType.type = hdfs<br>a1.sinks.kMyLogType.hdfs.path = hdfs://mycompany-cluster/user/mycompany/logs/flume/myLogType/%{country}/current</pre><h3>Issue and investigation</h3><p><strong><em>In the rest of this article, FLUME_HOME is set to the path to the Flume home directory, e.g. </em></strong><strong><em>FLUME_HOME=/opt/flume</em></strong></p><p>As stated in the preamble to this article, the issue is that several Flume agents suddenly stop writing data on HDFS.</p><p>Luckily, Flume offers several metrics to monitor sources, channels and sinks.</p><p>Let’s see what’s going on:</p><pre># Replace &lt;agent monitoring port&gt; by the numerical monitoring port.<br># The monitoring port of each Flume agent is defined in the configuration<br># file at $FLUME_HOME/conf/flume-env.sh, e.g. AGENT_1_MONITORING_PORT=34545<br>curl -s http://flume.mycompany.com:&lt;agent monitoring port&gt;/metrics | jq -Mr &#39;.[&quot;SOURCE.rMyLogType&quot;]&#39;<br>{<br>  &quot;AppendBatchAcceptedCount&quot;: &quot;5634890&quot;,<br>  &quot;GenericProcessingFail&quot;: &quot;0&quot;,<br>  &quot;EventAcceptedCount&quot;: &quot;28172690&quot;,<br>  &quot;AppendReceivedCount&quot;: &quot;0&quot;,<br>  &quot;StartTime&quot;: &quot;1682500964003&quot;,<br>  &quot;AppendBatchReceivedCount&quot;: &quot;5634890&quot;,<br>  &quot;ChannelWriteFail&quot;: &quot;0&quot;,<br>  &quot;EventReceivedCount&quot;: &quot;28172690&quot;,<br>  &quot;EventReadFail&quot;: &quot;0&quot;,<br>  &quot;Type&quot;: &quot;SOURCE&quot;,<br>  &quot;AppendAcceptedCount&quot;: &quot;0&quot;,<br>  &quot;OpenConnectionCount&quot;: &quot;5&quot;,<br>  &quot;StopTime&quot;: &quot;0&quot;<br>}<br><br>curl -s http://flume.mycompany.com:&lt;agent monitoring port&gt;/metrics | jq -Mr &#39;.[&quot;CHANNEL.cMyLogType&quot;]&#39;<br>{<br>  &quot;Unhealthy&quot;: &quot;0&quot;,<br>  &quot;ChannelSize&quot;: &quot;20&quot;,<br>  &quot;EventTakeAttemptCount&quot;: &quot;31011495&quot;,<br>  &quot;StartTime&quot;: &quot;1682500959364&quot;,<br>  &quot;Open&quot;: &quot;true&quot;,<br>  &quot;CheckpointWriteErrorCount&quot;: &quot;0&quot;,<br>  &quot;ChannelCapacity&quot;: &quot;15000000&quot;,<br>  &quot;ChannelFillPercentage&quot;: &quot;4.5&quot;,<br>  &quot;EventTakeErrorCount&quot;: &quot;0&quot;,<br>  &quot;Type&quot;: &quot;CHANNEL&quot;,<br>  &quot;EventTakeSuccessCount&quot;: &quot;28172755&quot;,<br>  &quot;Closed&quot;: &quot;0&quot;,<br>  &quot;CheckpointBackupWriteErrorCount&quot;: &quot;0&quot;,<br>  &quot;EventPutAttemptCount&quot;: &quot;28172760&quot;,<br>  &quot;EventPutSuccessCount&quot;: &quot;28172760&quot;,<br>  &quot;EventPutErrorCount&quot;: &quot;0&quot;,<br>  &quot;StopTime&quot;: &quot;0&quot;<br>}<br><br>curl -s http://flume.mycompany.com:&lt;agent monitoring port&gt;/metrics | jq -Mr &#39;.[&quot;SINK.kMyLogType&quot;]&#39;<br>{<br>  &quot;ConnectionCreatedCount&quot;: &quot;32109&quot;,<br>  &quot;BatchCompleteCount&quot;: &quot;1192&quot;,<br>  &quot;EventWriteFail&quot;: &quot;0&quot;,<br>  &quot;BatchEmptyCount&quot;: &quot;1310151&quot;,<br>  &quot;EventDrainAttemptCount&quot;: &quot;28172830&quot;,<br>  &quot;StartTime&quot;: &quot;1682500961896&quot;,<br>  &quot;BatchUnderflowCount&quot;: &quot;1528596&quot;,<br>  &quot;ChannelReadFail&quot;: &quot;0&quot;,<br>  &quot;ConnectionFailedCount&quot;: &quot;0&quot;,<br>  &quot;ConnectionClosedCount&quot;: &quot;32073&quot;,<br>  &quot;Type&quot;: &quot;SINK&quot;,<br>  &quot;EventDrainSuccessCount&quot;: &quot;28172830&quot;,<br>  &quot;StopTime&quot;: &quot;0&quot;<br>}</pre><p>The cMyLogType ChannelFillPercentage is suspiciously high, and a more thorough look at it shows that indeed the cMyLogType File Channel fill percentage keeps growing, and therefore the events are stuck in it.</p><pre>curl -s http://flume.mycompany.com:&lt;agent a1 monitoring port&gt;/metrics | jq -Mr &#39;.[&quot;CHANNEL.cMyLogType&quot;] | .ChannelFillPercentage&#39;<br>4.7</pre><p>A look at the Flume agent logs discloses the final hint on what is going on:</p><pre>Caused by: java.lang.IllegalArgumentException: Pathname /user/mycompany/logs/flume/myLogType/fr&#39;;WAITFOR DELAY &#39;0:0:32&#39;--/current/_MyLogType_20220707_14_flume01_a3.1657202736341.seq.tmp from hdfs://mycompany-cluster/user/mycompany/logs/flume/myLogType/fr&#39;;WAITFOR DELAY &#39;0:0:32&#39;--/current/_MyLogType_20220707_14_flume01_a3.1657202736341.seq.tmp is not a valid DFS filename.</pre><p>The problem is that the country header, which should be a 2-character country code, is defined using an unreliable external string field, and can sometimes be set to an invalid value, e.g.:</p><pre>fr&#39;+(select*from(select(sleep(20)))a)+&#39;<br>fr&#39;.)(.,&quot;)).<br>fr&#39;XJdBkx&lt;&#39;&quot;&gt;tHndBx<br>fr&#39;nvOpzp; AND 1=1 OR (&lt;&#39;&quot;&gt;iKO)),<br>fr) AND 1884=1884-- ffjs<br>fr) AND 4904=4904 AND (5459=5459<br>fr) AND 6726=8402 AND (8335=8335<br>fr) AND 8263=3105-- WYZL<br>fr)) AND 1535=5731 AND ((3940=3940<br>fr)) AND 1884=1884-- XkBD<br>fr)) AND 4904=4904 AND ((3073=3073<br>fr)) AND 7007=7794-- lVlA<br>fr)) ORDER BY 1-- Hmpc<br>fr70236806&#39; or 5536=5540--<br>friy3j4h234hjb23234</pre><p>This is inconvenient, but still does not cause more trouble than creating invalid directory names on HDFS.</p><p>However, the country header sometimes contains characters which are invalid for an HDFS directory name, e.g. fr&#39;;WAITFOR DELAY &#39;0:0:32&#39;-- in the above exception. In that case, the Flume agent will raise an IllegalArgumentException.</p><p>Even worse, the event will be stuck in the cMyLogType File Channel, and will block all the following events!</p><p>As a consequence, the File Channel fill percentage will kept growing, as we have experienced earlier.</p><h3>Solution: step-by-step guide</h3><p>The chosen solution is to use <a href="https://flume.apache.org/releases/content/1.11.0/FlumeUserGuide.html#flume-interceptors">Flume Interceptors</a> to modify the country header on the fly.</p><h4>Implement the Interceptor class</h4><p>The interceptor below will set the country header to the first two consecutive alphabetic characters in the original country header and put it in lower case.</p><pre>/**<br> * Licensed to the Apache Software Foundation (ASF) under one<br> * or more contributor license agreements.  See the NOTICE file<br> * distributed with this work for additional information<br> * regarding copyright ownership.  The ASF licenses this file<br> * to you under the Apache License, Version 2.0 (the<br> * &quot;License&quot;); you may not use this file except in compliance<br> * with the License.  You may obtain a copy of the License at<br> *<br> *     http://www.apache.org/licenses/LICENSE-2.0<br> *<br> * Unless required by applicable law or agreed to in writing, software<br> * distributed under the License is distributed on an &quot;AS IS&quot; BASIS,<br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<br> * See the License for the specific language governing permissions and<br> * limitations under the License.<br> */<br><br>package com.mycompany.flume.interceptor;<br><br>import java.util.List;<br>import java.util.Map;<br><br>import org.apache.flume.Context;<br>import org.apache.flume.Event;<br>import org.apache.flume.interceptor.Interceptor;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br><br>/**<br> * Interceptor class which modifies the country header (if it exists).<br> *<br> * It drops all except the first two consecutive alphabetic characters and converts them to lower case.<br> * If the country header does not contain two consecutive alphabetic characters, it drops all characters<br> * except the first two ones.<br> *<br> * Sample config:&lt;p&gt;<br> *<br> * &lt;code&gt;<br> *   agent.sources.r1.channels = c1&lt;p&gt;<br> *   agent.sources.r1.type = SEQ&lt;p&gt;<br> *   agent.sources.r1.interceptors = i1&lt;p&gt;<br> *   agent.sources.r1.interceptors.i1.type = com.mycompany.flume.interceptor.FixCountryHeaderInterceptor$Builder&lt;p&gt;<br> * &lt;/code&gt;<br> *<br> */<br>public class FixCountryHeaderInterceptor implements Interceptor {<br><br>  private static final Logger logger = LoggerFactory.getLogger(FixCountryHeaderInterceptor.class);<br><br>  private final String countryKey = &quot;country&quot;;<br><br>  /**<br>   * Only {@link HostInterceptor.Builder} can build me<br>   */<br>  private FixCountryHeaderInterceptor() {<br>    // no-op<br>  }<br><br>  @Override<br>  public void initialize() {<br>    // no-op<br>  }<br><br>  /**<br>   * Modifies events in-place.<br>   */<br>  @Override<br>  public Event intercept(Event event) {<br>    Map&lt;String, String&gt; headers = event.getHeaders();<br><br>    if (headers.containsKey(countryKey)) {<br>      String origCountry = headers.get(countryKey);<br>      String fixedCountry = origCountry.replaceFirst(&quot;^[^A-Za-z]*([A-Za-z]{2}).*$&quot;, &quot;$1&quot;)<br>        .replaceFirst(&quot;^(..).*$&quot;, &quot;$1&quot;)<br>        .toLowerCase();<br>      if (!fixedCountry.equals(origCountry)) {<br>        headers.put(countryKey, fixedCountry);<br>        logger.info(&quot;Replaced &quot; + countryKey + &quot; header, from &lt;&quot; + origCountry + &quot;&gt; to &lt;&quot; + fixedCountry + &quot;&gt;&quot;);<br>      }<br>    }<br><br>    return event;<br>  }<br><br>  /**<br>   * Delegates to {@link #intercept(Event)} in a loop.<br>   * @param events<br>   * @return<br>   */<br>  @Override<br>  public List&lt;Event&gt; intercept(List&lt;Event&gt; events) {<br>    for (Event event : events) {<br>      intercept(event);<br>    }<br>    return events;<br>  }<br><br>  @Override<br>  public void close() {<br>    // no-op<br>  }<br><br>  /**<br>   * Builder which builds new instance of the FixCountryHeaderInterceptor.<br>   */<br>  public static class Builder implements Interceptor.Builder {<br><br>    @Override<br>    public void configure(Context context) {<br>      // no-op<br>    }<br><br>    @Override<br>    public Interceptor build() {<br>      logger.info(&quot;Creating FixCountryHeaderInterceptor&quot;);<br>      return new FixCountryHeaderInterceptor();<br>    }<br><br>  }<br><br>}</pre><p>I now need to compile this class into a jar (let’s call it flume-interceptors-1.0.0.jar) and distribute it with flume at $FLUME_HOME/lib/flume-interceptors-1.0.0.jar.</p><h4>Define the interceptor topology</h4><p>The next step is to define a new topology (dubbed interceptor topology) which makes use of this interceptor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*fDIksEoUpTpYHHAo4_P-MQ.png" /></figure><p>I only need to define the interceptor i1 in the Avro Source:</p><pre>a1.sources.rMyLogType.type = avro<br>a1.sources.rMyLogType.bind = flume.mycompany.com<br>a1.sources.rMyLogType.port = 44444<br>a1.sources.rMyLogType.channels = cMyLogType<br>a1.sources.rMyLogType.interceptors = i1<br>a1.sources.rMyLogType.interceptors.i1.type = com.mycompany.flume.interceptor.FixCountryHeaderInterceptor$Builder<br><br>a1.channels.cMyLogType.type = file<br><br>a1.sinks.kMyLogType.channel = cMyLogType<br>a1.sinks.kMyLogType.type = hdfs<br>a1.sinks.kMyLogType.hdfs.path = hdfs://mycompany-cluster/user/mycompany/logs/flume/myLogType/%{country}/current</pre><p>However, if this topology is deployed now, new events will have their header fixed but the ones already stuck in the rMyLogType file channel won’t be impacted. This is because a Flume interceptor can only be applied on a Flume source, whereas the events, because of the original topology, are stuck in the cMyLogType File Channel!</p><p>As a consequence, I need first to define a temporary topology to flush the file channel (dubbed flushFileChannel topology) before using the interceptor topology above.</p><h4>Define the flushFileChannel topology</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eBcxUAmv97JSgECuMxuiFA.png" /></figure><pre>a1.sources.rMyLogType.type = avro<br>a1.sources.rMyLogType.bind = flume.mycompany.com<br>a1.sources.rMyLogType.port = 44444<br>a1.sources.rMyLogType.channels = cMyLogType<br><br>a1.channels.cMyLogType.type = file<br><br>a1.sinks.kMyLogTypeAvro.channel = cMyLogType<br>a1.sinks.kMyLogTypeAvro.type = avro<br>a1.sinks.kMyLogTypeAvro.hostname = localhost<br>a1.sinks.kMyLogTypeAvro.port = 44445<br><br>a1.sources.rMyLogTypeAvro.type = avro<br>a1.sources.rMyLogTypeAvro.bind = localhost<br>a1.sources.rMyLogTypeAvro.port = 44445<br>a1.sources.rMyLogTypeAvro.channels = cMyLogTypeAvro<br>a1.sources.rMyLogTypeAvro.interceptors = i1<br>a1.sources.rMyLogTypeAvro.interceptors.i1.type = com.mycompany.flume.interceptor.FixCountryHeaderInterceptor$Builder<br><br>a1.channels.cMyLogTypeAvro.type = file<br><br>a1.sinks.kMyLogType.channel = cMyLogTypeAvro<br>a1.sinks.kMyLogType.type = hdfs<br>a1.sinks.kMyLogType.hdfs.path = hdfs://mycompany-cluster/user/mycompany/logs/flume/myLogType/%{country}/current</pre><p>That way, I can:</p><ul><li>flush the events from the cMyLogType channel into the kMyLogTypeAvro avro sink.</li><li>fix the country header (drop all characters except the first two consecutive alphabetic ones) in the rMyLogTypeAvro Avro Source using the above Flume interceptor.</li><li>write the events with a now fixed country header in the kMyLogType HDFS Sink (by routing them through cMyLogTypeAvro File Channel).</li></ul><h4>Flush the File Channel</h4><p>Set the flushFileChannel topology described above in $FLUME_HOME/conf/flume-conf.properties, restart the impacted Flume agents, and wait for the cMyLogType File Channel fill percentage to decrease down to 0%.</p><p>For example for agent i1 (wait until ChannelFillPercentage is close to 0):</p><pre>curl -s http://flume.mycompany.com:&lt;agent a1 monitoring port&gt;/metrics | jq -Mr &quot;.[\&quot;CHANNEL.channel_Impression_storeInHdfs\&quot;] | .ChannelFillPercentage&quot;</pre><h4>Deploy the interceptor topology</h4><p>Now that the cMyLogType File Channel is completely empty, I can stop Flume and deploy the simpler interceptor topology above.</p><p>This will allow me to:</p><ul><li>fix the country header (drop all characters except the first two consecutive alphabetic ones) in the rMyLogType Avro Source using a custom Flume interceptor.</li><li>write the events with fixed country header in kMyLogType HDFS Sink (by routing them through cMyLogType File Channel).</li></ul><p>Set the interceptor topology described above in $FLUME_HOME/conf/flume-conf.properties and restart all Flume agents to load the interceptorTopology.</p><h3>A few final words</h3><p>Flume Interceptors are a powerful tool to modify/drop events on the fly.</p><p>The documentation for writing a Flume Interceptor is quite sparse, but once you got the knack of it it is quite simple.</p><p>After that, it is mainly a matter of plumbing (I mean topology!) to get what you want!</p><h3>About the author</h3><p>Christophe Préaud is data architect at Verkor.</p><p>You can connect with him on <a href="https://www.linkedin.com/in/christophe-pr%C3%A9aud-184023155">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3546414e29cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark: Jobs and Stages]]></title>
            <link>https://medium.com/@aquilae/spark-jobs-and-stages-3d24dd424971?source=rss-1798a63227ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d24dd424971</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Christophe Préaud]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 21:28:03 GMT</pubDate>
            <atom:updated>2025-02-16T21:50:47.437Z</atom:updated>
            <content:encoded><![CDATA[<p><em>originally published on </em><a href="https://preaudc.github.io/tech-articles/SparkJobsAndStages.html"><em>github</em></a></p><p>Spark is an open source scalable engine to process your data, whether in batches or real-time streaming.</p><p>In order to optimize performance and resource usage, you have to understand how Spark processes your data and more specifically how it splits its work into jobs and stages.</p><h4>Glossary</h4><ul><li><strong>Transformation</strong>: lazy evaluated Dataset operation which returns a Dataset (see <strong><em>Typed transformations</em></strong> and <strong><em>Untyped transformations</em></strong> in the <a href="http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.Dataset">Spark Dataset scaladoc</a>)<br>- Narrow transformation: The data required to compute the records in a single Partition resides in at most one Partition of the parent Dataset (no shuffle)<br>- Wide transformation: The data required to compute the records in a single Partition may reside in many Partitions of the parent Dataset (i.e. it triggers a shuffle operation, see below)</li><li><strong>Action</strong>: Dataset operation which returns a result to the driver (i.e. is evaluated and triggers the evaluation of previous transformations on the Dataset)</li><li><strong>Task</strong>: a unit of work that will be sent to one executor and done by a single thread</li><li><strong>Slot</strong>: the number of Tasks that can be processed simultaneously by the Spark application. The total number of Slots is <strong><em>number of executors × number of cores</em></strong> reserved for the Spark application</li><li><strong>Job</strong>: several transformation(s) followed by (exactly) one action</li><li><strong>Stage</strong>: several narrow transformations followed by (exactly) one wide transformation</li><li><strong>Shuffle</strong>: a shuffle operation is triggered when data needs to be moved between executors:<br>- data is written from RAM to local disk on the source executor<br>- the data is sent to another executor (the driver decides which executor gets which piece of data)<br>- the data is copied back into RAM on the destination executor</li></ul><h4>Example: Write Job</h4><pre>+------+---------+-----------------------+<br>| Step | Method  | Operation             |<br>+------+---------+-----------------------+<br>| 1    | Read    | Narrow transformation |<br>| 2    | Filter  | Narrow transformation |<br>| 3    | Map     | Narrow transformation |<br>| 4    | GroupBy | Wide transformation   |<br>| 5    | Filter  | Narrow transformation |<br>| 6    | Map     | Narrow transformation |<br>| 7    | Write   | Action                |<br>+------+---------+-----------------------+</pre><p>Step 4 is a stage boundary: a new stage is created to process all remaining Steps (5, 6, 7).</p><p>The synchronization between Tasks is done with a shuffle operation (i.e. data is moved between executors).</p><p>Hence, the Write job will be broken down into two stages:</p><h4>Stage 1</h4><pre>+---------+---------------+<br>| Step    | Method        |<br>+---------+---------------+<br>| 1       | Read          |<br>| 2       | Filter        |<br>| 3       | Map           |<br>| 4a      | GroupBy 1/2   |<br>| 4b      | shuffle write |<br>+---------+---------------+</pre><p>Step 4 is a stage boundary: all the Tasks must synchronize (i.e. all partitions must complete <strong>Stage 1</strong> before continuing to <strong>Stage 2</strong>).</p><h4>Stage 2</h4><pre>+---------+--------------+<br>| Step    | Method       |<br>+---------+--------------+<br>| 4c      | shuffle read |<br>| 4d      | GroupBy 2/2  |<br>| 5       | Filter       |<br>| 6       | Map          |<br>| 7       | Write        |<br>+---------+--------------+</pre><p>In more details:</p><figure><img alt="Spark jobs and stages — step 1" src="https://cdn-images-1.medium.com/max/400/1*V3LNo2oAPw6Dwnw0AWGHWg.png" /></figure><p>Four slots have been reserved for the Spark application. The file to read is split into 6 partitions (P1 to P6).</p><p>In <strong>Stage 1</strong>, Spark will create a pipeline of transformations in which the data is read into RAM (Step 1), and then perform Steps 2, 3, 4a and 4b on each partition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*LqvGAC2NAT4hKTs-MMzjdA.jpeg" /></figure><p>All four slots read a partition of the data into RAM (Step 1).</p><figure><img alt="Spark jobs and stages — step 3" src="https://cdn-images-1.medium.com/max/400/1*hK94lZLD3Gl86DxWUtm9IQ.png" /></figure><p>Some partitions are quicker to process than others, a slot can performs next steps in <strong>Stage 1</strong> for this partition without waiting for other partitions.</p><figure><img alt="Spark jobs and stages — step 4" src="https://cdn-images-1.medium.com/max/400/1*WSv6UZ2u91qbfHTw2PPtvQ.png" /></figure><p>Step 4 is a stage boundary, all slots at this step (Slot 2, 3 and 4) must write shuffle data for this partition (Step 4b).</p><figure><img alt="Spark jobs and stages — step 5" src="https://cdn-images-1.medium.com/max/400/1*HJiQPzm8uFo8OkfUoTdbAg.png" /></figure><p>Then process another partition (Slot 2 and 3 now process partitions P5 and P6, Slot 4 is still writing shuffle data for P4).</p><figure><img alt="Spark jobs and stages — step 6" src="https://cdn-images-1.medium.com/max/400/1*uYNZjg5ilEbDOby_cmXIJQ.png" /></figure><p>Notice that Slot 1 and Slot 4 are not working, they cannot be assigned a new Task as long as <strong>Stage 1</strong> is not finished.</p><p>When partitions P1 to P6 have finished Step 4b (i.e. they have finished writing their shuffle files), <strong>Stage 1</strong> is finished and <strong>Stage 2</strong> begins.</p><p>In <strong>Stage 2</strong>, Spark will create a pipeline of transformations in which the shuffle files are read into RAM (Step 4c), and then perform Steps 4d, 5, 6 and 7 on each partition.</p><figure><img alt="Spark jobs and stages — step 7" src="https://cdn-images-1.medium.com/max/400/1*hRrbhEobEESmy0t7c4o_Og.png" /></figure><p>All four slots read shuffle files into RAM (Step 4c).</p><p>And so on…</p><figure><img alt="Spark jobs and stages — DAG" src="https://cdn-images-1.medium.com/max/362/1*Mm34xMw05BgugBylGGZuvg.png" /></figure><h4>Building a house (the job) analogy</h4><ul><li>The first stage would be to lay the foundation.</li><li>The second stage would be to erect the walls.</li><li>The third stage would be to add the room.</li></ul><p>Then each stage can be broken down into several operations, e.g. for the first stage:</p><ul><li>digs trenches</li><li>pours concrete</li></ul><p>Each operation in each stage is handled by tasks which can be done independently (i.e. you can start pouring the concrete in one trench even if other trenches are still being dug).</p><p>However, you have to wait for all first stage tasks to be finished before starting to erect the walls.</p><h3>A few final words</h3><p>Understanding how Spark works under the hood will be a great help in diagnosing problems and/or performance issues.A few final words</p><p>Understanding how Spark works under the hood will be a great help in diagnosing problems and/or performance issues.</p><h3>About the author</h3><p>Christophe Préaud is data architect at Verkor.</p><p>You can connect with him on <a href="https://www.linkedin.com/in/christophe-pr%C3%A9aud-184023155">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d24dd424971" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark — good practices: some common caveats and solutions]]></title>
            <link>https://medium.com/@aquilae/spark-good-practices-some-common-caveats-and-solutions-ce0e9eeab84?source=rss-1798a63227ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce0e9eeab84</guid>
            <category><![CDATA[coding-tips]]></category>
            <category><![CDATA[spark-sql]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Christophe Préaud]]></dc:creator>
            <pubDate>Tue, 18 Oct 2022 19:44:21 GMT</pubDate>
            <atom:updated>2025-02-16T22:03:05.259Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spark — good practices: some common caveats and solutions</h3><p><em>originally published on </em><a href="https://preaudc.github.io/tech-articles/SparkGoodPractices"><em>github</em></a></p><p>Spark is an open source scalable engine to process your data, whether in batches or real-time streaming.</p><p>It has become widely popular, however it can be also quite complex, and it takes time exploiting it correctly.</p><p>Here are below some common mistakes — and their solutions — and also some useful tips for making your work with Spark easier.</p><h3>never collect a Dataset</h3><p>Never collect — quoted from the Spark Scaladoc:</p><pre>(collect) should only be used if the resulting array is expected to be small,<br>as all the data is loaded into the driver&#39;s memory</pre><pre>ds.collect()  // NOT OK - is long and has a good chance<br>              // of crashing the driver, unless ds is small<br>ds.show()     // OK - displays only the first 20 rows of ds<br>ds.write.parquet(...)  // OK - saves the content of ds<br>                       // out into external storage</pre><h3>evaluate as little as possible</h3><p>Quoted from the Spark Scaladoc:</p><pre>Operations available on Datasets are divided into transformations and actions.<br>Transformations are the ones that produce new Datasets, and actions are the<br>ones that trigger computation and return results (...).<br>Datasets are &quot;lazy&quot;, i.e. computations are only triggered when an action is<br>invoked.</pre><p>In other words, you should limit the number of actions you apply on your Dataset, since each action will trigger a costly computation, while all transformations are lazily evaluated.</p><p>Though it is not always possible, the ideal would be to call an action on your Dataset only once. Nevertheless, avoid calling an action on your Dataset unless it is necessary.</p><p>For example, doing a count (which is an action) for log printing should be avoided.</p><p>dsOut is computed twice in the exemple below:</p><pre>case class Data(id: Long, desc: String, price: Double)<br>val ds = Seq(<br>  Data(1, &quot;a&quot;, 123), Data(2, &quot;b&quot;, 234), Data(3, &quot;c&quot;, 345),<br>  Data(4, &quot;a&quot;, 234), Data(5, &quot;a&quot;, 345), Data(6, &quot;b&quot;, 123),<br>  Data(7, &quot;a&quot;, 234), Data(8, &quot;c&quot;, 345), Data(9, &quot;a&quot;, 234),<br>  Data(10, &quot;b&quot;, 234)).toDS<br>val dsOut = ds.map({ line =&gt;<br>   line.copy(desc = s&quot;this is a &#39;${line.desc}&#39;&quot;)<br>})<br>println(s&quot;num elements: ${dsOut.count}&quot;)  // 1st dsOut computation<br>dsOut.show                                // 2nd dsOut computation</pre><p>The simplest and preferable solution would be to skip the print, but if it is absolutely necessary you can use accumulators instead:</p><pre>val accum = sc.longAccumulator(&quot;num elements in ds&quot;)<br>val dsOut = ds.map({ line =&gt;<br>   accum.add(1)<br>   line.copy(desc = s&quot;this is a &#39;${line.desc}&#39;&quot;)<br>})<br>dsOut.show  // single dsOut computation<br>println(s&quot;num elements: ${accum.value}&quot;)</pre><h3>avoid unnecessary SparkSession parameter</h3><p>It is not necessary to pass the SparkSession as a function parameter if this function already has a Dataset[T] or DataFrame parameter. Indeed, a Dataset[T] or DataFrame already contains a reference to the SparkSession.</p><p>For example:</p><pre>def f(ds: Dataset[String], spark: SparkSession) = {<br>  import spark.implicits._<br>  // ...<br>}</pre><p>can be replaced by:</p><pre>def f(ds: Dataset[String]) = {<br>  import ds.sparkSession.implicits._<br>  // ...<br>}</pre><p>Similarly:</p><pre>def f(df: DataFrame, spark: SparkSession) = {<br>  import spark.implicits._<br>  // ...<br>}</pre><p>can be replaced by:</p><pre>def f(df: DataFrame) = {<br>  import df.sparkSession.implicits._<br>  // ...<br>}</pre><h3>remove extra columns when mapping a Dataset to a case class with fewer columns</h3><p>When a Dataset[T] is mapped to Dataset[U] (Dataset[T].as[U]), with U being a subclass of T with fewer columns, the resulting Dataset will still contain the extra columns.</p><p>Let’s illustrate this with an example:</p><pre>case class Data(f1: String, f2: String, f3: String, f4: String)<br>case class ShortData(f1: String, f2: String, f3: String)<br>val ds = Seq(<br>  Data(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;), Data(&quot;e&quot;, &quot;f&quot;, &quot;g&quot;, &quot;h&quot;),<br>  Data(&quot;i&quot;, &quot;j&quot;, &quot;k&quot;, &quot;l&quot;)).toDS<br>ds.as[ShortData].show<br>// will output:<br>// +---+---+---+---+<br>// | f1| f2| f3| f4|<br>// +---+---+---+---+<br>// |  a|  b|  c|  d|<br>// |  e|  f|  g|  h|<br>// |  i|  j|  k|  l|<br>// +---+---+---+---+</pre><p>We would have expected only columns f1, f2 and f3, but in fact, even the schema still contain the extra column f4!</p><pre>ds.as[ShortData].printSchema<br>// will output:<br>// root<br>//  |-- f1: string (nullable = true)<br>//  |-- f2: string (nullable = true)<br>//  |-- f3: string (nullable = true)<br>//  |-- f4: string (nullable = true)</pre><p>This is due to Dataset[T].as[U] type resolution being lazy. Adding a transformation (even a transformation doing nothing!) will force Spark to evaluate the type and fix the issue:</p><pre>ds.as[ShortData].map(identity).show<br>// will output:<br>// +---+---+---+<br>// | f1| f2| f3|<br>// +---+---+---+<br>// |  a|  b|  c|<br>// |  e|  f|  g|<br>// |  i|  j|  k|<br>// +---+---+---+<br>ds.as[ShortData].map(identity).printSchema<br>// will output:<br>// root<br>//  |-- f1: string (nullable = true)<br>//  |-- f2: string (nullable = true)<br>//  |-- f3: string (nullable = true)</pre><h3>always specify schema when reading files (parquet, json or csv) into a DataFrame</h3><p>Let’s begin with a Dataset mapped on case class TestData:</p><pre>case class TestData(id: Long, desc: String)<br>import spark.implicits._<br>import org.apache.spark.sql.SaveMode<br>val ds = Seq(<br>  TestData(1L, &quot;a&quot;), TestData(2L, &quot;b&quot;), TestData(3L, &quot;c&quot;),<br>  TestData(4L, &quot;d&quot;), TestData(5L, &quot;e&quot;)).toDS<br>ds.show<br>// will output:<br>// +---+----+<br>// | id|desc|<br>// +---+----+<br>// |  1|   a|<br>// |  2|   b|<br>// |  3|   c|<br>// |  4|   d|<br>// |  5|   e|<br>// +---+----+<br>// save ds locally<br>val localFile = &quot;file:///home/cpreaud/output/test_schema_change&quot;<br>ds.repartition(1).write.mode(SaveMode.Overwrite).parquet(localFile)</pre><p>Now let’s add a new field comment in case class TestData</p><pre>case class TestData(id: Long, desc: String, comment: String)</pre><p>We’re hitting an error when we try to map the parquet file loaded as a Dataset to the new definition of TestData, because the schema of the parquet file and the schema of TestData do not match anymore:</p><pre>val dsRead = spark.read.parquet(localFile).as[TestData]<br>// will output:<br>// org.apache.spark.sql.AnalysisException: cannot resolve &#39;comment&#39; given input columns: [desc, id]<br>//  at org.apache.spark.sql.catalyst.analysis.package$AnalysisErrorAt.failAnalysis(package.scala:54)<br>// (...)</pre><p>It works correctly if the schema is enforced when the parquet file is read:</p><pre>import org.apache.spark.sql.Encoders<br>val schema = Encoders.product[TestData].schema<br>val dsRead = spark.read.schema(schema).parquet(localFile).as[TestData]<br>dsRead.show<br>// will output:<br>// +---+----+-------+<br>// | id|desc|comment|<br>// +---+----+-------+<br>// |  1|   a|   null|<br>// |  2|   b|   null|<br>// |  3|   c|   null|<br>// |  4|   d|   null|<br>// |  5|   e|   null|<br>// +---+----+-------+</pre><p>P.S.: Here is the corresponding JIRA issue: <a href="https://issues.apache.org/jira/browse/SPARK-19477">SPARK-19477</a>.</p><h3>avoid union performance penalties when reading parquet files</h3><p>Doing a union to produce a single Dataset from several parquet files loaded as Datasets takes a lot more time than loading all the parquet files at once into a single Dataset.</p><p>Let’s load each parquet file into a Dataset and union all these Datasets to produce a single Dataset:</p><pre>import org.apache.hadoop.fs.{FileSystem, Path}<br>import org.apache.spark.sql.Encoders<br>import SaleRecord<br>val fs = FileSystem.get(sc.hadoopConfiguration)<br>val saleSchema = Encoders.product[SaleRecord].schema<br>fs.globStatus(new Path(&quot;/path/to/sale/data/*/2022/202203/202203*&quot;))<br>    .map(_.getPath.toString)<br>    .foldLeft(spark.emptyDataset[SaleRecord])((acc, path) =&gt;<br>      acc.union(<br>        spark.read.schema(saleSchema)<br>          .parquet(path).as[SaleRecord]<br>      )<br>    ).count</pre><p>→ Took 12 min</p><p>Let’s have a look at the Spark UI for more understanding on what’s going on.</p><ul><li>the DAG for the union of Datasets is huge (the image below display only a small part of the DAG):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/0*tCCFZGoSBrPHnXmp.png" /></figure><ul><li>analyzing this complex DAG takes time: there is a big pause at the start of the application:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*74cOAHKTY5qGfzBA.png" /></figure><p>Now let’s load all parquet files at once into a single Dataset:</p><pre>import org.apache.hadoop.fs.{FileSystem, Path}<br>import org.apache.spark.sql.Encoders<br>import SaleRecord<br>val fs = FileSystem.get(sc.hadoopConfiguration)<br>val saleSchema = Encoders.product[SaleRecord].schema<br>val listSales = fs<br>  .globStatus(new Path(&quot;/path/to/sale/data/*/2022/202203/202203*&quot;))<br>  .map(_.getPath.toString)<br>spark.read<br>  .schema(saleSchema)<br>  .parquet(listSales:_*)<br>  .as[SaleRecord]<br>  .count</pre><p>→ Took only 2.1 min</p><p>The Spark UI confirms that things are better now.</p><ul><li>the DAG is very simple as you can see:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/0*yuhVuRtPzVXhUUmd.png" /></figure><ul><li>there is no pause at the start of the application:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*q0gk7lPpXlV3qvkA.png" /></figure><h3>prefer select over withColumn when adding multiple columns</h3><p>withColumn should be avoided when adding multiple columns. Quoted from <a href="https://github.com/apache/spark/blob/v3.3.0/sql/core/src/main/scala/org/apache/spark/sql/Dataset.scala#L2472-L2475">Spark source code</a>:</p><pre>[`withColumn`] introduces a projection internally. Therefore, calling it multiple times,<br>for instance, via loops in order to add multiple columns can generate big plans which<br>can cause performance issues and even `StackOverflowException`. To avoid this,<br>use `select` with the multiple columns at once.`</pre><p>Let’s illustrate this by adding columns to df:</p><pre>val df = Seq((1L, &quot;a&quot;), (2L, &quot;b&quot;), (3L, &quot;c&quot;)).toDF(&quot;uid&quot;, &quot;desc&quot;)<br>df.show<br>// will output:<br>// +---+----+<br>// |uid|desc|<br>// +---+----+<br>// |  1|   a|<br>// |  2|   b|<br>// |  3|   c|<br>// +---+----+</pre><p>Add two columns “col1” and “col2” with withColumn:</p><pre>df.withColumn(&quot;col1&quot;, lit(&quot;val1&quot;))<br>  .withColumn(&quot;col2&quot;, lit(&quot;val2&quot;))<br>  .show<br>// will output:<br>// +---+----+----+----+<br>// |uid|desc|col1|col2|<br>// +---+----+----+----+<br>// |  1|   a|val1|val2|<br>// |  2|   b|val1|val2|<br>// |  3|   c|val1|val2|<br>// +---+----+----+----+</pre><p>Add two columns “col1” and “col2” with select:</p><pre>df.select((<br>      df.columns.map(col(_)) :+   // get list of columns<br>                                  // in df as a Seq[Column]<br>      lit(&quot;val1&quot;).as(&quot;col1&quot;) :+   // add Column &quot;col1&quot;<br>      lit(&quot;val2&quot;).as(&quot;col2&quot;)      // add Column &quot;col2&quot;<br>    ):_*                          // un-pack the Seq[Column]<br>                                  // into arguments <br>  ).show<br>// will output:<br>// +---+----+----+----+<br>// |uid|desc|col1|col2|<br>// +---+----+----+----+<br>// |  1|   a|val1|val2|<br>// |  2|   b|val1|val2|<br>// |  3|   c|val1|val2|<br>// +---+----+----+----+</pre><p>N.B.: always prefer the select implementation when adding multiple columns!</p><h3>A few final words</h3><p>Spark versatility comes with a certain level of complexity, I hope that this article will help you writing better applications.</p><h3>About the author</h3><p>Christophe Préaud is data architect at Verkor.</p><p>You can connect with him on <a href="https://www.linkedin.com/in/christophe-pr%C3%A9aud-184023155">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce0e9eeab84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exclude Spark dependencies from your Spark applications component]]></title>
            <link>https://medium.com/@aquilae/exclude-spark-dependencies-from-your-spark-applications-component-8cff333e9f7b?source=rss-1798a63227ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cff333e9f7b</guid>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[dependency-management]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[packaging]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[Christophe Préaud]]></dc:creator>
            <pubDate>Sun, 12 Jun 2022 16:04:05 GMT</pubDate>
            <atom:updated>2023-11-16T13:40:59.926Z</atom:updated>
            <content:encoded><![CDATA[<p><em>originally published on </em><a href="https://preaudc.github.io/spark-maven-parent"><em>github</em></a></p><p>A Spark application component is frequently oversized because it contains jars (i.e. Spark, Scala, or even Hadoop jars) which are already included by Spark / Hadoop.</p><p>Besides, these jars are useless because by default Spark always gives precedence to jars provided by Spark / Hadoop over the ones packaged with the Spark applications component.</p><p>On the other hand, it is sometimes necessary to include a more recent version of a jar already included by Spark / Hadoop, but it would be dangerous to always give precedence to jars packaged with the Spark applications component, because they could include jars with the wrong Hadoop, Spark or Scala version.</p><p>Common solutions to this issue consist in either to:</p><ul><li>Shade the dependencies in common by e.g. using the maven-shade-plugin.</li><li>Package all your dependencies (Spark + Spark applications) in an über jar.</li></ul><p>I will present below a third solution, which allows to automatically exclude from the Spark applications component the dependencies in common with Spark / Hadoop.<br>Additionally, it provides a safe way to override some of these dependencies when necessary.</p><h3>Step-by-step guide</h3><p>This solution consists in:</p><ol><li>Creating a parent POM <strong>spark-maven-parent</strong> which will include all the Spark / Hadoop dependencies with a <strong>provided</strong> scope (see e.g. this example: <a href="https://github.com/preaudc/spark-maven-parent/blob/master/pom.xml.template">pom.xml.template</a>)</li><li>Set the parent POM of your Spark applications component to <strong>spark-maven-parent</strong> so that all Spark / Hadoop dependencies are automatically excluded at the packaging step.</li></ol><h3>1. Create a parent POM with all the Spark / Hadoop dependencies</h3><p>Listing and writing down the more than 200 Spark / Hadoop dependencies being a bit tedious, I have created a quick &amp; dirty python helper script (<a href="https://github.com/preaudc/spark-maven-parent/blob/master/create-spark-parent-pom.py">create-spark-parent-pom.py</a>) for that purpose.</p><h4>1.1 Edit the configuration file (<a href="https://github.com/preaudc/spark-maven-parent/blob/master/conf/create-spark-parent-pom.yaml">conf/create-spark-parent-pom.yaml</a>) and adapt the lines below (at the top of the file) to your environment</h4><pre>project_pom:<br>  &#39;group_id&#39;: &#39;my.group.id&#39;<br>  &#39;artifact_id&#39;: &#39;spark-maven-parent&#39;<br>  &#39;version&#39;: &#39;1.0.0-SNAPSHOT&#39;<br>  &#39;description&#39;: &#39;Parent POM for Spark applications components&#39;<br>properties_version:<br>  &#39;jdk_version&#39;: &#39;1.8&#39;</pre><h4>1.2 Launch the script with the command below to generate the parent POM spark-maven-parent template</h4><pre># the command below creates a file pom.xml.template<br>./create-spark-parent-pom.py --provided --output-file pom.xml.template JARS_FILE</pre><p><strong>N.B.: JARS_FILE</strong> is a file containing all the path of the the Spark / Hadoop jars dependencies, you can create it for example with the steps below:</p><ul><li>create a <strong>extlib</strong> directory to store (Hadoop and) Spark jars</li><li>copy Hadoop jars in <strong>extlib/hadoop</strong> (if you use a pre-built Apache Spark package with user-provided Apache Hadoop)</li><li>copy Spark jars in <strong>extlib/spark</strong></li><li>create the <strong>JARS_FILE</strong> with the following command:</li></ul><pre>find extlib/{spark,hadoop} -type f ! -name &quot;*-tests.jar&quot; 2&gt;/dev/null &gt; hadoop_spark_jars.list</pre><p>The <strong>create-spark-parent-pom.py</strong> script will scan the <strong>$HOME/.m2 </strong>repository on your local machine to try to get the group and artifact ids using the SHA1SUM of the Spark / Hadoop jar. If unsuccessful, it will try to get the group id from a web service on <em>search.maven.org</em> using the SHA1SUM of the jar as parameter.</p><h4>1.3 Complete / update the parent POM spark-maven-parent template and rename it to <strong>pom.xml</strong></h4><h4>1.4 Compile and deploy it</h4><h3>2. Update your Spark applications component POM</h3><h4>2.1 Set the POM parent to spark-maven-parent</h4><pre>&lt;parent&gt;<br>   &lt;groupId&gt;my.group.id&lt;/groupId&gt;<br>   &lt;artifactId&gt;spark-maven-parent&lt;/artifactId&gt;<br>   &lt;version&gt;1.0.0&lt;/version&gt;<br>&lt;/parent&gt;</pre><h4>2.2 Add hadoop-client dependency if necessary (it is NOT provided by Spark / Hadoop)</h4><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.apache.hadoop&lt;/groupId&gt;<br>   &lt;artifactId&gt;hadoop-client&lt;/artifactId&gt;<br>   &lt;version&gt;${hadoop.version}&lt;/version&gt;<br>&lt;/dependency&gt;</pre><h4>2.3 Do not declare version and scope of Spark dependencies</h4><p>Since they are already defined in <strong>spark-maven-parent</strong>, they will be ignored anyway, e.g.:</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.apache.spark&lt;/groupId&gt;<br>   &lt;artifactId&gt;spark-hive_${scala.binary.version}&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>   &lt;groupId&gt;org.apache.spark&lt;/groupId&gt;<br>   &lt;artifactId&gt;spark-mllib_${scala.binary.version}&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h4>2.4 Do not overwrite the following properties</h4><p>They are already defined in <strong>spark-maven-parent</strong>:</p><pre>&lt;properties&gt;<br>   &lt;hadoop.version&gt;3.3.1&lt;/hadoop.version&gt;<br>   &lt;jdk.version&gt;1.8&lt;/jdk.version&gt;<br>   &lt;scala.binary.version&gt;2.13&lt;/scala.binary.version&gt;<br>   &lt;scala.version&gt;2.13.5&lt;/scala.version&gt;<br>   &lt;spark.version&gt;3.2.1&lt;/spark.version&gt;<br>&lt;/properties&gt;</pre><h4>2.5 (Optional) Declare in a &lt;dependencyManagement&gt; section the Spark / Hadoop dependencies that DO need to be overwritten</h4><p>→ If the dependency version is greater than the Spark / Hadoop dependency one</p><p>Declare this dependency in a <strong>&lt;dependencyManagement&gt;</strong> section:</p><pre>&lt;dependencyManagement&gt;<br>   &lt;dependencies&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;com.google.guava&lt;/groupId&gt;<br>         &lt;artifactId&gt;guava&lt;/artifactId&gt;<br>         &lt;version&gt;28.2-jre&lt;/version&gt;<br>         &lt;scope&gt;compile&lt;/scope&gt;<br>      &lt;/dependency&gt;<br>   &lt;/dependencies&gt;<br>&lt;/dependencyManagement&gt;</pre><p>→ If the dependency version is lower than the Spark / Hadoop dependency one</p><p>Declare this dependency in a <strong>&lt;dependencyManagement&gt;</strong> section:</p><pre>&lt;dependencyManagement&gt;<br>   &lt;dependencies&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.json4s&lt;/groupId&gt;<br>         &lt;artifactId&gt;json4s-core_${scala.binary.version}&lt;/artifactId&gt;<br>         &lt;version&gt;3.2.11&lt;/version&gt;<br>         &lt;scope&gt;compile&lt;/scope&gt;<br>      &lt;/dependency&gt;<br>   &lt;/dependencies&gt;<br>&lt;/dependencyManagement&gt;</pre><p>Declare also this dependency (without version and scope) in a <strong>&lt;dependencies&gt;</strong> section:</p><pre>&lt;dependencies&gt;<br>   (...)<br>   &lt;dependency&gt;<br>      &lt;groupId&gt;org.json4s&lt;/groupId&gt;<br>      &lt;artifactId&gt;json4s-core_${scala.binary.version}&lt;/artifactId&gt;<br>   &lt;/dependency&gt;<br>   (...)<br>&lt;dependencies&gt;</pre><h4>2.6 (Optional) Give precedence to jars packaged with the component over Spark / Hadoop jars when loading classes</h4><p>Set the Spark configuration properties <strong>spark.driver.userClassPathFirst</strong> and <strong>spark.executor.userClassPathFirst</strong> to true when launching your applications (with e.g. <strong>spark-submit</strong>):</p><pre>/opt/spark/bin/spark-submit (...) --conf spark.driver.userClassPathFirst=true --conf spark.executor.userClassPathFirst=true (...)</pre><h3>Notes on Spark / Hadoop dependency override</h3><p>If you override the Spark / Hadoop dependencies, this means that your Spark application may be compiled and run with a different version of the library.</p><p>Let’s look at an example with the guava library, which version 11.0.2 is included by Hadoop-2.8.3.</p><h4>no guava dependency in your Spark applications component `pom.xml`</h4><ul><li>compilation is done with <strong><em>guava-11.0.2</em></strong></li><li><strong><em>guava-11.0.2</em></strong> jar is NOT packaged with the Spark applications component</li><li>run is executed with <strong><em>guava-11.0.2</em></strong></li></ul><h4>guava-28.2-jre is added in a &lt;dependencies&gt; section in your Spark applications component pom.xml</h4><ul><li>compilation is done with <strong><em>guava-28.2-jre</em></strong></li><li><strong><em>guava-28.2-jre</em></strong> jar is NOT packaged with the Spark applications component</li><li>run is executed with <strong><em>guava-11.0.2</em></strong></li></ul><h4>guava-28.2-jre is added in a &lt;dependencyManagement&gt; section in your Spark applications component pom.xml</h4><ul><li>compilation is done with <strong><em>guava-28.2-jre</em></strong></li><li><strong><em>guava-28.2-jre</em></strong> jar is packaged with the Spark applications component</li><li>userClassPathFirst value in your `spark-submit` command:<br> — false or not defined: run is executed with <strong><em>guava-11.0.2</em></strong><br> — true: run is executed with <strong><em>guava-28.2-jre</em></strong></li></ul><p>Now let’s look at another example with the json4s libraries, which version 3.5.3 is included by Spark-2.4.5.</p><h4>no json4s dependency in your Spark applications component pom.xml</h4><ul><li>compilation is done with <strong><em>json4s-3.5.3</em></strong></li><li><strong><em>json4s-3.5.3</em></strong> jar is NOT packaged with the Spark applications component</li><li>run is executed with <strong><em>json4s-3.5.3</em></strong></li></ul><h4>json4s-3.2.11 is added in a &lt;dependencies&gt; section in your Spark applications component pom.xml</h4><ul><li>compilation is done with <strong><em>json4s-3.2.11</em></strong></li><li><strong><em>json4s-3.2.11</em></strong> jar is NOT packaged with the Spark applications component</li><li>run is executed with <strong><em>json4s-3.5.3</em></strong></li></ul><h4>json4s-3.2.11 is added in a &lt;dependencyManagement&gt; section in your Spark applications component pom.xml</h4><ul><li>compilation is done with <strong><em>json4s-3.2.11</em></strong></li><li><strong><em>json4s-3.2.11</em></strong> jar is NOT packaged with the Spark applications component</li><li><strong>userClassPathFirst</strong> value in your <strong>spark-submit</strong> command:<br> — false or not defined: run is executed with <strong><em>json4s-3.5.3</em></strong><br> — true: run is executed with <strong><em>json4s-3.2.11</em></strong> (and fails because <strong><em>json4s-3.2.11</em></strong> jar is not packaged with the Spark applications component)</li></ul><h4>json4s-3.2.11 is added both in a &lt;dependencyManagement&gt; section and in a &lt;dependencies&gt; section in your Spark applications component pom.xml</h4><ul><li>compilation is done with <strong><em>json4s-3.2.11</em></strong></li><li><strong><em>json4s-3.2.11</em></strong> jar is packaged with the Spark applications component</li><li><strong>userClassPathFirst</strong> value in your <strong>spark-submit</strong> command:<br> — false or not defined: run is executed with <strong><em>json4s-3.5.3</em></strong><br> — true: run is executed with <strong><em>json4s-3.2.11</em></strong></li></ul><h3>About the author</h3><p>Christophe Préaud is data architect at Verkor.</p><p>You can connect with him on <a href="https://www.linkedin.com/in/christophe-pr%C3%A9aud-184023155">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cff333e9f7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>