<?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[DataKare Solutions - Medium]]></title>
        <description><![CDATA[DataKare Solutions is a data analytics company focused on solutions powered by big data technologies helping organizations to apply advanced analytics and research. - Medium]]></description>
        <link>https://medium.com/datakaresolutions?source=rss----a787ff01f420---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>DataKare Solutions - Medium</title>
            <link>https://medium.com/datakaresolutions?source=rss----a787ff01f420---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:34:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/datakaresolutions" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Spark SQL — Salient functions in a Nutshell]]></title>
            <link>https://medium.com/datakaresolutions/spark-sql-salient-functions-in-a-nutshell-7f604593be94?source=rss----a787ff01f420---4</link>
            <guid isPermaLink="false">https://medium.com/p/7f604593be94</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Arun Jijo]]></dc:creator>
            <pubDate>Fri, 27 Dec 2019 04:03:28 GMT</pubDate>
            <atom:updated>2019-12-28T06:14:45.550Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spark SQL functions - Salient functions in a Nutshell</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*iY0NoIiNx1H87WpF.jpg" /></figure><p>As, Spark DataFrame becomes de-facto standard for data processing in Spark, it is a good idea to be aware key functions of Spark sql that most of the Data Engineers/Scientists might need to use in their data transformation journey.</p><p><strong>callUDF</strong></p><p>One of the most vital functions of Spark, which I found useful in my day to day usage. callUDF is used not only to call the user defined functions, but also to utilise the functions of Spark Sql which are not a part of Spark functions objects.</p><p>Example:</p><p>For example parse_url is a part of Spark Sql but not available in Spark’s functions object. Hence its not possible to use it directly as a part of your DataFrame operations, you need to wrap it in callUDF function.</p><pre>val df= Seq((“http://spark.apache.org/path?query=1&quot;),(&quot;https://people.apache.org/~pwendell/spark-nightly/spark-master-docs/latest/api/sql/#negative&quot;)).toDF(&quot;url_col&quot;)</pre><pre>df.withColumn(&quot;host&quot;, callUDF(&quot;parse_url&quot;, $&quot;url_col&quot;, lit(&quot;HOST&quot;)))</pre><p><strong>Input_file_name</strong></p><p>This function is used to get the file name of the current spark task. Mostly used in debugging or to find out the specific files which have bad records.</p><p>Example:</p><pre>df.withColumn(“filename”, input_file_name)</pre><p><strong>spark_partition_id</strong></p><p>To get the specific spark partition id.</p><pre>df.withColumn(“partition_id”,spark_partition_id)</pre><p><strong>na</strong></p><p>na is Spark DataFrame api function, which is used to drop or fill null values.</p><p>Example:</p><pre>df.na.drop()</pre><p>will drop all the rows which containing any null values.</p><pre>df.na.drop(Seq(&lt;cols&gt;))</pre><p>drop all the rows which contain null values in the specified columns</p><pre>df.na.fill(“literal”)</pre><p>Fill the null values with the specified literal</p><p><strong>agg</strong></p><p>Aggregate function is used to compute different aggregate expressions over different columns.</p><pre>df.groupBy(“dept”).agg(min(“id”), count(“id”), avg(“salary”))</pre><p><strong>struct</strong></p><p>Struct function is used to create new struct from existing columns.</p><p>Example:</p><p>One on the most common use case of this functions is to create JSON values from existing columns.</p><pre><strong>val </strong>df1 = <em>Seq</em>(<em>Seq</em>(&quot;Arun&quot;,&quot;Vijay&quot;,&quot;vinay&quot;),      <em>Seq</em>(1,2,3)).toDF(&quot;Name&quot;,&quot;id&quot;)</pre><pre>df1.select(<em>struct</em>(&quot;*&quot;).alias(&quot;json&quot;))</pre><p><strong>transform — DataFrame API</strong></p><p>Transform function is used to chain spark transformation functions. This function helps to breaks the big spark transformation queries into modular and chain them later.</p><p>Example</p><pre>val df = <strong>Seq</strong>(1,2,3).<strong>toDF</strong>(“id”)</pre><pre><strong>def </strong>incByOne(df: DataFrame): DataFrame = {<br><br>  df.withColumn(&quot;inc&quot;, df(&quot;id&quot;) +1)<br><br>}<br>val incDf = df.<strong>transform</strong>(incByOne)</pre><p><strong>Transform — Spark Sql</strong></p><p>Spark Sql also posses an transform function to work with array elements.</p><p>Example:</p><p>To increment one by each element of an array</p><pre>Spark.sql(“SELECT transform(array(1, 2, 3), x -&gt; x + 1)”)</pre><blockquote>Both Spark sql transform function and Dataframe Transform function are different and exists for different purpose.</blockquote><p><strong>java_method — Spark Sql</strong></p><p>Spark sql specific function to invoke a java method as a part of the query by passing the java class name, method name and arguments if any.</p><p>Example</p><pre>spark.sql(“SELECT java_method(“java.util.UUID”,”randomUUID”)”)</pre><p>The above query calls the method randomUUID from the Java class UUID via reflection and returns an universally unique identifier.</p><p><strong>flatten</strong></p><p>Flatten out columns which have nested array of array.</p><blockquote>Incase the nested levels are more than two, only one level will be flattened.</blockquote><p>Example:</p><pre>df.withColumn(“flattened_col”,flatten($”nested_column”))</pre><pre>Spark.sql(“SELECT flatten(array(array(1, 2), array(3, 4)))”)</pre><p><strong>get_json_objects</strong></p><p>Function used to extract JSON elements with the help of JPath.</p><pre><strong>val </strong>jsonDF = <em>Seq </em>((0, &quot;&quot;&quot;{&quot;student_id&quot;: 0, &quot;student_name&quot;: &quot;Arun&quot;, &quot;Age&quot;: 12}&quot;&quot;&quot;),(1, &quot;&quot;&quot;{&quot;student_id&quot;: 1, &quot;student_name&quot;: &quot;Vijay&quot;, &quot;Age&quot;: 12}&quot;&quot;&quot;)).toDF(&quot;id&quot;,&quot;json&quot;)</pre><pre> jsonDF.select($&quot;id&quot;, get_json_object($&quot;json&quot;, &quot;$.student_id&quot;).alias(&quot;student_id&quot;),get_json_object($&quot;json&quot;, &quot;$.student_name&quot;).alias(&quot;student_name&quot;),get_json_object($&quot;json&quot;, &quot;$.age&quot;).alias(&quot;age&quot;))</pre><p><strong>from_json</strong></p><p>Function used to convert JSON string into JSON struct. One of the common area for use of this function is decoding JSON string into struct from messages consumed from Kinesis/Kafka</p><pre><strong>val </strong>jsonSchema = <strong>new </strong>StructType()<br>                .add(&quot;student_id&quot;, IntegerType)<br>                .add(&quot;student_name&quot;, LongType)<br>                .add(&quot;age&quot;,IntegerType)</pre><pre>jsonDF.select($&quot;json&quot;,jsonSchema)</pre><p><strong>str_to_map — Spark Sql</strong></p><p>Converts string into map by splitting the text value into key value by using the specific pair and key/value delimiter.</p><p>Example:</p><pre>Spark.sql(“<strong>SELECT</strong> str_to_map(‘a:1,b:2,c:3’, ‘,’, ‘:’)”)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f604593be94" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datakaresolutions/spark-sql-salient-functions-in-a-nutshell-7f604593be94">Spark SQL — Salient functions in a Nutshell</a> was originally published in <a href="https://medium.com/datakaresolutions">DataKare Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NIFI — Monitoring Data Flows]]></title>
            <link>https://medium.com/datakaresolutions/nifi-monitoring-data-flows-aa5b7f4febef?source=rss----a787ff01f420---4</link>
            <guid isPermaLink="false">https://medium.com/p/aa5b7f4febef</guid>
            <category><![CDATA[apache-nifi]]></category>
            <category><![CDATA[hadoop]]></category>
            <dc:creator><![CDATA[Prabhath Vemula]]></dc:creator>
            <pubDate>Mon, 25 Nov 2019 01:20:51 GMT</pubDate>
            <atom:updated>2019-11-25T01:20:51.100Z</atom:updated>
            <content:encoded><![CDATA[<h3>NIFI — Monitoring Data Flows</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/0*ytCSAnwSXV0GhqNz" /></figure><p>Before moving an Data pipeline in production, the key thing is to designing/deciding an monitoring tool. Fortunately NIFI bloaters <br> with lot of Inbuilt monitoring utilities which helps one to monitor disk usage, memory usage, back pressure etc.. Throughout this <br> article let’s walk through monitoring data flows via NIFI bulletins which a processor emits during warnings or error.<br> <br> NIFI converts every bulletin to flow file by using S2S protocol, which in turn can be used for data flow monitoring.<br> <br> From official documentation,</p><blockquote>When sending data from one instance of NiFi to another, there are many different protocols that can be used. <br> The preferred protocol, though, is the NiFi Site-to-Site Protocol. Site-to-Site makes it easy to securely and efficiently transfer data to/from nodes in <br> one NiFi instance or <br> data producing application to nodes in another NiFi instance or other consuming application.</blockquote><p>To collect the all the reported bulletin continually, we can run the NIFI s2s reporting tasks. With the help of an input port (placed on <br> the canvas), the reported data can be received and used in NIFI workflow.</p><p>Make sure to use this <a href="https://gitlab.com/dks_public/nifi-app-monitoring">NIFI monitoring template</a> when following this article for better understanding.</p><p>For demonstration, lets run “UpdateAttribute”processor in debug level. Then via s2s reporting tasks, fetch the Bulletin’s as Flow File, process them and send an alert via mail to the appropriate teams.</p><p>Use UpdateAttribute processor with Bulletin level of Debug to generate dummy bulletins along with the GenerateFlowFile processor as upstream connection. Make sure the Name of the processors follow an unique convention, which helps to monitor the bulletins efficiently. For example in the following UpdateAttribute processor configuration the naming convention is<strong> “&lt;team&gt;.&lt;source&gt;.&lt;useCase&gt;.&lt;Purpose&gt;.&lt;processTask&gt;.&lt;Severity&gt;”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*R4AEc6f5NBNLjH80tG_PeA.png" /></figure><p>Then, create a new site2site reporting site.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*nv3X9IG5S0lCltQ8FejdKg.png" /></figure><p>Drag and Drop an Input port from the canvas and give it a name, which should be same as the Input Port Name in the reporting tasks. Once these mundane stuffs are done, NIFI routes the bulletins to this input port.</p><p>NIFI emits the bulletins as an JSON array, So the first process is to extract the individual elements in the JSON array using SplitJson Processor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*7QqB0H07Hs5v0PRz0dug3g.png" /></figure><p>Once the individual JSON elements are splitted, extract the source name i.e. from where the bulletin is emitted, using EvaluateJsonPath processor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*UkWimDQ2J3Lf2cuDM8we5Q.png" /></figure><p>As, the bulletin source name is the actual name of the processor which we give in the format of <strong>“&lt;team&gt;.&lt;source&gt;.&lt;useCase&gt;.&lt;Purpose&gt;.&lt;processTask&gt;.&lt;Severity&gt;”.</strong></p><p>Let’s extract the individual attribute from the source name using UpdateAttribute processor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*-szSVEfx39CAw4Rptf1R6Q.png" /></figure><p>Use the team attribute to route for the specific processor group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*FFEhShQ_Bbc2BcPXpVHYEg.png" /></figure><p>Remove duplicate bulletins to avoid bombarding with alert messages using DetectDuplicate processor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*9mDJnUzD1a9Mq_hC2xibeA.png" /></figure><p>Use the LookUpService processor to load email based on the severity levels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*U8mhEi-bLYTeZqa2w1ACFQ.png" /></figure><p>If the severity level is Audit it makes sense to store it in HDFS rather than alerting via e-mail. Hence, use RouteOnAttribute to route the flow files to respective flows like PutMail processor for alerting or merge the contents and dump it in HDFS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*fzpNlPWDjYXeP0m46WJNGA.png" /></figure><p><strong>Conclusion</strong></p><p>Hope, this walk-through helps you find how easy it is to monitor a NIFI data flow with the help of bulletins and built-in processors. Additionally the generated bulletins also helps in monitoring disk-usage, memory utilization and back-pressure which itself deserve separate article to cover.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa5b7f4febef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datakaresolutions/nifi-monitoring-data-flows-aa5b7f4febef">NIFI — Monitoring Data Flows</a> was originally published in <a href="https://medium.com/datakaresolutions">DataKare Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Key factors to consider when optimizing Spark Jobs]]></title>
            <link>https://medium.com/datakaresolutions/key-factors-to-consider-when-optimizing-spark-jobs-72b1a0dc22bf?source=rss----a787ff01f420---4</link>
            <guid isPermaLink="false">https://medium.com/p/72b1a0dc22bf</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[hive]]></category>
            <category><![CDATA[spark-streaming]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[hadoop]]></category>
            <dc:creator><![CDATA[Arun Jijo]]></dc:creator>
            <pubDate>Thu, 21 Mar 2019 09:03:47 GMT</pubDate>
            <atom:updated>2019-03-26T04:00:08.968Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*dmzEeDtF9_E5T3Mr_C09QA.png" /></figure><p>Developing a spark application is fairly simple and straightforward, as spark provides featured pack APIs. Be that as it may, the tedious task is to deploy it on the cluster in an optimal way which yields ideal performance and following the best practices when developing spark jobs. Here in DataKareSolutions, we often need to get our hands dirty to tune the spark application. Throughout this article I will put out all the best practices we follow in DataKareSolutions to optimize spark application.</p><h3><strong>Data Serialization</strong></h3><p>Spark bolsters two types of serialization, Java serialization which is the default one and Kryo serialization. Kryo serialization is significantly faster and compact than Java serialization. Thus, in production it is always recommended to use Kryo over Java serialization. To use Kryo, the spark serializer needs to be changed to Kryo serializer in the spark configurations.</p><pre>conf.set(“spark.serializer”,”org.apache.spark.serializer.KryoSerializer”)</pre><p>However, Kryo may fails to serialize few classes rarely to avoid this Kryo requires you to register the classes which are expected to be serialized.</p><h3>Broadcasting</h3><p>If the tasks across multiple stages requires the same data, it is better to broadcast the value rather than send it to the executors with each task. And when joining two tables if one of the join is small enough to fit into memory it is advisable to broadcast it, to avoid shuffles.</p><h3>Avoid UDF and UDAF</h3><p>It is better to avoid UDF in favor of spark SQL functions as it avoids deserialization of data so that it can process in scala and then serialize it again. Moreover Spark SQL functions are well tested and chances are there it will yield better performance compared to UDF.</p><p>Furthermore, with regards to UDAF which produces sortAggregate which is relatively in slower side than its counterpart hashAggregates.</p><h3>Data locality</h3><p>To achieve better performance the data should reside as close to the computation. There are four different sorts of locality in spark.</p><ol><li>PROCESS_LOCAL — Data is in the same JVM which is running the task. Obviously the best one.</li><li>NODE_LOCAL — Data is on the same node as the computation. Comparatively slower than process local as the data needs to travel between processes.</li><li>NO_PREF — No locality preference.</li><li>RACK_LOCAL — Data will reside on the same rack.</li><li>ANY — Data may reside anywhere on the network not on the same rack.</li></ol><p>It is always preferable to choose the best locality levels to avoid data movements. But there may be times when there are no new data to process, sparks tries to fetch data from lower locality levels. Spark will wait for a certain period of time before switching to lower locality levels.</p><p>Use the accompanying parameter to configure the interval time to wait before switching locality levels.</p><pre>spark.locality.wait //<em>which is 3 seconds by default</em></pre><blockquote>To inspect whether a task ran locally, in the spark UI the locality_levels can be found out under stages tab.</blockquote><h3>Dynamic allocation</h3><p>Spark is shipped with an excellent mechanism to use the cluster resources rather efficiently based on workloads and on shared clusters. According to the workloads it is possible to scale up and scale down the number of executors which is known as dynamic allocation.<br>The following configuration parameters are used to enable and tweak dynamic allocation.</p><pre>spark.dynamicAllocation.enabled //<em>Set the value to true to enable dynamic allocation.</em></pre><pre>spark.dynamicAllocation.executorIdleTimeout //<em>Timeout to wait before releasing the executor.</em></pre><pre>Spark. dynamicAllocation. cachedExecutorIdleTimeout  //Timeout to wait before removing the cached data blocks.</pre><pre>spark.dynamicAllocation.initialExecutors //<em>The initial number of executors to begin with. However, if the number of executors is explicitly mentioned via --num-executors` (or `spark.executor.instances`) then the larger value between them will be the initial executors value.</em></pre><pre>spark.dynamicAllocation.maxExecutors //<em>Upper bound of executors, by default infinity.</em></pre><pre>spark.dynamicAllocation.minExecutors //<em>Minimum number of executors by default is &#39;0&#39; which ensures our application won’t occupy cluster resources unnecessarily.</em></pre><blockquote>When enabling dynamic allocation it is also necessary to enable Spark’s external shuffle service which can be done by the parameter spark.shuffle.service.enabled.This ensures that we have a separate server on each machine in the cluster which will manage shuffle files when the appropriate executor is removed/lost.</blockquote><h3>Garbage collection</h3><p>Garbage collection can be a bottleneck in spark applications. It is advisable to try the G1GC garbage collector, which can improve the performance if garbage collection is the bottleneck. The parameter -XX:+UseG1GC is used to specify G1GC as the default garbage collector. And increase the G1GC region heap size if the executer heap size is large this can done by -XX:G1HeapRegionSize.</p><blockquote>It is always recommended to use data structures which generated less objects, like array instead of LinkedLists.</blockquote><p>Refer this <a href="https://databricks.com/blog/2015/05/28/tuning-java-garbage-collection-for-spark-applications.html">link</a> for in-depth explanation.</p><h3>Executor Tuning</h3><p>When deploying a spark application one of the most prominent thing is to allocate the execution resources optimally like number of executors, executors core and executors memory.</p><h4>Number of executor cores</h4><p>As the name indicated executor cores will define the number of cores to use for each executors. Each individual cores will be assigned to one different task. Therefore, we will be fancying to allocate more cores to a single executor. But too many tasks per executor will results in garbage collection overload and as a matter of fact HDFS achieves better throughput when the number of executors is set to 5. <br>Hence, it is always recommended to assign the number of executors cores to ~5.</p><blockquote>As a rule of thumb one core in each node of the cluster will be allocated to OS process and Hadoop daemons.</blockquote><h4>Number of executors</h4><p>Executer is just another JVM instance, so it is possible to have more than one executors. <br>The number of executors depends upon the number of cores in the cluster.</p><blockquote>If the application is deployed on top of yarn, one executor will be assigned to the yarn application master.</blockquote><p>For example, if there are 250 cores in the cluster, then the number of executors should be 250/5 = 50 executors. Out of which one should be left for application master and the remaining 49 can be assigned to our spark application by using the parameter –num-executors=49 when submitting the application for execution.</p><h4>Memory per executor</h4><p>As a standard guideline, one GB in each nodes of the cluster will be allocated to OS process and Hadoop daemons.</p><p>Let’s assume we have a 250 core cluster and 64 GB memory on each node. If 1 GB is allocated to Hadoop demon and OS processes, we will be left with 63 GB memory in each node.</p><p>As discussed above, we will be left with 5 executors per node if we have 25 cores per machine (i.e. 49 executors in a 250 core cluster after allocating one to yarn AM). Thus we may consider to allocate (63 GB/5 executors) = 12.6 GB to each executor.<br>But there is an additional yarn overhead memory needs to be allocated to each executor. The additional overhead memory is 10% by default (7% for legacy spark versions)of the executor memory. I.e. 12.6-(0.10 * 12.6)= 11.34 GB per executor is the optimal memory per executor.</p><h3>Parallelism</h3><p>Degree of parallelism is the most proficient parameter which dictates the performance of a spark job. The partition size should be in a form that it should not be too big which will eventually lead to under-utilization of the cluster neither too small which will lead to too much of small tasks. The partition size should be in such a way it should utilize the clusters efficiently without any overheads of small tasks.<br>In spark higher level APIs like dataframe and datasets use the following parameters to determine the partition of a file.</p><pre>spark.sql.files.maxPartitionBytes //<em>Specify maximum partition size by default 128mb</em></pre><pre>spark.sql.files.openCostInBytes //<em>The approximate cost to use to open the file and scan the file which is by default 4MB.</em></pre><p>Spark automatically figures the optimal partition size based on these two parameters.</p><p>At whatever point, if there is a shuffle operation spark will use spark.sql.shuffle.partitions parameter to determine the partition size which by default is 200 by default. It is recommended to shrink down the shuffle partitions size if the Size of the file is small.</p><blockquote>If the dataset was derived from an RDD, it will inherit the partition size of the parent RDD.</blockquote><h3>Speculative execution</h3><p>In real time use cases there are scenarios where a spark job may perform poorly compared to other worker nodes due to some external factors which may not in our control. Then spark will re-launch the same task in some other worker nodes. <br>Speculative execution can be enabled and can be tuned by using the accompanying parameters.</p><pre>spark.speculation //<em>Set to true to enable by default it is false.</em></pre><pre>spark.speculation.interval //<em>Time interval to check for speculative    tasks.</em></pre><pre>spark.speculation.multiplier //<em>specify how much times the tasks can be slower than the median to consider it as a speculative job.</em></pre><pre>spark.speculation.quantile (value in percentage) //<em>The fraction of tasks which must be completed before speculation is enabled in a particular stage.</em></pre><blockquote>Spark driver will normally spend a lot of time in detecting speculation when managing a large number of tasks, enable it only if needed.</blockquote><h3>Parallel transformations</h3><p>If there are multiple queries/transformations which can be executed independently it is recommended to take leverage of spark scheduler pool. By default spark executes the tasks in FIFO to execute tasks in parallel the first step is to change it into Fair, which will dictate spark to execute the job in round robin fashion. This can be done by changing the configuration parameter “spark. scheduler. mode” to FAIR in the Spark configuration object. <br>Then create an separate pools for different independent queries.</p><pre>spark.setLocalProperty(&quot;spark.scheduler.pool&quot;, &quot;pool1&quot;)<br>// Query 1<br>spark.setLocalProperty(&quot;spark.scheduler.pool&quot;, &quot;pool2&quot;)<br>//Query 2</pre><p>The most common use case for it is when writing the same streaming query <br>data to multiple destinations in structured streaming<br> Refer this <a href="https://spark.apache.org/docs/latest/job-scheduling.html#fair-scheduler-pools">link</a> for more details.</p><h3>Data Skewing</h3><p>Data skewing is a condition when the data is unevenly distributed across the cluster, which causes serious performance degrades because skewed data will makes the cluster underutilized. So, if a spark job is taking more time to complete, it is always a wise decision to check for data skew. And if it proves to be true apply one of the following techniques to handle data skewing.<br>1. Repartition<br>2. Salting<br>3. Isolating salting<br>4. Isolating Map/Join<br>5. Iterative Broadcasting<br>Each of these techniques has its own advantages/limitations. Covering each of these is out of scope for this article.</p><blockquote>Databricks delta provides some fairly simple and powerful techniques to handle Data skews.</blockquote><h3>Miscellaneous optimizations</h3><ul><li>Throughout the spark application use only Dataframe/Dataset. Typically, there is no reason to use RDD unless you are writing your own partitioner.</li><li>Cache Spark Sql table and dataframe. It will mimimize memory usage and Garbage collection overhead as Spark will scan only required columns and automatically tune compression.</li><li>Avoid String for keys and consider to use numeric IDs wherever possible.</li></ul><h3>Conclusion</h3><p>We have walked through the major key factors which will impact the performance of Spark jobs in detail. Go through <a href="https://medium.com/datakaresolutions/optimize-spark-sql-joins-c81b4e3ed7da">this article</a> which will give a good idea on how to optimize Spark joins.</p><p>If you have any query, throw that to me on <a href="https://twitter.com/ArunJijo36">twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72b1a0dc22bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datakaresolutions/key-factors-to-consider-when-optimizing-spark-jobs-72b1a0dc22bf">Key factors to consider when optimizing Spark Jobs</a> was originally published in <a href="https://medium.com/datakaresolutions">DataKare Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structured Streaming: Essentials]]></title>
            <link>https://medium.com/datakaresolutions/structured-streaming-essentials-e5e251531825?source=rss----a787ff01f420---4</link>
            <guid isPermaLink="false">https://medium.com/p/e5e251531825</guid>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[spark-streaming]]></category>
            <category><![CDATA[structured-streaming]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Arun Jijo]]></dc:creator>
            <pubDate>Sun, 03 Mar 2019 03:36:01 GMT</pubDate>
            <atom:updated>2019-03-03T03:36:01.716Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second chapter under the series “Structured Streaming” which center around covering all the essential details to set up a Structured Streaming query. Peruse the previous chapter <a href="https://medium.com/datakaresolutions/structured-streaming-cffb25976ae1">here</a> for getting introduced to Structured Streaming.</p><h4><strong>Sources</strong></h4><p>Sources in Structured Streaming refers to the streaming data sources which brings data into Structured Streaming. As of spark 2.4 the built in data sources are as follows,</p><ul><li><strong>Kafka</strong></li></ul><p>Kafka source reads data from Kafka brokers and it is compatible with Kafka broker versions 0.10.0 or higher versions. Follow this <a href="https://medium.com/datakaresolutions/structured-streaming-kafka-integration-6ab1b6a56dd1">link</a> which focuses on Spark-Kafka integration for more details.</p><ul><li><strong>File source</strong></li></ul><p>File source reads the files as a streams of data from a directory. For ex, reading log files from the HDFS directory which was collected using flume at regular intervals.</p><p>We will leave all the nitty-gritty details of file sources and how to use it in production for later parts of this series.</p><ul><li><strong>Socket source</strong></li></ul><p>To read the text input from a socket connection. Socket source should be used only for testing purpose.</p><p><strong>Schema</strong>: Socket source has two schemas,</p><p>1. Contains only one column named “value” and of string type.</p><p>2. Contains two columns named “value” and “timestamp” of which the former is of String type and the latter is of Timestamp type.</p><pre><strong>val</strong> socketDF <strong>=</strong> spark.readStream.format(&quot;socket&quot;)<br>               .option(&quot;host&quot;, &quot;localhost&quot;) <br>               .option(&quot;port&quot;, 9999)<br>//set to false or ignore this parameter to set the schema to type 1<br>             .option(&quot;includeTimestamp&quot;,true)<br>             .load()</pre><ul><li><strong>Rate source</strong></li></ul><p>Rate source is likewise utilized for testing, yet here the rate source will naturally produce some example data for testing.</p><p><strong>Schema: </strong>Rate source has two columns named “value” of long type and “timestamp” of Timestamp type.</p><pre><strong>val</strong> socketDF <strong>=</strong> spark.readStream<br>               .format(&quot;rate&quot;)<br>               .option(&quot;rowsPerSecond&quot;, 10)<br>               .load()</pre><p><strong>Schema Inference</strong></p><p>For file sources, it is recommended to provide the schema so that the schema will be consistent. To automatically infer the schema, it is necessary to set the configuration parameter “spark.sql.streaming.schemaInference” to true which by default is false.</p><blockquote>For sources like Kafka, Socket, Rate the schema is fixed and won’t possible to change.</blockquote><p><strong>Sinks</strong></p><p>Structured Streaming uses sinks to add the output of each batch to a destination. Spark is shipped with the following sinks as of spark 2.4,</p><ul><li><strong>File sinks</strong></li></ul><p>To write the output to a file in a directory. The supported file formats are ORC, JSON, CSV, Parquet.</p><pre>writeStream<br>.format(&quot;json&quot;)<br>.option(&quot;path&quot;, &quot;destinationdir&quot;)<br>.start()</pre><ul><li><strong>Kafka sinks</strong></li></ul><p>To publish the output to Kafka topics.</p><pre>writeStream<br>.format(&quot;kafka&quot;)<br>.option(&quot;kafka.bootstrap.servers&quot;, &quot;host1:port1,host2:port2&quot;)<br>.option(&quot;topic&quot;, &quot;updates&quot;)<br>.start()</pre><ul><li><strong>Foreach and Forechbatch sinks</strong></li></ul><p>Both sinks are used to run some arbitrary computations on the records. Both have their own merits. More details of each sink will be covered later in this series.</p><ul><li><strong>Memory sinks</strong></li></ul><p>The memory sink is designed for debugging purpose, the complete output will be stored in memory. So, it is recommended to use this sink in a low volume of data.</p><pre>writeStream<br>.format(&quot;memory&quot;)<br>.queryName(&quot;tableName&quot;)<br>.start()</pre><ul><li><strong>Console sinks</strong></li></ul><p>As like memory sink console sink is also designed for debugging and stores the data will be stored in memory. Instead of storing the data as in-memory table it will print it to the console.</p><pre>writeStream<br>.format(&quot;console&quot;)<br>.start()</pre><blockquote>By implementing StreamSinkProvider, it is possible to develop custom sinks.</blockquote><p><strong>Output Modes</strong></p><p>Output mode defines how to write out the data to the sink. Like if it just needs to add the new information (rows) or to update the rows with new information. Spark supports three output modes which needs to be specified at the time of setup the sinks, if not the default is append.</p><ul><li><strong>Append</strong></li></ul><p>Append mode writes only the new rows to the output table since the last trigger.</p><ul><li><strong>Update</strong></li></ul><p>Update mode writes only the rows which have been updated since the last trigger. If the query doesn’t contain any type of aggregations, it behaves like append mode.</p><ul><li><strong>Complete</strong></li></ul><p>Complete mode writes out all the output rows to the resultant table.</p><p><strong>Triggers</strong></p><p>Triggers defines how often structured streaming should check for new data in the source and updates the result.</p><p>· <strong>Fixed interval: </strong>The query will be executed in a micro batch mode. However, if a certain query hasn’t been processed within the interval, the streaming engine will start processing the next batch only after current batch is finished</p><p>· <strong>One-Time-Micro-Batch: </strong>The query will be executed only once and then it will shut down by itself. It is useful if it is necessary to process the data after a long interval, like schedule the application to run only two times in a day to avoid unnecessary cost.</p><p>· <strong>Continuous Processing: </strong>To achieve low latency as low as<strong> </strong>~1 ms. But it is in the experimental stage right now, not recommended in production.</p><p>· <strong>Default: </strong>By default if any type of triggers is not explicitly specified, the streaming engine will look for the new data as soon as the previous batches continue.</p><pre>df.writeStream<br>.format(&quot;console&quot;)<br>.trigger(<strong>Trigger</strong>.<strong>ProcessingTime</strong>(&quot;2 seconds&quot;))<br>.start()</pre><p>In the next chapter of this series, we will dive into fault-tolerance semantics and how it is achieved in Structured Streaming.</p><p>If you have any queries feel free to contact me on <a href="https://twitter.com/ArunJijo36">twitter</a> and follow <a href="https://twitter.com/DataKareS">data kare solutions</a> for more Big data articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5e251531825" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datakaresolutions/structured-streaming-essentials-e5e251531825">Structured Streaming: Essentials</a> was originally published in <a href="https://medium.com/datakaresolutions">DataKare Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structured Streaming]]></title>
            <link>https://medium.com/datakaresolutions/structured-streaming-cffb25976ae1?source=rss----a787ff01f420---4</link>
            <guid isPermaLink="false">https://medium.com/p/cffb25976ae1</guid>
            <category><![CDATA[real-time-analytics]]></category>
            <category><![CDATA[spark-streaming]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Arun Jijo]]></dc:creator>
            <pubDate>Tue, 26 Feb 2019 03:00:55 GMT</pubDate>
            <atom:updated>2019-02-26T03:00:55.214Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>As streaming frameworks are emerging gradually, it encourages the developers to concentrate on business challenges rather than focussing on potential streaming analytics issues. Structured Streaming is a part of the Apache Spark venture, which built on top of the Spark SQL engine for streaming analytics. Structured streaming is fault tolerant, scalable and mainly it conceals all the streaming complexities from the developer which makes the development easier.</p><p>Structured streaming was introduced in Spark 2.0 as a part of the Apache Spark project as a micro batch stream processing engine. It was marked as stable in Spark 2.2 which makes Structured Streaming as the standard stream processing engine with spark and termed DStreams as a legacy. This tutorial series will walk you through Structured Streaming and the recently introduced continuous streaming.</p><p>Structured Streaming operates on top of SQL engine of the spark. In Structured Streaming transformations, aggregations, event-time-windows all works on top of Dataframes/Datasets i.e. The data will be in the form of unbounded table and will be changed for each micro batch. So, it is possible to reuse the same logic intended for batch processing in Streaming analytics too.</p><p><strong>Advantages of Structured Streaming:</strong></p><p><strong>Event Time Processing</strong></p><p>In structured streaming it is possible to process data based on the event time i.e. When the data is generated rather than when it arrives to the processing engine. This is achieved by using the time field in the data. This also helps to process the data in order even though the arriving time of the data to the processing engine is out of order.</p><p><strong>Watermarks</strong></p><p>Structured Streaming supports watermarks, i.e. The maximum delay time it might take the data to arrive. So that structured streaming can keep the old data for a certain period of time</p><p><strong>Stream Processing on SQL engine</strong></p><p>Structured streaming is the first stream processing engine built on top of SQL. So, the Dataframe/Dataset API is simpler to use and familiar. And also it can take leverage of the optimization of the Spark SQL engine.</p><p>Let’s have a quick glance at an example, then will discuss further.</p><pre><strong>val</strong> sampleData =spark.readStream<br>                 .format(&quot;rate&quot;) //To generate sample data<br>                 .option(&quot;rowsPerSecond&quot;, 10)<br>                 .load()</pre><p>The above example will be familiar with most of you, if you have used Spark before, except for the one difference “readStream” function instead of the traditional “read” function. The readStream function returns the “DataStreamReader” instead of the “DataFramereader” which was return by the read function. SparkSession is the entry point for Structured Streaming too, it is not necessary to create a separate streaming context object like streams.</p><p>DataFrameReader (StructuredSteaming) supports data source like Kafka, socket, rate and File sources. In these data sources socket and rate is for testing and File sources supports data types like CSV, JSON, ORC, parquet, text. And the load function which was invoked on the DataStreamReader will load the data from the data source.</p><p>Till this point we have set up the streaming query. To actually receive the data and write it to the sinks structured streaming uses DataStreamWriter.</p><pre><strong>val</strong> query = sampleData.writeStream<br>             .outputMode(&quot;append&quot;)<br>             .format(&quot;console&quot;)<br>             .trigger(Trigger.ProcessingTime(&quot;10 second&quot;))<br>             .start().awaitTermination()</pre><p>writeStream function returns a DataStreamWriter and the output mode defined how the data should be written to the sink and then specify the sink which is console in this case and then the trigger function is used to query the data source for every 10 seconds.</p><p>We will be covering about all the sources, sinks, output modes, triggers and all the necessary detail in depth in the upcoming chapter of this series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cffb25976ae1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datakaresolutions/structured-streaming-cffb25976ae1">Structured Streaming</a> was originally published in <a href="https://medium.com/datakaresolutions">DataKare Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimize Spark SQL Joins]]></title>
            <link>https://medium.com/datakaresolutions/optimize-spark-sql-joins-c81b4e3ed7da?source=rss----a787ff01f420---4</link>
            <guid isPermaLink="false">https://medium.com/p/c81b4e3ed7da</guid>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[spark-sql]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Prabhath Vemula]]></dc:creator>
            <pubDate>Mon, 25 Feb 2019 09:50:56 GMT</pubDate>
            <atom:updated>2019-02-25T12:35:53.449Z</atom:updated>
            <content:encoded><![CDATA[<p>Joins are one of the fundamental operation when developing a spark job. So, it is worth knowing about the optimizations before working with joins.<br>In Data Kare Solutions we often found ourselves in situations to joining two big tables (data frames) when dealing with Spark SQL. In this article we put out the best practices and optimization techniques we used to pursue when managing Spark Joins.</p><p>Spark approaches two types of cluster communication Strategy:</p><ul><li>node-node communication strategy</li><li>per-node communication strategy</li></ul><p>In node-node communication Spark shuffles the data across the clusters, whereas in per-node strategy spark perform broadcast joins.</p><p>Performance of Spark joins depends upon the strategy used to tackle each scenario which in turn relies on the size of the tables. Sort Merge join and Shuffle Hash join are the two major power horses which drive the Spark SQL joins. Despite the fact that Broadcast joins are the most preferable and efficient one because it is based on per-node communication strategy which avoids shuffles but it’s applicable only for a smaller set of data. Thus, more often than not Spark SQL will go with both of Sort Merge join or Shuffle Hash.</p><h4>Sort -Merge Join</h4><p>S<strong>ort-Merge join</strong> is composed of 2 steps. The first step is to sort the datasets and the second operation is to merge the sorted data in the partition by iterating over the elements and according to the join key join the rows having the same value.</p><p>From spark 2.3 Merge-Sort join is the default join algorithm in spark. However, this can be turned down by using the internal parameter ‘<strong>spark.sql.join.preferSortMergeJoin</strong>’ which by default is true.</p><p><strong>To accomplish ideal performance in Sort Merge Join:</strong><br>• Make sure the partitions have been co-located. Otherwise, there will be shuffle operations to co-locate the data as it has a pre-requirement that all rows having the same value for the join key should be stored in the same partition.<br>• The DataFrame should be distributed uniformly on the joining columns.<br>• To leverage parallelism the DataFrame should have an adequate number of unique keys</p><h4>Broadcast joins</h4><p>Easily Broadcast joins are the one which yield the maximum performance in spark. However, it is relevant only for little datasets. In broadcast join, the smaller table will be broadcasted to all worker nodes. Thus, when working with one large table and another smaller table always makes sure to broadcast the smaller table. We can hint spark to broadcast a table.</p><pre>import org.apache.spark.sql.functions.broadcast<br>val dataframe = largedataframe.join(broadcast(smalldataframe), &quot;key&quot;)</pre><blockquote>Recently Spark has increased the maximum size for the broadcast table from 2GB to 8GB. Thus, it is not possible to broadcast tables which are greater than 8GB.</blockquote><p>Spark also internally maintains a threshold of the table size to automatically apply broadcast joins. The threshold can be configured using “<strong>spark.sql.autoBroadcastJoinThreshold</strong>” which is by default 10mb.<br>So, it is wise to leverage Broadcast Joins whenever possible and Broadcast joins also solves uneven sharding and limited parallelism problems if the data frame is small enough to fit into the memory.</p><h4>Shuffle Hash Join</h4><p>Shuffle Hash join works based on the concept of map reduce. Map through the data frames and use the values of the join column as output key. Shuffles the data frames based on the output keys and join the data frames in the reduce phase as the rows from the different data frame with the same keys will ended up in the same machine.</p><p>Spark chooses Shuffle Hash join when Sort merge join is turned off or if the key is not suitable and also based on the accompanying two functions.</p><pre>def canBuildLocalHashMap(plan:LogicalPlan):Boolean= { plan.statistics.sizeInBytes &lt; conf.autoBroadcastJoinThreshold * conf.numShufflePartitions<br>}</pre><p>As the name of the function indicates Spark uses this function to make sure Shuffle Hash join is better suitable for the given dataset than broadcast join. But, there might be a few situations where some scenarios join will be superior to anything Shuffle Hash join.</p><p>So, at that point we may increase the automatic broadcast join threshold size (<em>‘spark.sql.autoBroadcastJoinThreshold’</em>) to trick the catalyst optimizer to use Broadcast join.</p><pre>def muchSmaller(a: LogicalPlan, b: LogicalPlan): Boolean = { a.statistics.sizeInBytes * 3 &lt;= b.statistics.sizeInBytes<br>}</pre><p>Creating hash tables are costly and it can be only done when the average size of a single partition is small enough to build a hash table.</p><blockquote>Sort merge join is a very good candidate in most of times as it can spill the data to the disk and doesn’t need to hold the data in memory like its counterpart Shuffle Hash join. However, when the build size is smaller than the stream size Shuffle Hash join will outperform Sort Merge join.</blockquote><p>The factors which decide the performance in the Shuffle Hash Join is same as the one in the Sort Merge Join, except it doesn’t necessarily need the partitions should be co-located.</p><ul><li>The DataFrame should be distributed evenly on the joining columns.</li><li>To leverage parallelism the DataFrame should have an adequate number of unique keys.</li></ul><blockquote>Tips: During joins if there are rows which are irrelevant to the key, filter the rows before the join. Otherwise, there will be more data shuffle over the network.</blockquote><p><strong>Conclusion</strong></p><p>Thus we have walked through the different types of algorithms used by spark for joins. Try to use Broadcast joins wherever possible and filter out the irrelevant rows to the join key to avoid unnecessary data shuffling.</p><p>And for cases if you are confident enough that Shuffle Hash join is better than Sort Merge join, disable Sort Merge join for those scenarios.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c81b4e3ed7da" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datakaresolutions/optimize-spark-sql-joins-c81b4e3ed7da">Optimize Spark SQL Joins</a> was originally published in <a href="https://medium.com/datakaresolutions">DataKare Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compaction in Hive]]></title>
            <link>https://medium.com/datakaresolutions/compaction-in-hive-97a1d072400f?source=rss----a787ff01f420---4</link>
            <guid isPermaLink="false">https://medium.com/p/97a1d072400f</guid>
            <category><![CDATA[hive]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[nifi]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Prabhath Vemula]]></dc:creator>
            <pubDate>Thu, 21 Feb 2019 11:41:01 GMT</pubDate>
            <atom:updated>2019-02-21T11:41:01.848Z</atom:updated>
            <content:encoded><![CDATA[<p>This article centers around covering how to utilize compaction effectively to counter the small file problem in HDFS.</p><h4>Small File Problem</h4><p>HDFS is not suitable to work with small files. In HDFS a file is considered smaller, if it is significantly smaller than the HDFS default block size (I.e. 128mb).</p><p>To make HDFS faster all file names and block addresses are stored in Namenode memory. In this way, that implies, if there is any modification done in the file system or reading a file location, all of these can be served without any disk I/OS.</p><p>But this design approach to put away all metadata in memory has its own tradeoffs. One of them is that for every file, directory and block in HDFS we need to spend around 150 bytes of namenode’s memory. So, If there are millions of files, then the amount of RAM that needs to be reserved by the Namenode becomes large.</p><p>Besides, HDFS is not designed to geared up to efficiently accessing small files. It is designed to work with a small number of large files rather than working with large number of small files. Reading through small files normally causes lots of disk seeks which mitigates the performance.</p><h4>Compaction to the rescue</h4><p>Compaction can be used to counter small file problems by consolidating small files. This article will walk you through small file problems in Hive and how compaction can be applied on both transactional and non-transactional hive tables to overcome small files problem.</p><p>In Hive small files are normally created when any one of the accompanying scenario happen.</p><ul><li>Number of files in a partition will be increased as frequent updates are made on the hive table.</li><li>Chances are high to create more number of small files (i.e. Size lesser than default HDFS block size) when the number of reducers utilized is on the higher side.</li><li>Since there is a growing demand to query the streaming data in near real time (within 5 to 10 minutes). So the streaming data needs to be ingested into a Hive table with short interim of time, which will eventually result in lots of small files and this should be addressed in the design.</li></ul><p>For demonstration, let’s use the following hive query to create an ‘orders’ table and then apply a compaction algorithm over it.</p><pre><br>CREATE TABLE IF NOT EXISTS orders (</pre><pre>id bigint,<br>customer_id string,<br>customer_name string,<br>product_id int,<br>product_name string,<br>product_price decimal(12,2),<br>quantity int,<br>src_update_ts timestamp,<br>src_file string,<br>ingestion_ts timestamp</pre><pre>)<br>PARTITIONED BY (order_date date)<br>ROW FORMAT SERDE &#39;org.apache.hive.hcatalog.data.JsonSerDe&#39;<br>LOCATION &#39;/user/dks/datalake/orders&#39;;</pre><p>The Hive table is partitioned by date and stored in the form of JSON. As this table is partitioned by date, for 5 years of data with Avg 20 files per partition, then possibly we will end up with 5* 365 * 20 = 36,500 files. Having a huge number of files may lead to performance bottlenecks.</p><p>So, let’s run a compaction algorithm out of sight periodically to combine files whenever a particular partition reaches a certain number of files, in our case it is 5.</p><p><strong>Approach to enable compaction on Non-Transactional tables</strong></p><ul><li>Find out the list of all partitions which holds more than 5 files, this can be done by using the hive virtual column ‘input__file__name’.</li><li>Set the reducer size to define approximate file size.</li><li>Execute insert overwrite on the partitions which exceeded file threshold count, in our case which is 5.</li></ul><p>The hive configurations to use,</p><pre>set hive.support.quoted.identifiers=none;<br>set hive.exec.dynamic.partition=true;<br>set hive.exec.dynamic.partition.mode=nonstrict;<br>set hive.exec.reducers.bytes.per.reducer=268435456; --256MB reducer size.</pre><p>Use the accompanying hive query to perform compaction.</p><pre>with partition_list as<br>(</pre><pre>select order_date, count(distinct input__file__name) cnt from orders<br>group by order_date  having cnt &gt; 5</pre><pre>)<br>insert overwrite table orders partition (order_date)<br>select * from orders<br>where order_date  in (select order_date from partition_list)<br></pre><p><strong>Approach to enable compaction on Transactional tables</strong></p><p>I have already covered about Transactional tables in one of my past articles, so please examine the same <a href="https://medium.com/datakaresolutions/hive-design-patterns-632f9613fa52">here</a>, before proceeding further.</p><p>Given the need to apply frequent updates on the ACID enabled table, the hive can generate a large number of small files. Unlike a regular Hive table, ACID table handles compaction automatically. All it needs is some table properties to enable auto compaction.</p><p>“compactor.mapreduce.map.memory.mb” : specify compaction map job properties</p><p>“compactorthreshold.hive.compactor.delta.num.threshold: Trigger minor compaction threshold</p><p>“compactorthreshold.hive.compactor.delta.pct.threshold”: Threshold when to trigger major compaction</p><pre>CREATE TABLE IF NOT EXISTS orders (</pre><pre>id bigint,<br>customer_id string,<br>customer_name string,<br>product_id int,<br>product_name string,<br>product_price decimal(12,2),<br>quantity int,<br>src_update_ts timestamp,<br>src_file string,<br>ingestion_ts timestamp</pre><pre>)</pre><pre>PARTITIONED BY (order_date date)<br>CLUSTERED BY (id) INTO 10 BUCKETS STORED AS ORC<br>LOCATION &#39;/user/dks/datalake/orders_acid&#39;;<br>TBLPROPERTIES (&quot;transactional&quot;=&quot;true&quot;,<br>&quot;compactor.mapreduce.map.memory.mb&quot;=&quot;3072&quot;,     -- specify compaction map job properties<br>&quot;compactorthreshold.hive.compactor.delta.num.threshold&quot;=&quot;20&quot;,  -- trigger minor compaction if there are more than 20 delta directories<br>&quot;compactorthreshold.hive.compactor.delta.pct.threshold&quot;=&quot;0.5&quot; -- trigger major compaction if the ratio of size of delta files to          -- size of base files is greater than 50%</pre><pre>);</pre><p><strong>Conclusion</strong></p><p>Thus, compaction can be utilized effectively to build a robust data pipeline, which will ensure there will be of no small files.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97a1d072400f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datakaresolutions/compaction-in-hive-97a1d072400f">Compaction in Hive</a> was originally published in <a href="https://medium.com/datakaresolutions">DataKare Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hive Design Patterns]]></title>
            <link>https://medium.com/datakaresolutions/hive-design-patterns-632f9613fa52?source=rss----a787ff01f420---4</link>
            <guid isPermaLink="false">https://medium.com/p/632f9613fa52</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[hive]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[apache-nifi]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Prabhath Vemula]]></dc:creator>
            <pubDate>Wed, 20 Feb 2019 02:16:28 GMT</pubDate>
            <atom:updated>2019-02-20T04:12:48.778Z</atom:updated>
            <content:encoded><![CDATA[<h4>Incremental Ingestion -Acid Enabled Tables</h4><p>This article is a continuation of my previous article, which you can peruse <a href="https://medium.com/datakaresolutions/hive-design-patterns-783d6104d852">here.</a> Like the previous one this article also walks you through all the three sorts of Incremental Ingestion which should be possible on Hive tables yet just this time the tables are ACID enabled.</p><p>For demonstration purpose, we will be using the same example from the previous article. Let’s Start with creating a stage table for the same ‘orders’ data.</p><h4><strong>Step 1: Create Hive Stage Table</strong></h4><pre>CREATE EXTERNAL TABLE IF NOT EXISTS orders_stg (</pre><pre>id string,<br>customer_id string,<br>customer_name string,<br>product_id string,<br>product_name string,<br>product_price string,<br>quantity string,<br>order_date string,<br>src_update_ts string</pre><pre>)<br>ROW FORMAT SERDE &#39;org.apache.hive.hcatalog.data.JsonSerDe&#39;<br>LOCATION &#39;/user/dks/datalake/orders_stg&#39;;<br>/user/dks/datalake/orders_stg  // Location of the source data</pre><h4>Step 2: ACID enabled Tables in Hive</h4><p>As to keep up with the consistency of database before and after transactions, certain properties are followed. ACID stands for four traits of database transactions which are,</p><p><strong>Atomicity:</strong> A task either succeeds totally or fizzles, it doesn’t leave halfway information.</p><p><strong>Consistency: </strong>Once an application performs an operation the results of that operations are notified to it in each subsequent activity.</p><p><strong>Isolation: </strong>An<strong> </strong>incomplete operation by one user/client does not cause startling reactions for different users/clients.</p><p><strong>Durability: </strong>when an operation is finished it will be preserved even withstanding machine or system failure.</p><p>These qualities have for some time been anticipated from database systems as part of their transaction functionality.</p><blockquote>ACID transaction table functionality is available from Hive version 0.13.</blockquote><p>The principle motivation behind introducing ACID tables in Hive is to address following situations:</p><ol><li>Streaming Data Ingestion to Hive tables with frequent updates and insert data, enabling readers to get consistent view of data.</li><li>To counter too many small files.</li><li>Slowing changing functionality to Hive table.</li><li>Bulk Updates using SQL Merge.</li></ol><blockquote>Please note that ACID tables still doesn’t bolster commit and rollback. Only ORC file format is supported. Tables must be bucketed in order to utilize this feature.</blockquote><p>In an “ACID” enabled table, data is stored as a set of base files. New records, updates, and deletes are stored as delta files. For each transactions a new set of delta files are created.When reading the data from table, the reader blends the base and delta records, applying any updates and deletes as it reads.</p><p>Having so many delta/small files can lead to performance issues, this can be addressed by utilizing the compaction process which combines the delta files. Compaction is explained in the later part of this subject.</p><h4>Defining Acid enabled Tables</h4><p>To define an ACID enabled table in Hive use the accompanying configuration parameters,</p><pre>Set <a href="https://cwiki.apache.org/confluence/display/Hive/Configuration+Properties#ConfigurationProperties-hive.enforce.bucketing">hive.enforce.bucketing</a>=true<br>Set <a href="https://cwiki.apache.org/confluence/display/Hive/Configuration+Properties#ConfigurationProperties-hive.exec.dynamic.partition.mode">hive.exec.dynamic.partition.mode</a>= nonstrict<br>Set h<a href="https://cwiki.apache.org/confluence/display/Hive/Configuration+Properties#ConfigurationProperties-hive.support.concurrency">ive.support.concurrency</a>=true</pre><blockquote>and set the “transactional”=”true” table property on HIVE DDL query which enables the ACID features on Hive table.</blockquote><pre>CREATE TABLE IF NOT EXISTS orders (</pre><pre>id bigint,<br>customer_id string,<br>customer_name string,<br>product_id int,<br>product_name string,<br>product_price decimal(12,2),<br>quantity int,<br>src_update_ts timestamp,<br>src_file string,<br>ingestion_ts timestamp</pre><pre>)<br>PARTITIONED BY (order_date date)<br>CLUSTERED BY (id) INTO 10 BUCKETS STORED AS ORC<br>LOCATION &#39;/user/dks/datalake/orders_acid&#39;;<br>TBLPROPERTIES (&quot;transactional&quot;=&quot;true&quot;)</pre><h4><strong>Step 3: Ingestion</strong></h4><p>The following query can be used to perform insert/update or delete based on the requirements.</p><pre>with new_data_stg as  (select * from orders_stg)<br>MERGE INTO orders AS T<br>USING new_data_stg AS S<br>ON T.ID = S.ID and T.order_date = S.order_date<br>WHEN MATCHED AND (T.quantity != S.quantity AND S.quantity IS NOT NULL) THEN UPDATE SET quantity = S.quantity, src_update_ts = S.src_update_ts<br>WHEN MATCHED AND S.quantity IS NULL THEN DELETE<br>WHEN NOT MATCHED THEN INSERT VALUES (S.ID, S.customer_id, s.customer_name, s.product_id, s.product_name, s.product_price,quantity,src_update_ts,ingestion_ts, cast<br>(order_date as date));</pre><p>As mentioned above the disadvantage with this approach is each time an update/insert or delete operation is performed on a partition or table, Hive creates delta files which results in huge number of small delta files. Which can hinder the performance while reading the data. To counter this, enable auto compactor option on the table so that Hive can perform major and minor compaction out of sight to combine small/delta files.</p><p>The revised query to enable compaction on the hive table:</p><pre>CREATE TABLE IF NOT EXISTS orders (</pre><pre>id bigint,<br>customer_id string,<br>customer_name string,<br>product_id int,<br>product_name string,<br>product_price decimal(12,2),<br>quantity int,<br>src_update_ts timestamp,<br>src_file string,<br>ingestion_ts timestamp</pre><pre>)<br>PARTITIONED BY (order_date date)<br>CLUSTERED BY (id) INTO 10 BUCKETS STORED AS ORC<br>LOCATION &#39;/user/dks/datalake/orders_acid&#39;;<br>TBLPROPERTIES (&quot;transactional&quot;=&quot;true&quot;,<br>&quot;compactor.mapreduce.map.memory.mb&quot;=&quot;3072&quot;,     -- specify compaction map job properties<br>&quot;compactorthreshold.hive.compactor.delta.num.threshold&quot;=&quot;20&quot;,  -- trigger minor compaction if there are more than 20 delta directories<br>&quot;compactorthreshold.hive.compactor.delta.pct.threshold&quot;=&quot;0.5&quot; -- trigger major compaction if the ratio of size of delta files to          -- size of base files is greater than 50%<br>);</pre><h4><strong>Conclusion</strong></h4><p>So far we have covered various sorts of methods to perform incremental ingestion on Hive table and ACID enabled hive tables. As discussed, based on the criteria and requirement choose the suitable ingestion type.</p><p>Please feel free to contact me at my <a href="https://twitter.com/PrabhathVemula">twitter</a> account, if you have any sort of queries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=632f9613fa52" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datakaresolutions/hive-design-patterns-632f9613fa52">Hive Design Patterns</a> was originally published in <a href="https://medium.com/datakaresolutions">DataKare Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hive Design Patterns]]></title>
            <link>https://medium.com/datakaresolutions/hive-design-patterns-783d6104d852?source=rss----a787ff01f420---4</link>
            <guid isPermaLink="false">https://medium.com/p/783d6104d852</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[hive]]></category>
            <dc:creator><![CDATA[Prabhath Vemula]]></dc:creator>
            <pubDate>Sun, 17 Feb 2019 02:10:59 GMT</pubDate>
            <atom:updated>2019-02-18T23:29:53.258Z</atom:updated>
            <content:encoded><![CDATA[<h4>Incremental Ingestion</h4><h4>Apache Hive</h4><p>Apache Hive has evolved as one of the most popular interactive and analytical data store in the Hadoop ecosystem, due to this demand, Hive will play a major role in designing a robust big data pipeline.</p><p>Hive handles all types of data sources such as file system, database, streaming etc… It provides rich functionality for data aggregation, data analysis and querying.</p><p>This article explains a few design patterns for ingesting incremental data to the HIVE tables. The main focus of this article is explaining how to use hive efficiently in big data pipelines.</p><p>Typically the data ingestion process involves following scenarios to add new set of data to the Hadoop layer.</p><ul><li><strong>Complete Load</strong>: In this method, entire table/partition is truncated and then added with new full set of data.</li><li><strong>Append Load</strong>: New data is appended to existing data for each batch of data refresh.</li><li><strong>Insert or Update Ingestion</strong>: In this method, data with new key is inserted to the table, whereas if the relevant key already exists in partition/table then record is updated with latest info.</li></ul><p>Let’s go through each of these scenarios in detail. For demonstration purpose, we will be using orders table.</p><p>Orders table is in JSON format and contains below fields.</p><pre>1)   ID<br>2)   Order_ID<br>3)   Product_ID<br>4)   Product_Name<br>5)   Quanity<br>6)   Product_Price<br>7)   Customer_Id<br>8)   Customer_Name<br>9)   Order_Date</pre><p><strong>Step 1: Create Hive Stage</strong></p><p>First step in creating data pipeline is preparing and ingesting data to stage table. Data from from source system is fetching using hadoop API and then stored in HDFS landing area/stage location. An external stage table is created pointing to this location.</p><p>In our example, the stage table for ‘order’ data is defined where “/user/dks/datalake/orders_st” is HDFS landing location where incremental data is stored.</p><pre>CREATE EXTERNAL TABLE IF NOT EXISTS orders_stg (</pre><pre>id string,<br>customer_id string,<br>customer_name string,<br>product_id string,<br>product_name string,<br>product_price string,<br>quantity string,<br>order_date string,<br>src_update_ts string</pre><pre>)</pre><pre>ROW FORMAT SERDE &#39;org.apache.hive.hcatalog.data.JsonSerDe&#39;LOCATION &#39;/user/dks/datalake/orders_stg&#39;; //source data location</pre><p><strong>Step 2: Create final table</strong></p><p>In this step will create a hive managed table which holds the final data. Table is stored in ORC format and partitioned by order_date.</p><p>Here is the DML of final table:</p><pre>CREATE TABLE IF NOT EXISTS orders (</pre><pre>id bigint,<br>customer_id string,<br>customer_name string,<br>product_id int,<br>product_name string,<br>product_price decimal(12,2),<br>quantity int,<br>src_update_ts timestamp,<br>src_file string,<br>ingestion_ts timestamp<br>)<br>PARTITIONED BY (order_date date)<br>ROW FORMAT SERDE &#39;org.apache.hive.hcatalog.data.JsonSerDe&#39;<br>LOCATION &#39;/user/dks/datalake/orders&#39;;</pre><p>Now table structure has been defined, let’s go through each incremental ingestion option.</p><p><strong>Step 3: Incremental Ingestion Types</strong></p><p>Once the stage and final tables are created, next is determine best suitable ingestion scenario that works for you ingestion. You need to consider source data format, volume, velocity of data flow, access criteria, etc.. to find ingestion type that meets your requirement.</p><p>Note that orders table is partitioned table, so ingestion will be performed at partition level.</p><h3><strong>1. Complete/Full Load</strong></h3><p>In this approach overlapping partitions are dropped completely and recreated with new set of data.This method is typically used when incremental stage table holds corresponding full partition data.</p><p>Set the following hive configurations.</p><pre>set hive.support.quoted.identifiers=none;</pre><pre>set hive.exec.dynamic.partition=true;</pre><pre>set hive.exec.dynamic.partition.mode=nonstrict;</pre><p>Query for complete load</p><pre>with new_data as(select * from orders_stg)<br>insert overwrite table orders partition(order_date)<br>select `(order_date)?+.+`, input__file__name, current_timestamp as ingestion_ts, cast(order_date as date) as part from new_data</pre><p>In the above query, Hive command “insert overwrite” drops the existing partition and then recreated with new set of data from stage table.</p><p>Hive maintains the data integrity by acquiring shared lock on the ‘orders” table and exclusive lock on partition that is being updated.</p><h3><strong>2. Append Load</strong></h3><p>In append load new data is appended to the existing partition or table.This approach is typically used when incremental data contains only new data without any redundancy.</p><p>This can be achieved using two ways. Lets go through each one. In the first approach “Append Load” is done by overwriting the existing partition by merging old and new data. Advantage with method it avoids creating small files if there are frequent appends.</p><p>Here is the query for this method:</p><pre>//Use the same hive configuration used for Complete load</pre><pre>with new_data as(select * from orders_stg)<br>insert overwrite table orders partition(order_date)<br>(select * from orders where order_date in<br>(select distinct order_date from new_data)  --existing data<br>Union all<br>(select `(order_date)?+.+`, input__file__name, current_timestamp as ingestion_ts, cast(order_date as date) as part from new_data )</pre><p>Second approach is simply add the new data to existing partition.</p><pre>//Use the same hive configuration used for Complete load</pre><pre>with new_data as(select * from orders_stg)<br>insert into table orders partition(order_date)<br>select `(order_date)?+.+`, input__file__name, current_timestamp as ingestion_ts, cast(order_date as date) as part from new_data </pre><h3><strong>3. Insert or Update Ingestion</strong></h3><p>If the requirement for data ingestion is overwrite or update existing data with incoming data then Insert/Update method is preferred.</p><p>New data is added or updated to the existing partition/table based on a row key. Data is appended to the table if the record contains new “key” otherwise existing record is updated with latest information.</p><p>This option is only possible when a row in the table can be identified uniquely using one or more columns. In orders table, “ID” field is row key. src_update_ts field indicates record time stamp.</p><p>Let me walk you through two different techniques to apply insert or update ingestion.</p><p><strong>Method 1:</strong> use over() function to find out latest record that needs to be updated/inserted.</p><pre>with new_data as(select * from orders_stg)<br>insert overwrite table orders partition(order_date)<br>select `(rank_no)?+.+` from (<br>(<br>select *, row_number() over(partition by order_date,ID order by src_update_ts desc) rank_no from(<br>select * from orders where order_date in (select distinct order_date from new_data)<br>Union<br>select `(order_date)?+.+`, input__file__name, current_timestamp as ingestion_ts, cast(order_date as date) as part from new_data<br>)  update_data<br>where rank_no=1 distribute by order_date order by ID<br>--rank_no=1 indicates recent record<br>--`(order_date)?+.+` :  This selects all the columns except order_date</pre><p><strong>Method 2:</strong></p><p>In this method, a temporary table is created by merging data from both original and incremental tables. Next data in temporary table is filtered to select only the records with latest timestamp.</p><p>Last step is original table is dropped and temporary table is renamed with original table name.</p><p>This approach is more suitable non-partition tables. For example if orders table is not partitioned. Here would be the DML</p><p><strong>Step1=&gt; </strong>RECONCILE VIEW: This view combines record set from both original table and incremental data.</p><pre>With new_data as (select * from orders_stg)<br>create view recon_orders as (<br>   select final_data.* from<br>   (select * from orders where order_date Union all<br>select `(order_date)?+.+`, input__file__name, current_timestamp as ingestion_ts, cast(order_date as date) as part from new_data<br>)  final_data<br>inner join (select order_date, ID, max(src_update_ts) as max_src_upd_ts  from   (select order_date, id, src_update_ts from orders   union all<br>select order_date,id, src_update_ts from new_data) all_data )  max_data on final_data.id=max_data.id and final_data.src_update_ts=max_data.max_src_upd_ts</pre><pre>)</pre><p><strong>Step2 =&gt;</strong>Insert into temp table</p><pre>drop table temp_orders;</pre><pre>create table temp_orders as</pre><pre>select * from recon_orders  ---this view is created in step1</pre><p><strong>Step3=&gt;</strong> Purge</p><pre>drop table orders;</pre><pre>ALTER TABLE recon_orders RENAME TO orders;</pre><p>Conclusion, this covers various methods to ingest incremental data to Hive tables.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=783d6104d852" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datakaresolutions/hive-design-patterns-783d6104d852">Hive Design Patterns</a> was originally published in <a href="https://medium.com/datakaresolutions">DataKare Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structured Streaming: Kafka integration]]></title>
            <link>https://medium.com/datakaresolutions/structured-streaming-kafka-integration-6ab1b6a56dd1?source=rss----a787ff01f420---4</link>
            <guid isPermaLink="false">https://medium.com/p/6ab1b6a56dd1</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[stream-processing]]></category>
            <dc:creator><![CDATA[Arun Jijo]]></dc:creator>
            <pubDate>Sun, 10 Feb 2019 11:06:47 GMT</pubDate>
            <atom:updated>2019-02-12T12:19:50.957Z</atom:updated>
            <content:encoded><![CDATA[<p>This article focuses on explaining how to integrate Spark’s new stream processing engine Structured Streaming with Apache Kafka brokers 0.10 and higher along with all necessary configuration details.</p><h4>Apache Kafka</h4><p>Apache Kafka is a distributed reliable, fault tolerant publish-subscribe messaging system. Kafka works on top of two major primitives producer and subscriber clients. Kafka stores the data as topics, for parallelism the topics are divided into partitions.</p><p>Producer client publishes the messages to certain topics which are in turn consumed by one or more consumer groups. As records are published to Kafka topics, Kafka assigns a sequential “ID” to each record known as offset. The published records will be retained in the Kafka cluster for a certain period of time irrespective of whether the record is consumed or not. All of these features make Kafka an excellent candidate for real-time streaming applications.</p><h4>Kafka integration in Structured Streaming</h4><p>Structured Streaming is shipped with both Kafka source and Kafka Sink. I.e. It is possible to publish and consume messages from Kafka brokers without hassle.</p><p>Let’s dive into the Kafka source with an example.</p><h4>Adding Dependency</h4><p>Add the Structured Streaming dependencies for Kafka for developing the application. For maven/sbt projects use the following definitions.</p><pre>groupId = org.apache.spark<br>artifactId = spark-sql-kafka-0-10_2.11<br>version = 2.4.0//spark version</pre><h4>Reading Records from Kafka topics</h4><p>For creating Kafka Source Internally Structured Streaming uses ‘KafkaSourceProvider’ which requires Subscribe and bootstrap server configuration properties to initiate the Kafka source.</p><pre># Construct a streaming DataFrame that reads from topic person<br>val df = spark.readStream.format(&quot;kafka&quot;)<br>.option(&quot;kafka.bootstrap.servers&quot;, &quot;host:port&quot;)<br>.option(&quot;subscribe&quot;, &quot;person&quot;)<br>.option(&quot;startingOffsets&quot;, &quot;earliest&quot;)<br>.load()</pre><p>The example mentioned above creates an unbounded Dataframe subscribed to topic named “person”. It&#39;s also possible to set the topic name by using a regex pattern. In that case the configuration parameter “subscribe” needs to be replaced by “subscribePattern”. Structured streaming also provide a way to consume only certain partitions of a topic by using “assign” parameter, to do so, the value should be of the type JSON format and it is possible to subscribe to more than one format.</p><p>Specifying a topic name along with the partitions to consume.</p><pre>option(&quot;assign&quot;, &quot;{&quot;topicA&quot;:[0,1],&quot;topicB&quot;:[2,4]}&quot;)</pre><p>‘kafka.bootstrap.servers’ configuration parameter points to the location of the Kafka bootstrap servers. It should be in ‘hostname:port’ format and should be comma separated if there is more than one server.</p><p>An important note to spark developers who used DStreams is that option ‘auto.offset.reset’ is not supported in Structured Streaming. Instead of that configuration parameter ‘startingOffsets’ needs to be set to ‘latest’ or ‘earliest’. If this parameter is not configured structured streaming will use the default value which is ‘latest’. ‘startingOffsets’ also allows to explicitly configure the offsets and partitions to consume from.</p><p>The configuration format should be of JSON type,</p><pre>option(&quot;startingOffsets&quot;,&quot;&quot;&quot;{&quot;person&quot;:{&quot;0&quot;:23,&quot;1&quot;:-2},&quot;cusomer&quot;: {&quot;0&quot;:-1}}&quot;&quot;&quot;)</pre><p>In the above mentioned JSON string denotes two topic names ‘person’ and ‘customer’ along with their partitions and offsets. Here ‘-2’ denotes earliest and ‘-1’ denotes latest.</p><p>And another thing to note is this parameter will only take into effect only when the streaming query is started and if the query is stopped spark will consume from the offset where it left off once restarted.</p><h4><strong>Other Optional Configurations</strong></h4><ul><li>maxOffsetsPerTrigger :- To specify the amount of offsets to processed per trigger interval .</li><li>kafkaConsumer.pollTimeoutMs :- Timeout to wait to poll data from Kafka to executors. Value should be specified in milliseconds.</li><li>fetchOffset.numRetries :- Number of times to retry fetching Kafka offset before giving up.</li><li>fetchOffset.retryIntervalMs :- Intervel between each retry to fetch Kafka offsets in milliseconds.</li></ul><h4>Schema</h4><p>The Kafka source has fixed schema which covers all the necessary details required for traceability. Let’s take a closer look at the schema of our streaming dataframe which we have created earlier.</p><pre>root</pre><pre>|-- key: binary (nullable = true)<br>|-- value: binary (nullable = true)<br>|-- topic: string (nullable = true)<br>|-- partition: integer (nullable = true)<br>|-- offset: long (nullable = true)<br>|-- timestamp: timestamp (nullable = true)<br>|-- timestampType: integer (nullable = true)</pre><p>The schema consists of all the metadata associated with a Kafka message. As we know the messages in the Kafka clusters will be stored in serialized form, the data type of the ‘value’ field is binary which holds the actual value. Structured streaming doesn’t have any inbuilt deserializers even for the common formats like string and integer. For deserializing the data we need to rely on spark SQL functions. If one is not available for your particular data type, then there is no other option than developing a custom deserializer.</p><h4><strong>Example:</strong></h4><p>For this example, we will be reusing the Streaming dataframe which we have created earlier and was subscribed to the topic ‘person’. Each record under topic ‘person’ is of the format,</p><p>{“name”:”xyz”,”age”:12,”address”:”xyz”}</p><p><strong>Create the schema for our data</strong></p><pre>val personSchema:StructType = new StructType()<br>.add(&quot;name&quot;, DataTypes.StringType)<br>.add(&quot;age&quot;, DataTypes.IntegerType)<br>.add(&quot;address&quot;, DataTypes.StringType)</pre><p><strong>Deserializing value</strong></p><p>To convert the bytes back to String, Spark SQL contains a built in function named ‘CAST’</p><pre>//casting from binary to String<br>val castedDf = df.selectExpr(&quot;CAST(value AS STRING)&quot;)</pre><p>At this point the dataframe looks like,</p><pre>+--------------------+<br>|               value|<br>+--------------------+<br>|{&quot;name&quot;:&quot;xyz”,”age..|<br>+--------------------+</pre><p>Spark SQL has some amazing built in functions to play with JSON data. To deserialize JSON data, it is recommended to use from_json function and to serialize use to_json function.</p><pre>val jsonDf =  castedDf.select(from_json($&quot;value&quot;,personSchema).as(&quot;values&quot;))</pre><p>Now if we look at the schema, it is found that the value field is of type struct.</p><pre>root<br>|-- values: struct (nullable = true)<br>|    |-- name: string (nullable = true) <br>|    |-- age: integer (nullable = true)<br>|    |-- address: string (nullable = true)</pre><p>It takes just a select query to flatten the data.</p><pre>val flattenedJsonDf = jsonDf.select($&quot;values.*&quot;)</pre><p>After flattening the schema looks like,</p><pre>root<br>|-- name: string (nullable = true)<br>|-- age: integer (nullable = true)<br>|-- address: string (nullable = true)</pre><p>Printing data frame to console</p><pre>flattenedJsonDf.writeStream<br>.format(&quot;console&quot;)<br>.option(&quot;truncate&quot;,&quot;false&quot;)<br>.option(&quot;checkpointLocation&quot;, &quot;checkpoint/directory&quot;).<br>.trigger(Trigger.ProcessingTime(&quot;10 second&quot;))<br>.start()<br>.awaitTermination()</pre><h4><strong>Create a Kafka Batch Query</strong></h4><p>Spark also provides a feature to fetch the data from Kafka in batch mode. In batch mode Spark will consume all the messages at once. Kafka in batch mode requires two important parameters Starting offsets and ending offsets, if not specified spark will consider the default configuration which is,</p><ul><li>startingOffsets — earliest</li><li>endingOffsets — latest</li></ul><pre><strong>val</strong> df <strong>=</strong> spark<br>.read<br>.format(&quot;kafka&quot;)<br>.option(&quot;kafka.bootstrap.servers&quot;, &quot;host:port&quot;)<br>.option(&quot;subscribe&quot;, &quot;person,customer&quot;)<br>.option(&quot;startingOffsets&quot;, &quot;&quot;&quot;{&quot;person&quot;:{&quot;0&quot;:50,&quot;1&quot;:-2},&quot;customer&quot;:{&quot;0&quot;:-2}}&quot;&quot;&quot;)<br>.option(&quot;endingOffsets&quot;, &quot;&quot;&quot;{&quot;person&quot;:{&quot;0&quot;:1000,&quot;1&quot;:-1},&quot;customer&quot;:{&quot;0&quot;:-1}}&quot;&quot;&quot;)<br>.load()</pre><p>An important thing to note is ‘endingOffsets’ will be only applicable to Kafka batch query and not for streaming query.</p><p>If you have any queries please feel free to contact me on <a href="https://twitter.com/ArunJijo36">twitter</a> and follow <a href="https://twitter.com/DataKareS">data kare solutions</a> for more Big data articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ab1b6a56dd1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datakaresolutions/structured-streaming-kafka-integration-6ab1b6a56dd1">Structured Streaming: Kafka integration</a> was originally published in <a href="https://medium.com/datakaresolutions">DataKare Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>