<?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 Bruno Abbad on Medium]]></title>
        <description><![CDATA[Stories by Bruno Abbad on Medium]]></description>
        <link>https://medium.com/@abbad?source=rss-3e96cf8ac750------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YsG2L7QCoNF02JdNppboPg.png</url>
            <title>Stories by Bruno Abbad on Medium</title>
            <link>https://medium.com/@abbad?source=rss-3e96cf8ac750------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 10:02:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abbad/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 Modeling: Dimensions vs Facts]]></title>
            <link>https://medium.com/poatek/data-modeling-dimensions-vs-facts-13e83078510f?source=rss-3e96cf8ac750------2</link>
            <guid isPermaLink="false">https://medium.com/p/13e83078510f</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[dimensions]]></category>
            <category><![CDATA[facts]]></category>
            <dc:creator><![CDATA[Bruno Abbad]]></dc:creator>
            <pubDate>Wed, 22 Nov 2023 20:03:15 GMT</pubDate>
            <atom:updated>2023-11-23T15:58:48.277Z</atom:updated>
            <content:encoded><![CDATA[<p>Many issues a data team can face are related to a step before writing a single line of code. For many, data modeling can look easy and not an important step. Still, as data professionals, we must know that this decision can affect the cost and time in astronomic ways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhgNZ7RND3E8nOPKU73qDw.jpeg" /><figcaption>Photo from <a href="https://unsplash.com/pt-br/@airfocus?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">airfocus</a> on <a href="https://unsplash.com/pt-br/fotografias/homem-na-camisa-azul-de-manga-comprida-segurando-smartphone-v89zhr0iBFY?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h4>Knowing your consumer</h4><p>The starting point of the data modeling is understanding the first question before starting the project. “<strong>Who</strong> will consume this data?” As data engineers, we will have, in general, four archetypes of consumers that will vary in the way that we deliver our products to them:</p><ol><li>Data Analysts/Data Scientists Usually want “useful things,” which means we should give easy-to-query datasets with few complex data structures to avoid wasting their time decompressing and exploding arrays instead of doing the analytical job.</li><li>Data Engineers: Other data engineers are SQL pros, so it is safe to deliver to them more compact datasets; it means that it probably will be harder to query, but we have the performance trade-off.</li><li>ML Models: It will depend on the model and how it is trained, so sometimes we may need to turn the dataset into features and then into a feature store.</li><li>C-Level/Executives/Managers: The thumb rule is that we don’t deliver datasets to them; they want to see easy-to-interpret charts to decide.</li></ol><p>How we will model our data will depend on what kind of consumers we will have. Some of the biggest problems in data engineering occur when data is modeled for the wrong consumer.</p><h3>Dimensional Data Modeling</h3><h4>What is a dimension?</h4><p>A dimension is the attribute of an entity. (e.g., user’s birthday, user’s favorite food).</p><ul><li>Some dimensions can identify the entity (e.g., a user’s id).</li><li>Others are just attributes that complement the information of the entity.</li></ul><h4>Snapshot dimensions design</h4><p>This is the “standard” pattern of designing a dimension table. It will increment the table data with production snapshots from the time set. It means that if we want to track, for example, the daily activity of a user, the table would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*2NkErY2Pf1h46If71t_2Uw.png" /></figure><p>This data is elementary to query, but we can see there are drawbacks; try to imagine how this would look for a platform like Facebook or TikTok; the number of rows would be massive and cost a lot in storage.</p><h4>Cumulative table design</h4><p>The cumulative table design enters the scene to avoid the necessity of dozens of rows to track daily activities. We should use this design when we want history monitoring.</p><p>To create a cumulative table design, we will need a few core components:</p><ol><li>We will get both today’s and yesterday’s snapshot.</li><li>We FULL OUTER JOIN them so we can get all the data. Using the user’s example that was seen before, the join would give us people who were not in the database yesterday but are today, or that were yesterday but removed today.</li><li>We COALESCE values to keep everything around.</li><li>Hang onto all of history.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*absKmGCQdGTex8p9ipvYwA.png" /></figure><p>Using this modeling design has strengths and drawbacks.</p><p><strong>Strengths:</strong></p><ul><li>We can have the historical analysis without shuffling since we don’t need to GROUP BY data; we can sum it in the array or check if a value exists.</li><li>We can have an easy “transition” analysis. For example, we have the historical context in a row to map churn, resurrected, new, or deleted users.</li></ul><p><strong>Drawbacks:</strong></p><ul><li>It can only be backfilled sequentially. We can’t backfill multiple dates simultaneously; we must pick an initial point and create the table sequentially.</li><li>Handling PII data can be messy since deleted/inactive users get carried forward.</li></ul><h4>Snapshot Dimensions vs Cumulative Table Design</h4><p>The first difference that we will notice is that in the Cumulative Table Design, we will have arrays with data, with the growth representation looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*PxfAOU8JGUzK0vOBNOCYIA.png" /></figure><p>So, at the end of the week, we would have a partition with one String and seven Booleans, occupying much less storage than seven rows with data. Also, we can recreate all other previous records with the last partition.</p><p>“How many users are active this week?” To answer this question using the snapshot design, we would need to check the is_active column for the seven partitions created for each day of the week, and if in any of them there is a True value, we classify it as active. Conversely, in the Cumulative Table Design version, we only need to go to the 7th partition and check if there is any True value inside the is_active array for each user, using much less compute processing time. Compactness vs. Usability Tradeoff</p><p>Generally speaking, usability is always more important than compactness, especially when it takes employees time to use the table.</p><p>Tables can be categorized in three ways:</p><ol><li>The most usable tables: We will have no complex data types, only primitives, and are easy to manipulate with WHERE and GROUP BY.</li><li>The most compact tables: These are not meant to be humanly readable; to use them will need to be decoded, they are not directly available to be queried, and they are required to be as small as possible.</li><li>The middle-ground tables: Here, we can find a massive impact as data engineers, allowing us to use more complex data types (e.g., Array, Map and Struct), making the queries trickier and more compact.</li></ol><p>When do we use each type of table?</p><ol><li>The most usable ones are used when the analytics people are the primary consumers of the table.</li><li>The most compact consumers must be very technical, usually the software engineers. They are used on online systems where latency and data volumes matter greatly.</li><li>Middle-ground tables are used mainly as upstream staging, where most consumers are other data engineers or technical data scientists.</li></ol><h4>Slowly changing dimensions</h4><p>Sometimes, we will have dimensions that change throughout history. Let’s imagine the following scenario: We are working with a vehicle insurance company, and they want to track the car of each user. One person may have had car insurance for his Civic from 2013 to 2015, then this person changed his Civic for a Corolla, bought new insurance in 2016, and is keeping the same one until now with the insurance. If the company wants to track each user’s cars during the last decade, it must store this record.</p><p>The thing with slowly changing dimensions is to find the balance and need where the changes happen but not at a fast frequency like someone&#39;s weight.</p><p>What alternatives do we have to track these changes?</p><ol><li>Use the Snapshot dimensions design that we have seen before. Storing daily partitioned snapshots, with one record with the respective value every day, so the changes appear.</li><li>Recording the data with two extra columns: start_date and end_date. Using this pattern, we can store only when there are changes, minimizing the storage required to retain the data. A table for the vehicle insurance above would look like this:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*zk4PIjlCiszeW9xlynXPgA.png" /></figure><p>As we can see, instead of recording the data from all users daily to capture the changes, we can track when changes happened and use 9999 as current, but it can be changed for NULL, too.</p><p>In conclusion, dimensional data modeling, including Snapshot dimensions design, Cumulative table design, and handling of slowly changing dimensions, is a critical component in database management and post-data collection analysis. Snapshot dimension design allows us to track data periodically, though it might create massive and heavy databases. To counter this, the Cumulative table design \was introduced, which, despite its strengths and drawbacks, helps reduce storage costs. The choice among Usable, Compact, and Middle-ground tables is typically dictated by the nature of the data technicians who will primarily use the table, and these decisions must be deliberate and strategically made.</p><p>Slowly changing dimensions are accommodated, but they must be balanced carefully not to disrupt the database’s resemblance to real-life scenarios. Doing so gives us the foundation to maintain our data cost-effectively and efficiently. Ultimately, dimensional data models empower businesses to make better decisions, and mastering these techniques provides an invaluable tool in the armor of database management.</p><h3>Fact Data Modeling</h3><h4>What is a fact?</h4><p>A fact can be described as something that happened; it is an event. Since it already happened, facts are not slowly changing, so it is easier to model compared as dimensions in some respects.</p><p>An example of a fact is a transaction that is made. The transaction happened from someone to someone else, at a particular time, with a certain amount, and it will not be changed.</p><h4>How does fact modeling work?</h4><p>When we model a fact table, we should answer the following questions:</p><ul><li><strong>Who? </strong>Who are the actors involved in the action? Usually, they are pushed out as IDs.</li><li><strong>Where? </strong>It is most likely modeled out like who with IDs to join, but it is more likely to bring in dimensions.</li><li><strong>How? </strong>It is similar to where and can be a bit blurry in digital events, like a click on a website, the how can be by an iPhone, and where be the specific button.</li><li><strong>What? </strong>It tells us the nature of the fact, so we can understand what is the event that is happening.</li><li><strong>When? </strong>All facts have a temporal component; they are fundamentally part of the nature of the fact.</li></ul><p>Answering these questions will make modeling easy.</p><h4>What makes fact modeling hard?</h4><p>The main difficulty in the fact modeling context applies to their volume. Fact data is usually 10 to 100x the volume of dimension data. So, if we imagine a platform with 2 billion active users and 50 billion notifications sent through all the users daily if we want to track data for a week, we would have 350 billion notifications to be stored.</p><p>Fact data can need many contexts for practical analysis, which means that if we store just what happened, it cannot be very effective, so we may also need a few dimensions.</p><p>Duplicates in facts are way more common than in dimensional data and may need some treatment; an interesting approach to solve this is collapsing the dupped data, treating all duplicate data of a day as one event, for example, but we need to be aware that dupped data can be valid in some cases. Still, not all duplicates are good ones to be stored.</p><h4>When should you model facts with dimensions?</h4><p>Generally speaking, in fact data modeling, we will not bring anything into the row except for the identifier, keeping aside every other attribute.</p><p>In data engineering, we have the rule to keep data normalized when designing a fact table. Still, we need to be conscious that sometimes, joining all the fact events to get a dimension can make the pipeline slow, so sometimes this rule should be ignored and modeled with dimensions, too; it depends on the needs of the client and every decision will have tradeoffs.</p><h4>Reducing fact data modeling gives you superpowers</h4><p>The data of fact tables can vary in volume; a way to compact the table can be done through steps of reduction, and we have three levels to do so.</p><p><strong>Fact data often has this schema:</strong></p><ul><li>user_id, event_time, action, date_partition</li></ul><p>It will have a very high volume and row per event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*G2YqW3q564NZpRzigUxB-A.png" /></figure><p>We can reduce it to a second level by doing a <strong>daily aggregation:</strong></p><ul><li>user_id, date_partition, action_cnt</li></ul><p>Having a medium-sized volume and one row per user daily, it is ideal to deliver for analytics people.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*9axqeQ5pJ9vh-6LB1fItAg.png" /></figure><p>For a third level of reduction, we will use a<strong> long-array metrics </strong>design:</p><ul><li>user_id, month_start_partition/year_start_partition, action_cnt array</li></ul><p>This schema has a low volume and only one row per user per month/year. So, with the following table, we could see 90 days of data in just three rows. Usually, the long-array metrics design table is best suited for downstream pipelines since the array needs to be exploded to be explored.</p><p>The daily dates are stored as an offset of month_start or year_start, with the array’s first index being the date month_star + zero days, and the last index is the date start + array_length - 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*lhyBVxZ1y4lPxlD4jcrc9A.png" /></figure><p>One point to notice using the long-array metrics design is that dimensional joins can get weird if we want things to stay performant. The slowly changing accuracy will be the same as the month_start or year_start value until the next one, so we give up the 100% accurate slowly changing dimension tracking for massively increased performance since we can make analysis much faster in this way instead of exploding the arrays to get a precise analysis. That’s why we pick snapshots in time, month_start value, month_end_value, or even both and treat the dimensions as fixed to get the changes through time.</p><p>In summary, fact data modeling revolves around events or occurrences and necessitates answering certain fundamental questions for successful implementation, such as Who, Where, How, What, and When. The challenges of fact modeling often arise from its high volume, potential for duplicate data, and requirements for context. Striking a balance between storing fact data and relevant dimensions can greatly enhance data analysis but must be handled wisely, considering performance implications.<br>One way to handle the large volume of fact data is through reduction techniques, which transition from a high-volume per-event basis to more aggregated levels, ultimately leading to significantly smaller data volume in the design of the long-array metric. This particular design can drastically improve performance by reducing the need for array explosion but sacrifices the precision of slowly changing dimensions.</p><p>Overall, fact data modeling is a complex yet supremely invaluable process in data engineering. It allows for a comprehensive understanding and analysis of the occurring events within a system. While it requires careful planning and decision-making, successful implementation can produce highly effective systems that enhance not only data storage but also the accuracy and speed of analytics, subsequently leading to more informed decision-making.</p><h3>Properties of Facts vs Dimensions</h3><p>Generally speaking, some rules can help us classify a dimension or a fact, but in some cases, they <strong>can</strong> be overlapped.</p><p><strong>Dimensions:</strong></p><ul><li>Usually, these are the things we can GROUP BY when doing analytics.</li><li>It can be “high cardinality” or “low cardinality,” depending, but usually, the high ones are the IDs.</li><li>Generally, it comes from snapshots of the state.</li></ul><p><strong>Facts:</strong></p><ul><li>Usually aggregated when doing analytics by SUM, AVG, and COUNT.</li><li>Almost always higher volume than dimensions, although some fact sources are low-volume, we can think of them as “rare events.”</li><li>Generally, it comes from events and logs.</li></ul><p>To summarize, dimensions and facts are two crucial properties in data analysis, each with unique roles and characteristics. Dimensions, commonly sourced from snapshots of the state, often serve as metrics by which we group our data during analytics. They can have either high or low cardinality, with IDs typically assuming high. On the other hand, facts, primarily derived from events and logs, are usually used in analytics for aggregation operations such as sum, average, and count. They typically come in higher volumes than dimensions, though some fact sources can be low-volume if they represent rare events. While there might be occasional overlaps between facts and dimensions, it’s essential to distinguish between them correctly for accurate and effective data analysis. Understanding their differences and appropriate uses provides a robust base for insightful business decisions.</p><h3>Conclusion</h3><p>Indeed, understanding and effectively implementing data modeling concepts, precisely dimension and fact data modeling, is imperative in any data-driven business context. Dimensional data modeling allows us to capture and structure key attributes or entities, accommodating variabilities using snapshot designs, cumulative table designs, or handling slowly changing dimensions. However, the choice between the compactness and usability of tables must be strategic and aligned with who the primary consumers will be. On the other hand, fact data modeling focuses on capturing events or occurrences and their relevant dimensions for a complete analysis. Fact data models are usually high volume and can be made more manageable through reduction techniques at multiple levels.</p><p>While dimensions and facts carry different but equally important roles and characteristics, they collectively enrich the data analysis. Measurements, typically derived from snapshots, offer a grouping mechanism for data in analytics, while facts, commonly obtained from events, provide an aggregation mechanism.</p><p>Understanding these subtle differences between dimensions and facts Paves the way for deeper data insights and supports the formulating of actionable business strategies. The judicious, strategic planning and implementation of these data modeling techniques can power more effective decision-making, optimize costs, and enhance process efficiency, underlining the astronomical potential of competently manipulating and managing data models.</p><p>I hope this post has been interesting to you. If you want to join a team of data-driven professionals willing to share knowledge and grow, check out Poatek <a href="https://www.poatek.com/careers">Careers</a>. There may be a job opportunity waiting for you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13e83078510f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/poatek/data-modeling-dimensions-vs-facts-13e83078510f">Data Modeling: Dimensions vs Facts</a> was originally published in <a href="https://medium.com/poatek">Poatek</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Which File Format Should I Use?]]></title>
            <link>https://medium.com/@abbad/which-file-format-should-i-use-73b58404bedb?source=rss-3e96cf8ac750------2</link>
            <guid isPermaLink="false">https://medium.com/p/73b58404bedb</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Bruno Abbad]]></dc:creator>
            <pubDate>Mon, 29 May 2023 14:25:22 GMT</pubDate>
            <atom:updated>2023-05-29T14:37:50.680Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDu6VdCenl30Bg4YIihe_A.jpeg" /><figcaption>Photo from <a href="https://unsplash.com/@qwitka?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Maksym Kaharlytskyi</a> on<a href="https://unsplash.com/pt-br/fotografias/Q9y3LRuuxmg?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I often faced the question on the title when I was doing some ETL tasks in the past… “Should I save the data in the Parquet format, or is using .csv format sufficient?” to be honest, many times I just used .csv because it was the most familiar to me, however when we get to understand more about the big data environment, we see that if we want to go to the next level, we need to learn and understand the reason behind the things!</p><h4>Why do we need different file formats?</h4><p>Choosing the appropriate file format can provide the following benefits:</p><ul><li>To save storage</li><li>Do fast processing</li><li>Less time for our I/O operations</li></ul><p>When we decide which file format we are going to use, there are a lot of choices available:</p><ol><li>Faster reads</li><li>Faster writes</li><li>Spllitable or not</li><li>Schema evolution support</li><li>Advanced compression</li><li>Most compatible platform</li></ol><h4>File formats can be categorized into two main types:</h4><p><strong>Row-based file format:</strong> Writing data is easy, but when retrieving a subset of columns, it requires reading the entire record.</p><ul><li>Faster writes</li><li>Slower read</li><li>Less compression</li></ul><p>A row-based file format would look like this:</p><pre>1, joe, 10000, sales, 2, mary, 20000, hr, 3, steve, 30000, finance, 4, rose, 15000, sales</pre><p><strong>Column-based file format: </strong>If we are going to do more reads, column-based files are best.</p><ul><li>Slower writes</li><li>Efficient reads</li><li>Good compression</li><li>A column-based file format would look like this:</li></ul><pre>1 2 3 4 joe mary steve rose 10000 20000 30000 15000 sales hr finance sales</pre><h3>What are the file formats?</h3><h4>CSV file</h4><p>The most common file format is used for general purposes.</p><p>Data is stored in a human-readable format. Also, everything is stored in text form. For example, An integer will be stored as text, so the number 4565987 will be stored as text. It will take 14 bytes; storing it as an integer would take just 4.</p><p>Text files can take a lot of storage since everything is stored as a string, also when our data is stored as a string, and we want to use it as an integer, this type of conversion will take time, and we have to pay the penalty in terms of time.</p><p>Processing on text file files and I/O operations can be very slow too.</p><h4>XML &amp; JSON</h4><p>They have the same conditions that fall upon CSV files but are also not splittable, so they can not be used for distributed processing in a big data environment.</p><p>All the formats above are text files; we discussed before that text files are bad for big data, so a few <strong>specialized file formats</strong> for big data environments were developed. The most famous of them are:</p><ol><li>Avro</li><li>Orc</li><li>Parquet</li></ol><p>Two common things about them are that they are all splittable and they can use any compression technique with them.</p><p>The compression codec is kept in the metadata of this file. So whenever the reader wants to read, he learns this compression codec from metadata and can easily understand this data.</p><h4>Avro file format</h4><p>It is a row-based file format, which means writing is faster than reading.</p><p>The schema for the Avro file is stored in JSON format; The data is self-describing because the schema (metadata) is embedded as part of the data itself. However, the actual data is stored in a binary form which is quite efficient in terms of storage.</p><p>Avro file format is quite general and supports processing in many programming languages.</p><p>In terms of schema evolution, Avro is mature. There is <strong>no better</strong> format than Avro. You can easily add columns, remove them, rename them, etc.</p><p>When should I use .avro files? Avro is the best fit for storing data in the landing zone of the data lake; also, whenever we do ETL operations, Avro is a good fit because we have to read all the columns and the entire rows. Kafka and Druid suit best with .avro files.</p><h4>ORC file format</h4><p>ORC means Optimized Row Columnar; it is a column-based file format, which means writes are inefficient compared to very efficient reading. Also, the ORC file format is efficient in terms of storage.</p><p>When we talk about schema evolution, ORC is not mature as Avro but can be done with a few limitations.</p><p>The metadata is stored using protocol buffers, which allow the addition and removal of fields.</p><p>An ORC file is divided into three parts:</p><ol><li>Header: This contains the word “ORC”</li><li>Body: Made up of stripes of data, even these stripes are further divided into blocks of records. By default, 10.000 rows are there in each block. The default size of each stripe is 250 MB. The stripes can be described as the following:<br>a. Set of indexes: Max &amp; Min &amp; Count for each column in every row group in the stripe.<br>b. The data itself is broken into raw groups.<br>c. Stripe footer: Tells the encoding used.</li><li>Tail: The tail is made of two parts also:<br>a. File footer: Contains the metadata at file.<br>b. Postscript: The postscript is never compressed by itself, and it helps to understand the remaining file.</li></ol><p>Hortonworks developed the ORC format for Hive in 2013, so it best suits using a Hive environment.</p><h4>Parquet file format</h4><p>As ORC, Parquet is also a column-based file format, which applies the same principle of fast reading and slow writing.</p><p>Parquet shares many design goals with Orc, like being self-describing, but it is more general purpose. It shines when we are handling nested data.</p><p>From a schema evolution perspective, Parquet supports it somewhat, but you can only add or delete the columns from the end.</p><p>It is also divided into three:</p><ol><li>Header: With the word “Par1”</li><li>Row Groups: Contains the column chunks</li><li>Footer: Contains the file metadata, the length of file metadata and a magic number (4 bytes) “PAR1.”</li></ol><p>Parquet is best suited for processing using Spark.</p><h4>ORC vs. Parquet</h4><p>Since both are column-based file formats, when should I pick each one?</p><p>In Parquet, we can handle deeply nested data, which ORC can not do. However, ORC supports ACID properties which Parquet does not.</p><p>Regarding compression, ORC is much better than Parquet, but it will depend. For example, if you use Hive, ORC will probably be best; if you use Spark, go with Parquet.</p><p>Choosing the correct file format is crucial in the big data environment. While text-based formats like CSV, XML, and JSON are commonly used, they come with limitations such as slower processing, more extensive storage requirements, and lack of splittability for distributed processing. To overcome these challenges derived from text-based formats, specialized file formats have been developed.</p><p>Avro, ORC, and Parquet are popular file formats that address the specific needs of big data processing. Avro offers fast writing and schema evolution support, making it suitable for data storage in the landing zone of a data lake and performing ETL operations. ORC excels in efficient reading and storage optimization, making it a preferred choice within a Hive environment. On the other hand, Parquet is well-suited for processing using Spark and shines when dealing with nested data structures.</p><p>While ORC and Parquet share similarities as column-based file formats, they have distinct features. ORC supports ACID properties and has superior compression capabilities, while Parquet handles deeply nested data structures more effectively.</p><p>Ultimately, the decision between ORC and Parquet depends on the specific requirements of your use case. Consider factors such as schema evolution needs, tool compatibility, and the nature of your data to make an informed choice.</p><p>Understanding the characteristics and trade-offs of different file formats allows you to optimize storage, processing speed, and I/O operations in your big data environment. Selecting the appropriate file format unlocks the potential for efficient data processing, enabling you to unlock valuable insights and extract maximum value from your data resources.</p><p>I hope this text has provided a helpful overview of the difference between the big data file formats and which one to choose. Share this article with your friends and colleagues interested in big data, and feel free to connect with me on <a href="https://www.linkedin.com/in/abbad-bruno/">LinkedIn</a> for further discussions. Thank you for reading! 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73b58404bedb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Optimize Big Data?]]></title>
            <link>https://medium.com/@abbad/how-to-optimize-big-data-27d94cb55ef?source=rss-3e96cf8ac750------2</link>
            <guid isPermaLink="false">https://medium.com/p/27d94cb55ef</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Bruno Abbad]]></dc:creator>
            <pubDate>Wed, 17 May 2023 19:42:18 GMT</pubDate>
            <atom:updated>2023-05-26T12:55:51.513Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Optimize Big Data? 🔥</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J4ikQG8QoPmVJ52oQ4FNQw.jpeg" /><figcaption>Foto de <a href="https://unsplash.com/@timmossholder?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tim Mossholder</a> na <a href="https://unsplash.com/pt-br/fotografias/VurHDpO4VYI?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This is one of the most captivating contents I have learned in the <a href="https://trendytech.in/">Trendytech</a> big data course series. It delves into optimization techniques for Big Data, primarily applied in Hive, but it also encompasses concepts relevant to distributed computing. The content is divided into three types of optimization:</p><ul><li>Structure level optimization</li><li>Query level optimzation</li><li>Windowing functions</li></ul><h3>Structure Level Optimization Theory</h3><p>This section is covered basically with the following premise: divide the data into smaller parts.</p><h4>Partitioning</h4><p>What is “partitioning”? Partitioning splits data into smaller subsets and separates records into manageable parts based on a column value. We should perform partitioning for the most common queries. Suppose we attempt to partition a column with high cardinality. In that case, it will create numerous folders, which is undesirable because it burdens our name node with handling all this metadata. In Hive, we have two types of partitioning:</p><ol><li><strong>Static Partitioning:</strong> We should know our data and load each partition manually. Tedious process.</li><li><strong>Dynamic Partitioning: </strong>Partitions are created automatically without any manual loading.</li></ol><p>When we don’t know the data in advance, we go with dynamic partitioning, but when we know the data, we go with static partitioning.<br>But which one is faster? Since in Static, we will not let the system handle the partitioning, purely talking about speed, Static is faster.</p><h4>Bucketing</h4><p>When we have a high cardinality with our data, partitioning will not be an excellent way to optimize the performance, so we need to use bucketing. We have to define a fixed number of buckets during table creation.</p><p>For example:</p><p>Considering we have a product table with 1 million product id’s. If we partition the table on product id, we would have 1 million folders, so it would not be optimized; that’s why we use bucketing so that we can divide the product id’s into groups.</p><p>It is also possible to combine partitioning and bucketing; for example, if we partition our customer’s table by state and fix four buckets of customer_id for each one, we would have the following structure:</p><pre>/user/hive/warehouse/database.db/customers/state=CA<br><br>bucket_0_file<br><br>bucket_1_file<br><br>bucket_2_file<br><br>bucket_3_file<br><br>/user/hive/warehouse/database.db/customers/state=WA<br><br>bucket_0_file<br><br>bucket_1_file<br><br>bucket_2_file<br><br>bucket_3_file</pre><p>Why bucketing? Faster query responses and join optimization.</p><p>Below we have a table comparing Partitioning and Bucketing:</p><figure><img alt="Table compairing Partitioning and Bucketing" src="https://cdn-images-1.medium.com/max/492/1*V1nRkhtDD64ssqZx9EiFNQ.png" /><figcaption>Table compairing Partitioning and Bucketing</figcaption></figure><h3>Query Level Optimization Theory</h3><p>When we want to optimize queries, usually, the optimization must come in the joins.</p><h4>Join Optimizations</h4><ol><li>We minimize the number of join columns. Because if we reduce the join columns, there will be fewer MapReduce jobs.</li><li>Bucketing &amp; partitioning help you to optimize the joins. For this, your tables should be bucketed or partitioned on the join columns.</li><li>Converting the joins to map side jobs whenever possible.</li></ol><p>Even if a join is executed as a MapReduce job internally, the mapper will assign the join column as the key and all the other columns as the value.</p><p>We can structure specific queries to eliminate the reduce phase, which is the ideal scenario as the reduce part tends to be slower. To achieve this, we can write the join so that the reducer does not need to perform any tasks, referred to as a map side join.</p><p><strong>Map side joins are performant.</strong></p><p>What do we need to do a map side join? All tables except one should be small enough to fit in memory.</p><p><strong>Bucket Map Join:</strong></p><ol><li>The bucket map join performing join operations between two large tables.</li><li>Both tables must be bucketed based on the same join column.</li><li>The number of buckets in one table should be a multiple of the number of buckets in the other table.</li><li>Only the necessary buckets are loaded into memory, providing an advantage over map side join.</li></ol><p><strong>Sort Merge Map Join:</strong></p><ol><li>It can also be done with two big tables.</li><li>Both tables must be sorted in the join column.</li><li>Both tables should be bucketed on the join column.</li><li>The number of buckets in both tables should be precisely equal.</li><li>There will be a one-to-one mapping between buckets in both tables. And a quick joining can be performed as both buckets have sorted data.</li></ol><p><strong>Execution Flow:</strong></p><p>Before the MapReduce job is executed, a local task is completed.</p><ol><li>This local task will take the small table and create a hashtable for this small table.</li><li>Once the hashtable is created, it will be put on HDFS.</li><li>From HDFS, this hashtable is broadcasted to all nodes.</li><li>When this hashtable is copied on the nodes, it will exist in the local disk of each node — also called a distributed cache.</li><li>Hashtable is loaded into memory in each node. So each local disk of the nodes is loaded into the nodes’ memory.</li></ol><p>After this the MapReduce job is executed.</p><h3>Hive Window Functions</h3><p>What are window functions? A suite of functions that are syntactic sugar for complex queries. It reduces the need for intermediate tables to store temporary data.</p><p>For example:</p><p>What were the top-selling N products in last week’s sale?</p><p>The window = one week</p><p>The operation = ranking product sales</p><p>In another example, a query to get the revenue running total for each day would be:</p><pre>from groceries<br>select id, revenue, day,  <br>sum(revenue) over (  <br>partition by day  <br>order by id<br>) <br>as running_total;</pre><h4>Ranking</h4><p>In window functions, we have different ways to rank for various purposes.</p><ul><li>Rank: Will rank the elements in a specific order and skips the next rank when ties happen.</li></ul><pre>select name, score, <br>rank() over ( <br>order by score desc<br>) <br>as ranking from rank_test;</pre><ul><li>Dense Rank: Ranks are consecutive. No ranks are skipped, even in the case of ties.</li></ul><pre>select name, score, <br>dense_rank() over (<br>order by score desc<br>) <br>as ranking from rank_test;</pre><ul><li>Row Number: Assigns unique numbers to each row given the order by clause</li></ul><pre>select name, score, <br>row_number() over (<br>order by score desc<br>) <br>as ranking from rank_test;</pre><p>It can also be used with partition by ranking by each group, as seen in the example below:</p><pre>select name, score, <br>row_number() over ( <br>partition by name <br>order by score desc<br>) <br>as ranking from rank_test;</pre><h4>Sorting</h4><p>When we want to sort the data, we have a few options:</p><ul><li>Order by: It guarantees the total ordering, but it is limited to being done by just one reducer.</li></ul><pre>select order_value <br>from order <br>order by order_value;</pre><ul><li>Sort by: Multiple reducers can do so, but we cannot guarantee the total ordering.</li></ul><pre>select order_value <br>from order <br>sort by order_value;</pre><ul><li>Distribute by: Ensures each of the reducers gets a non-overlapping set of values.</li></ul><pre>select order_value <br>from order <br>distribute by order_value;</pre><ul><li>Distribute by sort by: If we need a non-overlapping set of values on each reducer and if we need sorting as well, then we should use distribute by sort by.</li></ul><pre>select order_value <br>from order <br>distribute by order_value <br>sort by order_value;</pre><ul><li>Cluster by: It is the same as distributed by sort by.</li></ul><pre>select order_value <br>from order <br>distribute by order_value;</pre><p>In conclusion, optimizing big data involves implementing various techniques at the structure and query levels. At the structure level, partitioning and bucketing are essential optimization strategies.</p><p>Partitioning involves dividing data into smaller subsets based on a column value while bucketing divides data into fixed groups during table creation.</p><p>Combining partitioning and bucketing can further enhance performance.<br>At the query level, optimization focuses on join operations. Minimizing the number of join columns reduces the number of MapReduce jobs required.</p><p>Bucketing and partitioning tables on join columns can significantly improve join performance. Additionally, converting joins to map side jobs whenever possible can eliminate the need for a reducer phase, leading to faster execution.</p><p>Techniques like bucket map join, and sort-merge map join are useful for optimizing join operations between large tables.</p><p>Hive window functions provide a convenient way to perform complex queries without the need for intermediate tables. Ranking, dense ranking, and row numbering are examples of window functions that can be used to order and analyze data. Sorting data can be achieved using options such as order by, sort by, distribute by, distribute by sort by, or cluster by, depending on the specific requirements.</p><p>By applying these optimization techniques, organizations can improve the performance and efficiency of their big data processing, enabling faster query responses, efficient joins, and better utilization of resources.</p><p>I hope this text has provided a clear and helpful overview of how to optimize data in Hive and distributed computing. Share this article with your friends and colleagues interested in big data, and feel free to connect with me on <a href="https://www.linkedin.com/in/abbad-bruno/">LinkedIn</a> for further discussions. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27d94cb55ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Hive, an Introduction of The Apache Hive Theory ]]></title>
            <link>https://medium.com/@abbad/how-to-hive-an-introduction-of-the-apache-hive-theory-dfbc53cf4646?source=rss-3e96cf8ac750------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfbc53cf4646</guid>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[hive]]></category>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[apache-hive]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Bruno Abbad]]></dc:creator>
            <pubDate>Mon, 17 Apr 2023 15:55:42 GMT</pubDate>
            <atom:updated>2023-04-17T15:55:42.098Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IjdqPe4DvvzrSi6HahVJ7g.jpeg" /><figcaption>Foto de <a href="https://unsplash.com/@ante_kante?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ante Hamersmit</a> na <a href="https://unsplash.com/pt-br/fotografias/gi1f13S1-64?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Following the series of texts I am writing about the content I learned in the <a href="https://trendytech.in/">TrendyTech</a> Big Data course, now is time to cover the Hive topic.</p><p>Before learning the details of Hive, you must understand the difference between Analytical and Transactional Systems.</p><h3>Analytical Systems x Transactional Systems</h3><p>A transactional system has the following characteristics:</p><ul><li>It is the one where we deal with day-to-day data. Present data.</li><li>Are there happens inserts, updates, etc.</li><li>RDBMS are best suited for transaction systems.</li><li>The best way to design a transactional system is with a monolithic system.</li></ul><p>An analytical system, on the other side, will have the following characteristics:</p><ul><li>It is the one where we deal with historical data.</li><li>Mostly read operations.</li><li>Usually, data warehouses suites better analytical systems</li><li>A distributed system is best suited for analytical systems</li></ul><p>In the table below, we can summarize the differences between transactional processing against analytical processing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*qysRRjLYsxVpz__mxDTS5g.png" /><figcaption>Table with the Transactional Processing x Analytical Processing</figcaption></figure><h3>What is Hive?</h3><p>Hive is an open-source data warehouse meant to solve analytical problems.</p><p>We will use SQL-like queries called Hive Query Language (HQL) to operate in Hive. Hive will convert these queries as a MapReduce job and submit them on the Hadoop cluster.</p><p>We can say that Hive is nothing but a way to abstract complexities from the user.</p><blockquote>Hive is an abstraction/layer on top of MapReduce.</blockquote><p>A Hive table has two parts:</p><ol><li>Actual Data (HDFS)</li><li>Metadata (Schema): Since HDFS does not allow modifications to what is written and has high latency for retrieval, it stores data in a database.</li></ol><p>But why Hive? Because it provides parallelism.</p><h3>Understanding Hive</h3><blockquote>How can Hive display data as tables if it is stored as files?</blockquote><p>The Hive Metastore exposes the file-based storage of HDFS in the form o tables. It is the bridge between data stored in files and tables exposed to users. We can summarize it with the following points:</p><ul><li>Stores metadata for all the tables in Hive</li><li>Maps the files and directories in Hive to tables.</li><li>Holds table definitions and the schema for each table.</li><li>Has information on converting files to table representations.</li></ul><p>On Hive, the metadata is stored in the metastore, and the data itself is in HDFS in the form of files, so when we query the table, this schema is imposed on the data, and we see a tabular view.</p><p>Comparing Hive with an RDBMS, we can see the differences exposed in the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*8QaYtWEuXk8PC6NVIemgQA.png" /><figcaption>Table comparing Hive with RDBMS</figcaption></figure><p>We can define low latency and high latency as the seek time taken to fetch a particular record.</p><h4>Schema on Write x Schema on Read</h4><p>RDBMS follows a schema-on-write approach, where the table is created with a schema, and the data is inserted into the table according to the established format. During data insertion, the RDBMS validates the data.</p><p>Hive is schema on read, which means that the data already exists in the form of files, so we create the table on top of data to see in a tabular manner, so the schema is built while reading the data.</p><p>To operate with the data, Hive uses HiveQL; the differences between SQL and HQL can be seen in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*ZO-25q9qaUHI45KUOnwnMw.png" /><figcaption>Table showing the HiveQL and SQL differences.</figcaption></figure><h3>Hive Concepts</h3><p>How is data stored in Hive?</p><h4>Storing Data in Hive</h4><p>Your data is, by default, stored in the warehouse directory but can be modified.</p><p>/user/hive/warehouse — Default location</p><p>/user/hive/warehouse/database name. db/table/files — How would a database and table be stored in Hive</p><h4>Normalize or Not?</h4><p>Hive prefers data in a denormalization form, which means storing the data not in granular form but in somewhat bigger tables, even if some redundancy is there.</p><p>We do not need to worry about data redundancy but instead about storing the data in fewer tables. Also, storage space is very cheap; if we spend a little more on storage, then it’s not a big deal.</p><p>If we make updates, it is possible to run into data inconsistency issues, but since Hive is not a system meant to do updates, we don’t need to worry.</p><p>The advantage to keeping data in a denormalized way in Hive is that we do not have to operate joins; we intend to minimize the joins because it takes time.</p><h4>Hive Tables</h4><ol><li>Managed Table: Hive manages the data in a Managed Table, meaning that if you drop the managed table, the data and metadata will be deleted.</li><li>External Table: Where Hive does not manage the data. The data is external to Hive; only metadata is deleted.</li></ol><p>When to go for a managed table? When there are no other Hive user</p><p>When to go for an external table? When there are more Hive users, like other tools, etc.</p><p>This text covers the basic concepts of Apache Hive, an open-source data warehouse tool designed to solve analytical problems in big data. We explored the differences between transactional and analytical systems, highlighting the features and advantages of Hive as an option for distributed analytical processing. We discussed how Hive uses Hive Query Language (HQL), a query language similar to SQL, to operate on top of the Hadoop cluster, abstracting complexities for the user. Furthermore, we saw how Hive stores data in managed and external tables and how the “schema on read” approach allows for greater flexibility in data manipulation.</p><p>As we progress in our study of Hive, we must highlight the differences from other data storage and processing tools, such as RDBMS, and how Hive can be suitable for handling large volumes of data in distributed environments. Hive is a powerful tool for extensive data analysis and can be a valuable option for data professionals and engineers working on large-scale data analysis projects.</p><p>I hope this text has provided a clear and helpful overview of Hive, and I encourage you to continue deepening your study of this fascinating tool. Share this article with your friends and colleagues interested in big data and Hive, and feel free to connect with me on <a href="https://www.linkedin.com/in/abbad-bruno/">LinkedIn</a> for further discussions. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfbc53cf4646" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Sqoop, Hadoop  RDBMS]]></title>
            <link>https://medium.com/@abbad/apache-sqoop-hadoop-rdbms-27c64a06ea4e?source=rss-3e96cf8ac750------2</link>
            <guid isPermaLink="false">https://medium.com/p/27c64a06ea4e</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[sqoop]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Bruno Abbad]]></dc:creator>
            <pubDate>Wed, 22 Mar 2023 20:33:38 GMT</pubDate>
            <atom:updated>2023-03-22T20:33:38.008Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Kcg-ooLYZpJcyBVOaOXNQ.jpeg" /><figcaption>Foto de <a href="https://unsplash.com/@heftiba?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Toa Heftiba</a> na <a href="https://unsplash.com/pt-br/fotografias/fbCxL_wEo5M?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This text is a continuation of my study on the Hadoop ecosystem; now, I concluded the Sqoop module of the <a href="https://trendytech.in/">TrendyTech</a> course and am ready to bring you what I have learned during this step.</p><p>Apache Sqoop is a tool that transfers data between Hadoop and relational databases. Many organizations have a significant amount of data stored in relational databases. They may want to take advantage of the benefits offered by Hadoop, such as scalability, fault tolerance, and cost-effectiveness. This text will explore Sqoop and its two modes — Import and Export.</p><h4>Sqoop in one phrase:</h4><blockquote>Sqoop is a tool designed to transfer data between Hadoop and relational databases.</blockquote><p>We can exemplify using Sqoop in a case where a company has their database tables in MySQL, but they decide to migrate their data to a Hadoop environment; in that way, they can use Sqoop to bring this data to HDFS.</p><p>Sqoop has two modes:</p><ul><li>Import</li><li>Export</li></ul><h4>Sqoop Import</h4><p>We use the Sqoop import command to import individual tables from an RDBMS to HDFS. During this process, Sqoop treats each row in a table as a record in HDFS. We can specify whether to store these records as text, sequence file, Avro, or parquet file format. If we do not define it, Sqoop assumes it is a text file.</p><p>The Sqoop import command works by running a MapReduce job. The mappers do the work. Four mappers do the work by default, but we can change this number. The mappers divide the work based on the primary key. If there is no primary key, we change the number of mappers to one or choose another numerical column to split by.</p><p>Whenever we run a Sqoop import with more than one mapper, Sqoop runs a bounding vals query. The query runs on the primary key field to get its min and max values. We can customize this query to run on non-primary keys or remove outliers. Here’s an example:</p><p>Suppose we have an Employee table with emp_id from 0 to 100,000, and we have the default number of mappers. The query finds the max and min emp_id (100,000 and 0, respectively). Then, it defines the split size as (max-min) / number of mappers. In this case, 100,000/4 = 25,000. Each mapper takes care of an interval of 25,000 rows.</p><p>We can store the data differently, depending on the flag we pass on the import command. We use the target dir to specify the absolute path where the data is copied. When we import more than one table, we use the warehouse dir, and Sqoop creates a subdirectory with each table name. Note that we do not recommend using the target directory for production environments. If it exists, it will give us an error. However there is a way to prevent this error, but it is not a good practice. Here’s a code snippet exemplifying what a Sqoop import command with a target-dir flag looks like:</p><pre>sqoop import \<br>--connect CONNECTION_STRING \<br>--username USERNAME \<br>--password PASSWORD \<br>--table TABLE \<br>--as-textfile \<br>--target-dir PATH_TO_DIR</pre><p>If we want to import just part of a table or apply conditions to the import, we can also remove the table flag and add a flag called — query, where we can pass a SQL query.</p><h4>Execution Flow</h4><p>When we run an import, it will run the following flow of tasks:</p><ol><li>Get metadata of the table by running a query</li><li>Build the POJO class with appropriate getters and setters</li><li>Compile the POJO class into a jar file</li><li>Run boundary vals query to get min and max by split column</li><li>Compute split size max — min</li><li>Divide it with numbers of mappers and compute splits</li><li>Submit MapReduce job with a number of mappers</li><li>Each map task will run a select query on the source table with where condition based on the splits to read the data</li><li>Data will be written to the files in the location specified</li></ol><h4>Incremental Import</h4><p>When we want incremental imports, Sqoop offers us a mode to do it. So we will need to pass three more flags:</p><pre>--check-column PRIMARY_KEY \<br>--incremental MODE_OF_INCREMENTAL \<br>--last-value LAST_VALUE \</pre><p>We have two possibilities to specify the incremental mode in Sqoop:</p><ol><li>Append: new rows are continually added with increasing row id values. Sqoop imports all values greater than the last one.</li><li>Last Modified: if we have rows that get updated and a column with the modified timestamp, Sqoop imports rows with a timestamp greater than the last value.</li></ol><h4>How do we Automate?</h4><p>To automate this process, we can use a job in Sqoop that remembers the parameters used to specify a job. We can re-execute the job by invoking it. If a saved job is configured to perform an incremental import, Sqoop updates the state regarding the most recently imported rows in the saved position. It allows the job to import the newest rows continually. This solution solves the manual process issue of keeping track of the last value and supplying it during the next run of the incremental import. Below, I will show how to create a Sqoop job for an incremental append:</p><pre>sqoop job \<br>--create JOBNAME \<br>--import \<br>--connect CONNECTION_STRING \<br>--username USERNAME \<br>--password PASSWORD \<br>--table TABLE \<br>--warehouse-dir PATH_TO_DATA_DIR \<br>--incremental append \<br>--check-column COLLUMN \<br>--last-value 0</pre><p>And to execute it, we run the following:</p><pre>sqoop job --exec JOBNAME</pre><p>As you may have noticed, when we create the job, it has a password flag; it means that every time we run this job, it will ask for the password, but how can we automate even the password typing? We can create a password file running the following command:</p><pre>echo -n PASSWORD &gt;&gt; PATH_TO_PASSWORD_FILE/.password-file</pre><p>After creating a password file, we need to change the job, removing the password flag and adding a new flag called password-file:</p><pre>sqoop job \<br>--create JOBNAME \<br>--import \<br>--connect CONNECTION_STRING \<br>--username USERNAME \<br>--password-file PATH_TO_PASSWORD_FILE \<br>--table TABLE \<br>--warehouse-dir PATH_TO_DATA_DIR \<br>--incremental append \<br>--check-column COLLUMN \<br>--last-value 0</pre><h4>Sqoop Export</h4><p>The Sqoop export command transfers data from HDFS to a relational database. We can use Sqoop export to export data from Hadoop into a relational database or export a MapReduce job’s output to a database. Sqoop export runs a MapReduce job in the background to read data from HDFS and write it to the database.</p><p>We specify the source data in HDFS using the — export-dir flag and provide the connection details of the target RDBMS using the — connect flag. We also need to provide the username and password for the RDBMS using the — username and — password flags, respectively.</p><p>We can specify how the data should be inserted into the target table using the — input-fields-terminated-by and — input-lines-terminated-by flags, which determine the delimiter used between fields and lines in the source data, respectively. We can also specify the table name in the target database using the — table flag.</p><pre>sqoop export \<br>--connect CONNECTION_STRING \<br>--username USERNAME \<br>--password PASSWORD \<br>--table TABLE \<br>--export-dir PATH_TO_DIRECTORY \<br>--fields-terminated-by &#39;END OF FIELD&#39; \<br>--lines-terminated-by &#39;END OF LINE&#39;</pre><h4>Tips and Tricks</h4><p>Sqoop offers a wide range of customizations that can be used for specific cases or configurations. Use the command below to look for extra flags, or read the documentation <a href="https://sqoop.apache.org/">here</a>.</p><pre>sqoop --help</pre><p>The content above is the parts that are the basics of using Sqoop, but feel free to continue advancing your Sqoop study if you like it! I hope to bring more content for you so we can learn together!</p><p>If you find this helpful article, please share it with your friends!</p><p>You can find me on <a href="https://www.linkedin.com/in/abbad-bruno/">LinkedIn</a> ;D</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27c64a06ea4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hadoop Fundamentals]]></title>
            <link>https://medium.com/@abbad/hadoop-fundamentals-b2b584e4b311?source=rss-3e96cf8ac750------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2b584e4b311</guid>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Bruno Abbad]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 13:21:42 GMT</pubDate>
            <atom:updated>2023-03-06T13:21:42.436Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YxBRUnHoGIwt6jAHc4-lqw.jpeg" /><figcaption>Foto de <a href="https://unsplash.com/@tvick?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Taylor Vick</a> na <a href="https://unsplash.com/pt-br/fotografias/M5tzZtFCOfs?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>There are many ways to learn; for me, usually, it works by explaining to people about a topic; Today, I will clarify what I have learned from Sumit Mittal, a well-known content creator of big data topics on LinkedIn and also the founder of <a href="https://trendytech.in/">TrendyTech</a>. This company certificates students that complete their course Big Data Mastering program.</p><h4>Hadoop? What?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9yRCS0_kaT2ZM_A9akVRiQ.png" /></figure><p>When I was starting in the big data universe, one of the most famous words was “Hadoop,” and it is widespread among data practitioners, even with one year of experience or more, to don’t know precisely what is the Hadoop or struggle to answer a simples question: “What is Hadoop?”</p><blockquote>“How do I download Hadoop?” — A friend of mine</blockquote><p>Hadoop is nothing more than a framework to solve big data problems; it is not a thing; it is a bunch of tools and technologies which come together to solve a purpose.</p><p>The three core components of Hadoop, in the most basic way, are:</p><p>YARN: Mainly responsible for resource management</p><p>HDFS: A distributed storage</p><p>MapReduce: Distributed processing | Computer engine (Nowadays, the most famous computing engine is Apache Spark)</p><p>In this article I will cover the HDFS and MapReduce topics.</p><h4>HDFS Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_p22T-28cRnX7sIRJxc3sA.jpeg" /><figcaption>Foto de <a href="https://unsplash.com/@andersjilden?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Anders Jildén</a> na <a href="https://unsplash.com/pt-br/fotografias/Sc5RKXLBjGg?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The first topic covered in the course is how HDFS works on storing files in a distributed way. Thinking about what is the minimum that someone entering the big data universe needs to know about the HDFS and how it works, I simplified it in the following manner:</p><p>The HDFS architecture can be separated into two types of nodes:</p><p>Name nodes that are high-quality hardware</p><p>Data nodes, machines using commodity hardware</p><p>The workflow of communication that differs the type of node and their functions works in the following way:</p><p>The client (us) requests information from the name node, but the name node will not contain the information it selves; it can tell us the address of the data (metadata) that we want; this data is stored in the data nodes, so having the location we can access the data nodes that have the data that we are requesting and get it.</p><p>The name node has high-quality hardware because it is responsible for telling us where the information we want is among a cluster with lots of data nodes. Since the data node will “just” store the data, it must not be a NASA computer.</p><p>Each data node will contain data blocks; the data block is where the data is. The HDFS block size is 128 MB by default, but the HDFS administrator can change it. If we increase the block size, we will have fewer numbers of blocks so that the cluster will use fewer data nodes. Increasing the block size <strong>can</strong> lead to underutilization of the cluster. If we decrease the size of the block, it will lead to a higher amount of metadata which the name node has to handle so that it <strong>can</strong> overburden the name node.</p><p>The data node can hold thousands of blocks, so using by example, if we have four node cluster and we want to store a 1 GB file using the 128 MB default block size, we would have eight 128 MB blocks distributed along the nodes.</p><h4>We Map, We Reduce</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Adu6Sk8oCF2I18OCXibOkQ.jpeg" /><figcaption>Foto de <a href="https://unsplash.com/@olloweb?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Agence Olloweb</a> na <a href="https://unsplash.com/pt-br/fotografias/d9ILr-dbEdg?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The first thing that we should know about MapReduce is that it is no longer necessary in a practical way. Still, the concepts are the fundamentals we must understand when discussing distributed systems in big data.</p><p>MapReduce is a programming paradigm for processing data that resides on many computers. Traditional programming models will work when data is kept on a single machine. Still, when we distribute data on multiple machines, we must use a different programming model to solve our problems.</p><p>Hadoop works on the data locality principle, which means that the data is processed where it is kept, and the code goes to the data, not the data to the code.</p><p>MapReduce has two phases: Map and Reduce, and both phases work only on (key, value) pairs.</p><p>What is a “map”? Map is a code that will run on each data block <strong>parallelly. </strong>The output of the mappers goes to a single machine and then is reduced to generate the final output.</p><p>Since our map phase needs to be in the (key, value) format, the first thing when using the MapReduce that will happen is to convert the data of each line from our input into the format desired, it is taken care of by the system with a tool called Record Reader, and it will read our input and create dummy values for keys and put our values on a tuple. Exemplifying if we have a file with the following data:</p><pre>&quot;hello how are you&quot;<br>&quot;hello world&quot;<br>&quot;hi there&quot;</pre><p>The record reader will output the data in the format below so the Map can understand it:</p><pre>(1,&quot;hello how are you&quot;)<br>(2,&quot;hello world&quot;)<br>(3,&quot;hi there&quot;)</pre><p>Differently from the record reader that the system takes care of, the mapper code must be written by the developer. Since we don’t need the dummy keys created by the record reader, the mapper will ignore the keys and concentrate on the value part.</p><p>The output of the mapper should be in (key, value). After the mapping process, we could expect an output like the one below:</p><pre>(&quot;hello&quot;,1)<br>(&quot;how&quot;,1)<br>(&quot;are&quot;,1)<br>(&quot;you&quot;,1)<br>(&quot;hello&quot;,1)<br>(&quot;world&quot;,1)<br>(&quot;hi&quot;,1)<br>(&quot;there&quot;,1)</pre><p>This output is “shuffled” to the reducer machine; shuffling is nothing more than sending the data from the mapper machine to the reducer machine so the reducer machine gets the data to work.</p><p>When the data gets into the reducer machine, the framework will automatically do the sort phase, making the data look like this:</p><pre>(&quot;are&quot;,{1})<br>(&quot;hello&quot;{1,1})<br>(&quot;hi&quot;,{1})<br>(&quot;how&quot;,{1})<br>(&quot;there&quot;,{1})<br>(&quot;you&quot;,{1})</pre><p>The example above will be the input to the reducer code. The developer writes the reduce logic; in the example of a sum reduce, the result would be:</p><pre>(&quot;are&quot;,1)<br>(&quot;hello&quot;,2)<br>(&quot;hi&quot;,1)<br>(&quot;how&quot;,1)<br>(&quot;there&quot;,1)<br>(&quot;you&quot;,1)</pre><p>When studying this chapter of the course, Sumit Mittal answered some of my questions with the following information:</p><p>The number of mappers is equal to the number of blocks.</p><p>The number of reducers by default is one, but as developers, we can change it, even to zero. Zero reducers are used when we don’t need to aggregate data. We should consider increasing the number of reducers when the bottleneck of the job is on the reducer’s time to complete a job.</p><p>Ideally, we want to make mappers do the heavy part of the work, so in some cases, we can use combiners and partitions (these two I will let you search by yourself ;D) to optimize our logic.</p><p>I presented just a bit of the content on the course; I hope to bring more content for you so we can learn together!</p><p>If you find this helpful article, please share it with your friends!</p><p>You can find me on <a href="https://www.linkedin.com/in/abbad-bruno/">LinkedIn</a> ;D</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2b584e4b311" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My First Year as a Data Scientist]]></title>
            <link>https://medium.com/building-digifarmz/my-first-year-as-a-data-scientist-f3deaec801f2?source=rss-3e96cf8ac750------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3deaec801f2</guid>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Bruno Abbad]]></dc:creator>
            <pubDate>Mon, 04 Apr 2022 18:44:51 GMT</pubDate>
            <atom:updated>2022-04-04T18:44:51.146Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8DGchrL3bjPeStt584ZrGQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@choys_?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Conny Schneider</a> on <a href="https://unsplash.com/s/photos/data-science?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Being in a startup can be a challenging job. Things are fast-paced, the budget can often be limited; for example, we can not use some cloud services that help in numerous ways, so we need to implement some features by ourselves;</p><p>As data scientists, our tasks may be far from the primary data buzzwords that we hear, such as machine learning, IA, deep learning, IoT, etc. In this text, I will bring what my first year as a data scientist in an agriculture startup looked like and what I have learned.</p><h4>The Magic of Web Scrapers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g-S22wCtTutFWucrMyCeWQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@hobijist3d?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">hobijist3d</a> on <a href="https://unsplash.com/s/photos/robot?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>As a data scientist, my first mission was to create web scrapers for sites that provided agriculture data to us. My first attempt was using the Beautiful Soup library, where I found my first trouble: How to deal with the dynamic javascript pages? Since BeautifulSoup does not render the javascript, I needed to try another approach.</p><p>I decided to use the Selenium framework, which initially was made for web testing but can and is used to create web scrapers since it does render the web javascript. After reading the Selenium documentation, a few hours of coding and the data extract algorithm were ready ;). My next step was to improve code quality; a few exceptions were stopping the execution and creating a snapshot of where the code stopped and how to start from that point.</p><p>After doing the first web scrapers, the next ones were way easier; it was the first time that I was coding for a job, and it gave me much more confidence about coding solutions for my problems.</p><h4>SQL is a Must</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eGHkpxzlnzwfR6yBG1JgWw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ikukevk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kevin Ku</a> on <a href="https://unsplash.com/s/photos/database?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>After the scrapers task, it was time to deal with SQL. I have done a lot of SQL queries to answer some questions that other teams had, for example: Where are most of our customers located? How many and who are the clients that we only had their emails as contact information? As a former data analyst, this task was a lot easier for me, I was more used to doing different SQL tasks, but I learned a lot about how our database tables are structured. SQL is one of the most influential hard skills for those starting a data science career since, in different scopes, all data science positions use it.</p><p>I have also taught the basics of SQL to our research team, so they could be less dependent on the data team to give them the answers to a few questions. It was nice to see them performing SQL queries by themselves.</p><h4>Are Data Scientists Dashboarders?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gtJeCka-IbI3z1HfoX8scg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Luke Chesser</a> on <a href="https://unsplash.com/s/photos/data-center?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Some SQL queries were becoming dashboards to aid different teams. I have created a dashboard that shows customers’ distributions weekly in a histogram, how many per week have made a meeting with them, and how many of them have not shown up for our customer success team meetings. This dashboard helps our customer success team’s decision-making and as a metric for their meetings.</p><p>It was significant for my data scientist development since I learned one more data visualization tool, Tableau, which has a different approach from Power BI, a tool I used before.</p><p>In my perception, many companies hire data scientists to do mainly dashboards, and I feel a bit awkward when I see a job opportunity that only focuses on dashboarding. I know that it is essential, the future (and the present) is business intelligence, but a data scientist must not be the dashboard guy.</p><h4>From Google Sheets to Machine Learning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*niOJ2tw5NNHgum9S0CPUbg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@santesson89?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Andrea De Santis</a> on <a href="https://unsplash.com/s/photos/machine-learning?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The subsequent tasks were where I spent most of the year. First, starting with data parser tasks, I need to explain that our R&amp;D team makes our machine learning model inputs. Still, the issue is that they write our inputs in google sheets, where we found some cases like how they format their data, that sometimes are indexed in a complex way to read with Pandas. We needed to do codes that read from these sheets and parse them in a DataFrame that our machine learning could easily read.</p><p>After turning the parsed data into a .csv file, we need to load them into our database, so a data migration is necessary to turn our R&amp;D parsed .csv into a DataFrame that shapes a table of our database with a similar structure. So we sometimes need to do lots of data manipulations to turn the DataFrame into a perfect format to fit the database. Names are turned into foreign keys of other tables and for primary keys of the table that we want to load.</p><p>Combining the parsing and data migration tasks and incorporating the parsing and data migration tasks made me learn and develop my Pandas and data manipulations skills to the point that data manipulation is my better skill nowadays.</p><p>The parsing of Jupyter Notebooks became a lot more functional. It gave us an easier way to retrain our models when our r&amp;d team was testing different numbers in their rationals, so I did a lot of model retraining with new data to validate the curves generated with them.</p><h4>Kedro is Amazing!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8JPDa-JpsOA1HRuteL5p1A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@quinten149?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Quinten de Graaf</a> on <a href="https://unsplash.com/s/photos/pipeline?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Recently our company was accelerated by Google. Our data team has received mentoring from companies like Wildlife, where we were introduced to a framework to create modular data science code using software engineering concepts applied to data science code. I was the one chosen for our first Kedro PoC development to try to automate our parsing and loading tasks. I can already tell you that it was a success! :D</p><p>The most challenging parts were getting used to documentation from an open-source framework created in 2019, so some problems were not in stack overflow (yet, lol). Also, we earn some GCP credits from google, so I was trying to combine lots of new tools to do an ETL pipeline that reads a .csv file from a GCP database instance, parses and models it and then loads into our MySQL database, using a data catalog structure to register the datasets and nodes to register functions in a way that we can use them in pipelines.</p><p>I can tell you the Kedro framework is fantastic; it fits well in the data science pipelines. It feels good to use when you get used to it. The feeling of a job well done was excellent and only motivated me to improve my code and try to do other PoCs with new technologies (I am watching you Streamlit <strong>👀</strong>).</p><h4>My Plans?</h4><p>Data science has many areas of study that can make you feel lost; Understanding software engineering architectures to do more good quality codes, learning technologies related to data engineering and being in touch with the MLOps ecosystem will be my next steps.</p><p>If you find this article useful, please share it with your friends!</p><p>You can find me on <a href="https://www.linkedin.com/in/abbad-bruno/">LinkedIn</a> ;D</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3deaec801f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-digifarmz/my-first-year-as-a-data-scientist-f3deaec801f2">My First Year as a Data Scientist</a> was originally published in <a href="https://medium.com/building-digifarmz">Building DigiFarmz</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>