<?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 Prabhath Vemula on Medium]]></title>
        <description><![CDATA[Stories by Prabhath Vemula on Medium]]></description>
        <link>https://medium.com/@prabhathvemula?source=rss-3ca68db85820------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RB5K8MtpFKSoxs-9.jpg</url>
            <title>Stories by Prabhath Vemula on Medium</title>
            <link>https://medium.com/@prabhathvemula?source=rss-3ca68db85820------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:21:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prabhathvemula/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[Data Engineering’s Impending Frontier: A Look at the Shift from Warehousing to AI]]></title>
            <link>https://medium.com/@prabhathvemula/data-engineerings-impending-frontier-a-look-at-the-shift-from-warehousing-to-ai-42e3e97f676a?source=rss-3ca68db85820------2</link>
            <guid isPermaLink="false">https://medium.com/p/42e3e97f676a</guid>
            <dc:creator><![CDATA[Prabhath Vemula]]></dc:creator>
            <pubDate>Tue, 27 May 2025 21:33:01 GMT</pubDate>
            <atom:updated>2025-05-27T21:33:01.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W4v9EnezF3O8Q6qe2prRfg.jpeg" /></figure><h3>The Evolving Landscape of Data: Infrastructure, Roles, and the AI-Driven Future</h3><p>The field of data management has undergone a profound transformation, witnessing significant shifts in technologies, architectures, and professional roles. Initially, the discipline centered on traditional data warehousing, where professionals — often BI Developers, ETL Developers, or Data Warehouse Architects — focused on designing schemas, building ETL pipelines for nightly batch loads, and optimizing SQL queries on robust systems like Netezza and Teradata. The primary objective was to manage structured data and deliver reliable reports.</p><p>However, the data landscape has shifted dramatically. The explosion of data diversity and volume, the advent of cloud computing, and now the pervasive influence of AI/LLMs have fundamentally altered not just the tools, but the very nature of data work. This evolution saw a transition towards modern cloud platforms like Snowflake, BigQuery, and Databricks, and with it, a redefinition of roles towards the “Data Engineer” — a position demanding a broader skillset and a different strategic mindset.</p><p>This article explores that evolution, outlines the practical differences between past and present paradigms, and considers the future trajectory of data engineering in an increasingly AI-driven world.</p><p><strong>The Foundations: Traditional Warehousing and Its Constraints</strong></p><p>Traditional Massively Parallel Processing (MPP) warehouses and appliances were pivotal, offering many organizations their first real opportunity to consolidate data for analysis. Professionals working with these systems became proficient in relational modeling, SQL optimization, and managing complex ETL workflows using specialized tools. For years, these systems formed the backbone of Business Intelligence.</p><p>However, operating within their architectural boundaries presented significant and growing challenges as data ecosystems became more complex:</p><ul><li>Infrastructure Rigidity and Scaling Hurdles: A major limitation was the tight coupling of compute and storage, typically within physical appliances or integrated clusters. Scaling required extensive planning, capital expenditure for hardware, and often disruptive downtime. Elastic adjustment of resources to meet fluctuating demand was not feasible, leading to over-provisioning or performance bottlenecks. This operational overhead, along with complex and costly disaster recovery, was a constant factor.</li><li>Data Format and Processing Limitations: These systems were optimized for structured data loaded via schema-on-write. Handling semi-structured (JSON, XML) or unstructured data (text, logs) was cumbersome, often resulting in data being ignored, stored inefficiently, or requiring complex pre-processing outside the warehouse. Advanced analytics or non-SQL based processing directly within the warehouse was typically impractical.</li><li>Development and Integration Bottlenecks: SQL, while powerful, limited the complexity of logic implementable directly in the warehouse. Lack of native support for general-purpose languages like Python or Java meant heavy reliance on external ETL tools or cumbersome stored procedures. This hampered reusable code frameworks, slowed innovation, and made integration with emerging AI/ML tools challenging. Vendor lock-in was also a common constraint.</li></ul><p>As data volume, velocity, and variety grew, traditional warehouses struggled, signaling the need for a new approach.</p><p><strong>The Transition: Rise of Big Data, Cloud, and the “Data Engineer”</strong></p><p>The emergence of Hadoop introduced concepts like distributed file systems (HDFS) for inexpensive storage of diverse data formats and distributed processing frameworks (MapReduce, then Spark). While a catalyst for change, Hadoop often brought significant operational complexity.</p><p>The true acceleration of this transformation, however, came with cloud platforms. Services like Snowflake, BigQuery, and Databricks offered managed, scalable solutions that addressed the core limitations of the traditional model. This technological shift drove an evolution in professional roles. Skills expanded beyond SQL and ETL tools to include:</p><ul><li>Cloud Infrastructure: Understanding object storage (S3, ADLS, GCS), virtual machines, containers, serverless functions, and Infrastructure as Code (IaC).</li><li>Distributed Computing: Grasping principles behind Spark or other distributed engines.</li><li>Programming: Proficiency in Python became almost essential, alongside Scala or Java, for data manipulation, automation, and API integration.</li><li>Broader Data Ecosystem: Awareness of message queues (Kafka), orchestration tools (Airflow), data quality frameworks, and more.</li></ul><p>This expanded scope is what truly defines the “Data Engineer” role, differentiating it from the more narrowly focused “Data Warehouse Developer.” Data Engineers became responsible not just for loading data, but for building and operating robust, scalable, and efficient data pipelines and platforms.</p><p><strong>Modern Data Platforms: Enabling Speed, Scale, and AI</strong></p><p>Working with modern cloud data platforms has fundamentally changed how organizations approach data challenges. The key advantages are clear:</p><ul><li>Flexibility and Developer Productivity: The architectural separation of storage and compute allows independent, elastic scaling, drastically improving cost efficiency and performance. Native support for Python, Java, and Scala alongside SQL empowers developers to use the best language for the task, leverage open-source libraries, and build complex applications directly on data. Handling diverse data types is significantly more straightforward.</li><li>Scalability, Cost Efficiency, and Control: Cloud platforms offer virtually limitless on-demand scalability. Pay-as-you-go pricing makes large-scale data processing and experimentation economically viable. While providers manage physical hardware, users gain fine-grained control over virtual resources via APIs and IaC tools, enabling automation and optimization.</li><li>Seamless AI/ML Integration: These platforms are designed with AI/ML workloads in mind. They provide easy data access for data scientists, integrate with popular ML libraries and MLOps platforms (e.g., MLflow), offer built-in ML capabilities (e.g., BigQuery ML, Snowpark), and connect to the broader AI ecosystem, including vector databases crucial for LLM applications like RAG. This built-in readiness is essential for AI adoption.</li></ul><p>These capabilities represent a paradigm shift, enabling use cases previously impractical or impossible.</p><p><strong>The Data Engineer in the Age of AI: What’s Next?</strong></p><p>The current AI wave, particularly with LLMs, is again reshaping the landscape, and the role of the Data Engineer is evolving in response. Key impacts and future trajectories include:</p><ul><li>Building the Foundation for AI: AI initiatives demand robust data infrastructure. Data Engineers are critical in building reliable pipelines to collect, clean, transform, and serve the vast, diverse data AI models consume. Data quality, lineage, and governance become even more paramount. Understanding vector databases, feature stores, and MLOps principles is crucial for supporting ML Engineers and Data Scientists.</li><li>AI Augmenting Data Engineering Tasks: AI tools are emerging to assist Data Engineers directly — AI-powered code generation for SQL/Python, automated data quality anomaly detection, intelligent pipeline optimization suggestions, and natural language interfaces for data querying or infrastructure management. These tools promise to boost productivity, allowing focus on higher-level design.</li><li>Shift Towards Platform Thinking: As data stacks integrate more deeply with AI tools, Data Engineers increasingly need to adopt a platform engineering mindset — building reusable components, defining clear interfaces, ensuring observability, and managing overall data platform health.</li><li>Continuous Learning Remains Paramount: The accelerating pace of change necessitates a commitment to continuous learning — staying updated on core data technologies, fundamental AI/ML concepts, new tools, and best practices for MLOps and data governance in the AI context.</li></ul><p>The core principles of data engineering — ensuring data is available, reliable, and usable — remain fundamental. However, the context is shifting from primarily serving human analysts and BI dashboards to increasingly serving AI models and automated systems, while also leveraging AI to enhance data engineering workflows.</p><p><strong>Final Thoughts: Embracing the Evolution</strong></p><p>The journey from the structured world of traditional data warehousing to the dynamic, AI-influenced landscape of modern data engineering has been one of constant adaptation across the industry. It has required letting go of old assumptions, embracing new programming languages and paradigms, understanding cloud architecture, and recognizing the ongoing evolution of data roles.</p><p>The shift from “Data Warehouse Developer” to “Data Engineer” reflected a significant expansion of responsibilities and required skills. Now, as AI becomes more central, the role is evolving further. It’s an exciting, challenging era for the field. The tools are more powerful, the potential impact is enormous, and the need for skilled professionals who can bridge the gap between raw data and valuable insights (human or machine-driven) is only growing. Staying curious, adaptable, and focused on delivering value through reliable data remains the key to navigating the road ahead.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42e3e97f676a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NIFI — Monitoring Data Flows]]></title>
            <link>https://medium.com/datakaresolutions/nifi-monitoring-data-flows-aa5b7f4febef?source=rss-3ca68db85820------2</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[HBase — Optimization factors to ponder]]></title>
            <link>https://medium.com/@prabhathvemula/hbase-optimization-factors-to-ponder-7b53bb48398d?source=rss-3ca68db85820------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b53bb48398d</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[hbase]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Prabhath Vemula]]></dc:creator>
            <pubDate>Mon, 21 Oct 2019 03:09:55 GMT</pubDate>
            <atom:updated>2019-10-21T03:09:55.714Z</atom:updated>
            <content:encoded><![CDATA[<h3>HBase — Optimization factors to ponder</h3><p>HBase has made itself an prominent space among NoSQL engines and in BigData industry. Optimization is an key phase in every distributed processing storage engines. Let’s walk through key HBase optimization knobs to consider.</p><h4>HBase Write Optimization</h4><p>Carryout inserts via batch wherever possible by make use of BufferedMutator.<br> BufferedMutator buffers the puts in buffer and flush it to HBase when the buffering threshold is reached. The following parameters needs to be taken care of when dealing with BufferedMutator.</p><p><strong>hbase.client.write.buffer</strong></p><p>Buffer size in bytes, higher the size higher the throughput.</p><p><strong>hbase.client.max.total.tasks</strong></p><p>Maximum number of requests pending throughout the cluster until AsyncProcess begins to block requests.</p><p><strong>hbase.client.max.perserver.tasks</strong></p><p>Maximum number of pending requests for an region server until AsyncProcess begins to block requests.</p><p><strong>hbase.client.max.perregion.tasks</strong></p><p>Requests per region.</p><p>To avoid RPC overheads when issuing multiple puts, pass the puts as List of puts to the HBase client. The client will group the puts by different region server and each RPC request will be issued for each batch.</p><p>The following knobs will come in handy when the write optimization is at its peak.</p><p><strong>hbase.hregion.memstore.flush.size</strong></p><p>Size of each memstore opened for a single column family, the memstore gets flushed to disk in the form of a Hfile once the threshold size is reached. During peak times Hfiles will be flushed to the disk frequently. As frequntly the Hfiles flushing, quicker the compaction getting triggered which will cause IO overhead. Hence the flush size should be moderate in a way it should ensure minimal compactions and leave optimal memory for other regions and column families in the region server.</p><p><strong>hbase.hregion.memstore.block.multiplier</strong></p><p>Allows a single memstore to be extended during peak writes by using this multiplier.</p><blockquote>N.B- Write operations will be blocked to the column family. Once the memstore size breaches the flush.size * block.multiplier threshold.</blockquote><p><strong>hbase.regionserver.handler.count</strong></p><p>Specifies the number of RPC listeners / threads spun up to respond to users incoming requests.</p><p><strong>hbase.client.retries</strong></p><p>The maximum number of retries. Used as a limit for all retrievable operations like having the value of a column, beginning a row update, etc.</p><p><strong>hbase.client.pause</strong></p><p>General client pause value. Used mostly as value to wait before running a retry of a failed get, region lookup, etc</p><p><strong>hbase.rpc.timeout</strong></p><p>Timeout interval RPC layer uses to determining how long can a HBase client can take for a remote call before throwing TimeOutException.</p><p><strong>hbase.client.operation.timeout</strong></p><p>Timeout which defines that a blocking operation in a table will not take more than this. If an RPC request fails in an operation, the operation will be retried until success or an exception will be thrown if the retries are exceeded the specified threshold. But in case if the total time taken of blocking breached the defined operation timeout before retries exhausted, then the operation will break early with an Exception.</p><h4>Compression of HBase tables</h4><p>HBase is data intensive, making data reads bottleneck in overall process.<br> By leveraging compression, data occupies less space on disk. Thus making the reads efficient but with an trade off of increase in CPU load because of un-compression.</p><h4>Miscellaneous Considerations</h4><ul><li>Row key should be not be designed for full table scan.</li><li>Use filters with queries.</li><li>Consider disabling of WAL during bulk Loading.</li><li>Use constants to store column family and column names, because converting string to byte arrays every time is expensive especially when performing HBase operations inside a loop.</li></ul><pre><strong>Example:<br></strong>byte[] b = r.getValue(Bytes.toBytes(“cf”), Bytes.toBytes(“attr”)); <br>public static final byte[] CF = “cf”.getBytes();<br>public static final byte[] ATTR = “attr”.getBytes();</pre><p><strong>Conclusion</strong></p><p>So far we have walked through various knobs which can be tuned to obtain optimal performance in HBase. 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=7b53bb48398d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimize Spark SQL Joins]]></title>
            <link>https://medium.com/datakaresolutions/optimize-spark-sql-joins-c81b4e3ed7da?source=rss-3ca68db85820------2</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-3ca68db85820------2</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-3ca68db85820------2</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-3ca68db85820------2</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>
    </channel>
</rss>