<?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 Rubens Sôto on Medium]]></title>
        <description><![CDATA[Stories by Rubens Sôto on Medium]]></description>
        <link>https://medium.com/@rubenssoto2005?source=rss-d376d103afbd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*PDsbky_160EgKQ9JdF5zAw.jpeg</url>
            <title>Stories by Rubens Sôto on Medium</title>
            <link>https://medium.com/@rubenssoto2005?source=rss-d376d103afbd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 06:56:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rubenssoto2005/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[Every App Has a Save Button. None of Them Share a Memory.]]></title>
            <link>https://medium.com/@rubenssoto2005/every-app-has-a-save-button-none-of-them-share-a-memory-2a9e654e2dd4?source=rss-d376d103afbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a9e654e2dd4</guid>
            <category><![CDATA[entrepreneurship]]></category>
            <category><![CDATA[bookmarks]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Rubens Sôto]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 20:20:25 GMT</pubDate>
            <atom:updated>2026-07-23T20:20:25.098Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Separate video, discussion, code, article, news, and bookmark cards follow different paths around a person trying to remember where something was saved." src="https://cdn-images-1.medium.com/max/1024/1*Uokx4-_ZRV5bjHnGAzRckA.png" /><figcaption>Image created with an AI image generation tool for this article.</figcaption></figure><p>I usually remembered the idea. What I could not remember was where I had saved it. It might have been a YouTube video in Watch Later, a post bookmarked on X, a Reddit discussion, an article on Medium, a GitHub repository I starred, or a page sitting in my browser bookmarks.</p><p><em>Editorial note: I used an AI writing tool to help draft and edit this article. The experience, opinions, and product decisions are mine.</em></p><p>There was no single dramatic incident that made me build a product. The frustration was smaller and more persistent. I would remember enough to know I had already found something useful, but not enough to retrieve it.</p><p>When no private collection was the obvious place to begin, searching the open web could become the simpler option. That is a strange outcome for something already saved.</p><h3>The convenient choice at save time</h3><p>Using each platform’s save button made sense in the moment.</p><p>If I was watching YouTube, Watch Later was right there. On X, bookmarking a post took one tap. Reddit had its saved list. GitHub had stars. Medium let me save articles without leaving the page. My browser handled everything else.</p><p>Each action was quick. None required me to stop reading, decide on a folder, or write a note.</p><p>The problem appeared later because those choices created separate libraries. Each platform remembered what I had saved inside it. No platform knew about the others.</p><p>I had several ways to save and no reliable place to begin a search.</p><h3>My collection had no catalog</h3><p>The usual advice for bookmark problems is to organize more carefully. Create folders. Add tags. Choose better names.</p><p>That advice assumes you already know which library to open.</p><p>My first question was often more basic. Was the thing I remembered a video, a discussion, an article, or a repository? If I could not answer that, a perfect folder structure inside one platform would not help.</p><p>The details I remembered were rarely the details the software expected. I remembered what the item was about, why it caught my attention, or what I hoped to use it for. I did not necessarily remember its title, creator, platform, or exact words.</p><p>This problem is older than the current set of apps. In an observational study published in 2001, researchers at Microsoft found that people used many methods to keep web information, including bookmarks, email, documents, and local files. The researchers noted that browser bookmarks often lacked two useful things: a reminder and the context that explained why the page mattered. <a href="https://www.microsoft.com/en-us/research/publication/keeping-found-things-found-web/">The study is still worth reading</a>.</p><p>The save buttons improved. The separation remained.</p><h3>Centralizing the links was only half the job</h3><p>Putting every link in one place sounds like the complete answer. It is not.</p><p>A single library can become another quiet pile. If saving is effortless but returning depends on perfect memory and motivation, the same failure moves into a nicer interface.</p><p>Capture had to stay quick. A system that asks for a taxonomy every time I find something useful will eventually be ignored.</p><p>Retrieval had to work with partial memory. I needed to search for the idea I remembered, even when the original title used different words.</p><p>Useful links also needed a way to return without waiting for a search. Some things are forgotten so completely that I never think to look for them.</p><p>Those requirements changed the product I wanted to build. It could not be a storage box with better folders. It needed paths back into the collection.</p><h3>The product requirements came from the failure</h3><p>That is where Nodus Vault started.</p><p>The first requirement was a shared destination for links from different sources. Today, Nodus can capture a page through its Chromium extension, accept a pasted URL, or import a browser bookmarks file. A YouTube video, Reddit post, X post, Medium article, news page, or GitHub repository can live in the same library.</p><p>The second requirement was search based on the saved material, not only the title. The current search can use titles, descriptions, extracted content, notes, tags, sources, and meaning. The point is to let a remembered idea become a useful query.</p><p>The third requirement was a small return path. Nodus has a Daily Check that brings back up to five links for a decision. A link can be read, kept, archived, hidden from future suggestions, or deleted. The limit matters because an endless review queue would reproduce the original problem.</p><p>I did not arrive at these choices by imagining a person with a perfectly maintained knowledge system. I arrived at them by looking at my own behavior. I saved quickly, forgot context, and often could not remember where to search.</p><p>A useful system had to tolerate that behavior before asking me to improve it.</p><h3>What the current product cannot do</h3><p>Centralizing new saves does not automatically recover everything already buried inside private platform accounts.</p><p>Nodus does not silently sync a YouTube Watch Later list, X bookmarks, Reddit saves, Medium reading lists, or GitHub stars. Those platforms have different access rules, exports, and technical limits. The current product works with links that I deliberately capture, paste, or import.</p><p>That creates a real cost. I have to choose which items deserve to leave a platform silo and enter the shared library.</p><p>That cost is not entirely bad. Moving every old save into a new system can create a larger pile without making any of it more useful. A gradual approach is more honest. When an old item becomes relevant again, I can bring it into the library with the context it was missing.</p><p>There are other limits. A saved URL can break. A page can change. A post can be deleted or placed behind a login. A bookmark manager is not the same thing as a permanent archive.</p><p>One library reduces the number of places I need to search. It does not make the web stable.</p><h3>A smaller definition of success</h3><p>A useful system does not need to turn every passing interest into lasting knowledge.</p><p>The goal is narrower. When something matters, I want one place where I can preserve the link, keep enough context to recognize it, search using what I remember, and decide whether it still deserves attention.</p><p>Every platform gave me a convenient way to save for later. The problem was that each one defined “later” inside its own walls.</p><p>I built Nodus Vault to create a path across those walls.</p><p><em>I am the founder of Nodus Vault. The method in this article can be used with any bookmark or personal knowledge tool. If you want to see how I implemented capture, search, and review, you can </em><a href="https://nodusvault.com/?utm_source=medium&amp;utm_medium=article&amp;utm_campaign=founder_story&amp;utm_content=every_app_save_button"><em>visit Nodus Vault</em></a><em>. This link leaves Medium and opens the Nodus Vault website.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a9e654e2dd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Spark: Solutions for Data Skewness in Query Execution]]></title>
            <link>https://towardsdev.com/mastering-spark-solutions-for-data-skewness-in-query-execution-d4152ae62fff?source=rss-d376d103afbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4152ae62fff</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Rubens Sôto]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 12:37:01 GMT</pubDate>
            <atom:updated>2024-08-14T14:58:36.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*Aky562qF5Gy7jbAUERG9iw.jpeg" /></figure><p>The definition of Data Skewness is when a given key is unevenly distributed in a dataset. For example the following transactions table:</p><pre>+----------------+---------+--------+------------------+<br>| transaction_id | user_id | amount | transaction_date |<br>+----------------+---------+--------+------------------+<br>| 1              | 101     | 10     | 2024-08-01       |<br>| 2              | 101     | 15     | 2024-08-01       |<br>| 3              | 102     | 2000   | 2024-08-02       |<br>| 4              | 103     | 3000   | 2024-08-02       |<br>| 5              | 101     | 12     | 2024-08-03       |<br>| 6              | 101     | 8      | 2024-08-03       |<br>| 7              | 104     | 500    | 2024-08-04       |<br>| 8              | 102     | 2500   | 2024-08-04       |<br>| 9              | 101     | 7      | 2024-08-05       |<br>| 10             | 101     | 20     | 2024-08-05       |<br>| 11             | 101     | 5      | 2024-08-06       |<br>| 12             | 105     | 4500   | 2024-08-06       |<br>+----------------+---------+--------+------------------+</pre><p>The user_id 101 has significantly higher number of transactions compared to other users. That situation can lead in performance problems when we are executing Wide operations in spark like JOINS or GROUP BYs, as the data become unevenly distributed across the memory partitions. The partition containing user_id 101 will be much larger, causing an overload on a single node.</p><p>There are several of techniques to solve this problem:</p><h3>Salt</h3><p>This technique involves adding a random value to the key that shows skewness, which helps distribute the data more evenly across the partitions.</p><pre>+----------------+----------------+--------+------------------+<br>| transaction_id | salted_user_id | amount | transaction_date |<br>+----------------+----------------+--------+------------------+<br>| 1              | 101_1          | 10     | 2024-08-01       |<br>| 2              | 101_2          | 15     | 2024-08-01       |<br>| 3              | 102            | 2000   | 2024-08-02       |<br>| 4              | 103            | 3000   | 2024-08-02       |<br>| 5              | 101_1          | 12     | 2024-08-03       |<br>| 6              | 101_3          | 8      | 2024-08-03       |<br>| 7              | 104            | 500    | 2024-08-04       |<br>| 8              | 102            | 2500   | 2024-08-04       |<br>| 9              | 101_2          | 7      | 2024-08-05       |<br>| 10             | 101_1          | 20     | 2024-08-05       |<br>| 11             | 101_3          | 5      | 2024-08-06       |<br>| 12             | 105            | 4500   | 2024-08-06       |<br>+----------------+----------------+--------+------------------+</pre><p>The following code is a good example how to apply in spark:</p><pre>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import col, lit, rand, concat, when, broadcast<br>from pyspark.sql.types import IntegerType<br>from pyspark.sql import functions as F<br><br># Sample DataFrames<br>data1 = [(1, &quot;a&quot;), (1, &quot;b&quot;), (1, &quot;c&quot;), (2, &quot;d&quot;), (3, &quot;e&quot;)]<br>data2 = [(1, &quot;x&quot;), (1, &quot;y&quot;), (1, &quot;z&quot;), (4, &quot;w&quot;), (5, &quot;t&quot;)]<br><br>df1 = spark.createDataFrame(data1, [&quot;key&quot;, &quot;value&quot;])<br>df2 = spark.createDataFrame(data2, [&quot;key&quot;, &quot;value&quot;])<br><br># Identify skewed keys<br>skew_threshold = 2 # Example threshold for skew<br>skewed_keys = df1.groupBy(&quot;key&quot;).count().filter(col(&quot;count&quot;) &gt; skew_threshold).select(&quot;key&quot;).rdd.flatMap(lambda x: x).collect()<br><br>print(&quot;Skewed keys:&quot;, skewed_keys)<br><br>df1_salted = df1.withColumn(<br>&quot;salted_key&quot;,<br>when(col(&quot;key&quot;).isin(skewed_keys), concat(col(&quot;key&quot;), lit(&quot;_&quot;), (rand() * 10).cast(&quot;int&quot;))).otherwise(col(&quot;key&quot;)))<br><br>df1_salted_to_broadcast = df1_salted.filter(col(&quot;key&quot;) == 1)<br><br>df2_salted = df2.join(df1_salted_to_broadcast, on=df2[&quot;key&quot;] == df1_salted_to_broadcast[&quot;key&quot;], how=&quot;left&quot;).select(df2[&quot;key&quot;], df2[&quot;value&quot;], df1_salted_to_broadcast[&quot;salted_key&quot;]).withColumn(&quot;salted_key&quot;,<br>when(col(&quot;salted_key&quot;).isNull(), col(&quot;key&quot;)).otherwise(col(&quot;salted_key&quot;)))<br><br>df2_salted = df2_salted.dropDuplicates([&quot;salted_key&quot;])<br><br>df_final = df2_salted.join(df1_salted, on=df2_salted[&quot;salted_key&quot;] == df1_salted[&quot;salted_key&quot;])<br><br>display(df1_salted)<br>display(df1_salted_to_broadcast)<br>display(df2_salted)<br>display(df_final)</pre><h3>Broadcast JOIN</h3><p>This technique involves broadcasting the smaller dataset to all nodes, allowing Spark to perform the join operation more efficiently and reducing the impact of data skewness.</p><p>This avoids the necessity of shuffling, as the smaller table will be present on all nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*FYBAycZkTFd1CMrfT_tCqw.png" /></figure><pre>from pyspark.sql.functions import broadcast<br><br># Create two sample DataFrames<br># Small DataFrame<br>data_small = [<br>    (1, &quot;A&quot;),<br>    (2, &quot;B&quot;),<br>    (3, &quot;C&quot;)<br>]<br><br># Large DataFrame<br>data_large = [<br>    (1, &quot;X&quot;),<br>    (1, &quot;Y&quot;),<br>    (2, &quot;Z&quot;),<br>    (4, &quot;W&quot;)<br>]<br><br># Define the schema<br>schema_small = [&quot;id&quot;, &quot;value_small&quot;]<br>schema_large = [&quot;id&quot;, &quot;value_large&quot;]<br><br># Create DataFrames<br>df_small = spark.createDataFrame(data_small, schema=schema_small)<br>df_large = spark.createDataFrame(data_large, schema=schema_large)<br><br># Perform a broadcast join<br>df_joined = df_large.join(broadcast(df_small), &quot;id&quot;)<br><br># Show the result<br>df_joined.show()</pre><h3>Spark AQE</h3><p>Adaptive Query Execution (AQE) in Spark is a feature that optimizes query plans while the query is running, using real-time data collected during execution.</p><p>For skewed data, AQE uses Adaptive Skew Join, which finds large partitions and breaks them into smaller ones, distributing the load more evenly across nodes.</p><p>For example, if we consider the transaction and customer tables that we used on the image above, Spark would detect the skew in customer 1’s data in the transaction table and split it into smaller partitions. This way, customer 1’s transaction data is spread more evenly across nodes, reducing the risk of overloading any single node.</p><p>You might wonder what happens with the customer table. There are two possibilities: if the customer table is small enough, Spark might broadcast it to all nodes. Otherwise, it will shuffle the customer table’s data to the nodes where the matching key 1 from the transaction table is located.</p><p>Spark also has a feature that automatically decides whether to broadcast a table or not.</p><p>These are the Spark Configs related to what we’ve talked:</p><pre>spark.conf.set(&quot;spark.sql.adaptive.enabled&quot;, &quot;true&quot;)<br>spark.conf.set(&quot;spark.sql.adaptive.skewJoin.enabled&quot;, &quot;true&quot;)<br>spark.conf.set(&quot;spark.sql.autoBroadcastJoinThreshold&quot;, &quot;10MB&quot;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4152ae62fff" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/mastering-spark-solutions-for-data-skewness-in-query-execution-d4152ae62fff">Mastering Spark: Solutions for Data Skewness in Query Execution</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Engineering Newsletter — Week 1]]></title>
            <link>https://medium.com/@rubenssoto2005/data-engineering-newsletter-week-1-ba8ae57492ac?source=rss-d376d103afbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba8ae57492ac</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[duckdb]]></category>
            <dc:creator><![CDATA[Rubens Sôto]]></dc:creator>
            <pubDate>Sun, 11 Aug 2024 14:04:48 GMT</pubDate>
            <atom:updated>2024-08-11T14:05:24.066Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Engineering Newsletter — Week 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FXq0rgG7A9URDyj9tL52lg.jpeg" /></figure><p>It is not easy to stay updated on everything happening in the data landscape. I maintain a reading routine to keep learning every day. However, I struggle to find the right sources and select the most relevant articles to read, as there is so much great content available online.</p><p>Recently, I started paying more attention to AI and began thinking about how I can avoid the hype and find practical ways it can help me in my daily work life and career.</p><p>I created a project using Crew AI that iterates over a list of quality RSS sources to select the most relevant articles I should read each week. The results were great. My plan is to improve the tool further by adding content from YouTube videos, Reddit posts, and more.</p><p>Each week, I will share the results with you because I want this tool to help you as much as it helps me, and hopefully, you will find it useful too.</p><p>Afterward, I will write an article explaining everything I did and share the code.</p><p>In the ever-evolving world of data engineering, staying updated with the latest trends and technologies is crucial. This week, we’ve curated a selection of insightful articles that dive deep into memory management, performance benchmarking, and the latest tools and techniques in data engineering.</p><p>Whether you’re looking to enhance your skills or stay ahead of the curve, these resources will provide valuable knowledge to keep you informed and inspired. Let’s dive in!</p><ol><li><strong>Title:</strong> Memory Management in DuckDB<br><strong>Link:</strong> <a href="https://duckdb.org/2024/07/09/memory-management.html">https://duckdb.org/2024/07/09/memory-management.html</a><br><strong>Published:</strong> 2024–07–09<br><strong>Summary:</strong> DuckDB effectively utilizes available memory while avoiding out-of-memory errors through its streaming execution engine and buffer manager. The streaming execution engine processes queries in small chunks, reading and processing data one piece at a time. This approach enables larger-than-memory support for simple use cases, but may not be sufficient for complex queries with large intermediates.</li><li><strong>Title:</strong> Benchmarking Ourselves over Time at DuckDB<br><strong>Link:</strong> <a href="https://duckdb.org/2024/06/26/benchmarks-over-time.html">https://duckdb.org/2024/06/26/benchmarks-over-time.html</a><br><strong>Published:</strong> 2024–06–26<br><strong>Summary:</strong> DuckDB has improved its performance by 3–25x and can analyze ~10x larger datasets over the past 3 years. The benchmarking approach focuses on measuring DuckDB’s performance over time, avoiding comparison pitfalls. The results show a significant improvement in performance, with the latest version completing the full benchmark suite in under 35 seconds.</li><li><strong>Title:</strong> Databricks Unity Catalog — Overview<br><strong>Link:</strong> <a href="https://towardsdev.com/databricks-unity-catalog-overview-c6239f6e431c?source=rss-4d13d9b57eb3------2">https://towardsdev.com/databricks-unity-catalog-overview-c6239f6e431c?source=rss-4d13d9b57eb3------2</a><br><strong>Published:</strong> Fri, 19 Jul 2024 13:51:18 GMT<br><strong>Summary:</strong> Databricks’ Unity Catalog is a unified and open governance solution for data that provides a centralized way to manage access, data lineage, and security. It allows multiple workspaces to access a shared data catalog, with features such as access control, row-level security, and data lineage tracking. Unity Catalog provides a layer above workspaces to manage access and permissions, with three types of admins: Account admin, Metastore admin, and Workspace admin.</li><li><strong>Title:</strong> Databricks LakeFlow Overview<br><strong>Link:</strong> <a href="https://towardsdev.com/databricks-lakeflow-overview-381e8e5fe287?source=rss-4d13d9b57eb3------2">https://towardsdev.com/databricks-lakeflow-overview-381e8e5fe287?source=rss-4d13d9b57eb3------2</a><br><strong>Published:</strong> Thu, 11 Jul 2024 16:42:45 GMT<br><strong>Summary:</strong> Databricks LakeFlow is a new solution that simplifies the ETL process for data engineers, allowing them to ingest data from various sources, transform it using SQL and Python, and deploy it in production. LakeFlow Connect provides simple ingestion connectors for databases and enterprise applications, and LakeFlow Pipelines enables users to write plain SQL for batch and streaming transformations. This solution eliminates the need for complex infrastructure setup and allows users to focus on writing valuable transformation SQL queries.</li><li><strong>Title:</strong> The Top 10 Data Lifecycle Problems that Data Engineering Solves<br><strong>Link:</strong> <a href="https://towardsdatascience.com/the-top-10-data-lifecycle-problems-that-data-engineering-solves-7735781959d5?source=rss-e06a48b3dd48------2">https://towardsdatascience.com/the-top-10-data-lifecycle-problems-that-data-engineering-solves-7735781959d5?source=rss-e06a48b3dd48------2</a><br><strong>Published:</strong> Fri, 02 Aug 2024 14:13:25 GMT<br><strong>Summary:</strong> Data engineers face challenges managing huge volumes of diverse data from various sources. Data lifecycle management enables businesses to strategically organize and manage data from creation to destruction. The typical data lifecycle follows an ETL (Extract, Transform, Load) pattern.</li><li><strong>Title:</strong> How Data Engineering Evolved since 2014<br><strong>Link:</strong> <a href="https://towardsdatascience.com/how-data-engineering-evolved-since-2014-9cc85f37fea6?source=rss-e06a48b3dd48------2">https://towardsdatascience.com/how-data-engineering-evolved-since-2014-9cc85f37fea6?source=rss-e06a48b3dd48------2</a><br><strong>Published:</strong> Sat, 27 Jul 2024 15:32:10 GMT<br><strong>Summary:</strong> The data engineering landscape has transformed since 2014, addressing more sophisticated use cases and requirements. Contemporary tools like Airflow, Luigi, and Prefect streamline data engineering processes, enabling robust and scalable data pipelines. A “Cambrian explosion” of ETL frameworks has occurred, with many open-source and Python-based tools emerging.</li><li><strong>Title:</strong> Config-Driven Data Standardization Framework using Spark<br><strong>Link:</strong> <a href="https://medium.com/@pallavisinha12/config-driven-data-standardization-framework-using-spark-12aa7c52fae1?source=rss-5ff3e598a787------2">https://medium.com/@pallavisinha12/config-driven-data-standardization-framework-using-spark-12aa7c52fae1?source=rss-5ff3e598a787------2</a><br><strong>Published:</strong> Fri, 05 Jul 2024 05:18:46 GMT<br><strong>Summary:</strong> Data standardization is crucial for transforming raw data from diverse sources into a common format, ensuring consistency, reducing errors, and enhancing usability. A config-driven approach to data standardization uses configuration files to define rules and mappings, decoupling standardization logic from application code. This approach offers flexibility, scalability, and maintainability, making it ideal for handling large datasets and simplifying maintenance and updates.</li><li><strong>Title:</strong> Data Contracts in Action: Testing<br><strong>Link:</strong> <a href="https://medium.com/@pflooky/data-contracts-in-action-testing-111631338657?source=rss-b471ef59a5e0------2">https://medium.com/@pflooky/data-contracts-in-action-testing-111631338657?source=rss-b471ef59a5e0------2</a><br><strong>Published:</strong> Wed, 17 Jul 2024 06:48:29 GMT<br><strong>Summary:</strong> Data contracts are agreements between data producers and consumers that outline data source, schema, ownership, and quality expectations. The Open Data Contract Standard aims to standardize data contracts for a common understanding and simplified data flows. Data contracts are applied in data pipelines to ensure data integrity and quality.</li><li><strong>Title:</strong> Why use Apache Airflow (or any orchestrator)?<br><strong>Link:</strong> <a href="https://www.startdataengineering.com/post/why-to-use-orchestrators/">https://www.startdataengineering.com/post/why-to-use-orchestrators/</a><br><strong>Published:</strong> Mon, 24 Jun 2024 10:45:36 -0400<br><strong>Summary:</strong> Apache Airflow is a system used to run complex data pipelines, providing features such as scheduling, orchestration, and observability. It enables data engineers to define the order of execution of pipeline tasks using Directed Acyclic Graphs (DAGs) and schedule pipelines to run at specified frequencies. Airflow also provides observability features, including logs and metadata, to monitor pipeline performance and execution.</li><li><strong>Title:</strong> How to implement data quality checks with greatexpectations<br><strong>Link:</strong> <a href="https://www.startdataengineering.com/post/implement_data_quality_with_great_expectations/">https://www.startdataengineering.com/post/implement_data_quality_with_great_expectations/</a><br><strong>Published:</strong> Fri, 26 Jul 2024 16:19:00 -0400<br><strong>Summary:</strong> The greatexpectations library is a popular tool for implementing data quality checks in production pipelines. It follows the Write-Audit-Publish (WAP) pattern, which involves checking data before making it available to end-users. The library allows users to define expectations, run validations, and store results to identify patterns and improve data quality.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba8ae57492ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Personal Thoughts About the Present and Future of AI]]></title>
            <link>https://medium.com/@rubenssoto2005/my-personal-thoughts-about-the-present-and-future-of-ai-101ee229c1fa?source=rss-d376d103afbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/101ee229c1fa</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Rubens Sôto]]></dc:creator>
            <pubDate>Wed, 15 May 2024 12:50:27 GMT</pubDate>
            <atom:updated>2024-05-15T12:50:54.972Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WK5PMqe_hS4RDMRy1A-bZA.jpeg" /></figure><p>AI is a highly discussed topic, people are constantly engaging in conversations about it. While some are dedicated to creating valuable content discussing current use cases and limitations of large language models, others exploit the hype to profit from potentially unnecessary courses, causing unnecessary panic and fear. I’m tired of the number of YouTube videos that I’ve been speculating about which jobs will disappear shortly.</p><p>My intention here is to focus on the positive aspects and potential use cases of AI, both now and in the future, while also acknowledging the need for caution. In my view, one of the most fundamental benefits of AI is its ability to enhance productivity. This means that we will be able to accomplish more tasks and generate more output within the same amount of time. This increase in productivity will benefit a wide range of industries, from traditional law firms and accounting offices to large-scale manufacturers. Ultimately, this is expected to lead to more affordable products and higher salaries.</p><p>However, what excites me the most are the significant advancements AI could bring to fields such as science and medicine. Imagine spending significantly less time discovering new drug candidates, developing new treatments, and finding cures for diseases. The potential for progress in these areas is truly remarkable.</p><p>While I’ve focused on the positive aspects of AI, it’s essential to address the question of how these advancements will be achieved. I won’t delve into specific features of chatbots; instead, I’ll discuss AI at a higher level. AI has the potential to assist us in various tasks, such as translating text, answering questions, facilitating learning, generating code, debugging, organizing ideas, and much more. Additionally, AI can be trained with specific data sets, enabling it to provide insights into internal knowledge.</p><p>In the realm of science, AI can simulate drug reactions with our body cells, allowing researchers to select the most promising substances and avoid wasting time on ineffective ones. It can also analyze image tests like tomography, detecting patterns that may be imperceptible to the human eye. Projects like Google’s AlphaFold, which predicts protein structures based on amino acid sequences, demonstrate the rapid progress being made in the field of science and medicine.</p><p>Despite the numerous benefits, I do have some concerns. It’s challenging to predict the economic impacts of these new technologies, and while I don’t subscribe to the panic surrounding job loss, it’s undeniable that some roles may evolve or become obsolete. It’s crucial to remember that AI doesn’t create anything; it simply identifies patterns in the knowledge we provide. As such, there will be challenges ahead, and it’s essential for us to remain informed and adaptable to navigate the changes effectively.</p><p>If you’ve read this far, thank you. I’m eager to hear your thoughts on the topic. Do you agree or disagree with my perspective? What future do you envision for our society? Let’s continue the conversation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=101ee229c1fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Concurrency Problems in Databricks (Delta Lake)]]></title>
            <link>https://medium.com/@rubenssoto2005/handling-concurrency-problems-in-databricks-delta-lake-72d4b7948e7a?source=rss-d376d103afbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/72d4b7948e7a</guid>
            <category><![CDATA[databricks-delta-lake]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[delta-lake]]></category>
            <dc:creator><![CDATA[Rubens Sôto]]></dc:creator>
            <pubDate>Fri, 29 Dec 2023 19:26:34 GMT</pubDate>
            <atom:updated>2023-12-29T19:26:56.482Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey Guys,</p><p>Today we will discuss a problem that I recently encountered at my work with Delta Lake(Databricks), a problem you may have already faced. There were twenty sources from different countries and our goal is to put all this data in the same table. To make the process faster, the countries are processed concurrently; in other words, more than one country is processed at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z2yhia9w-0R_k1Cun-Y6Vg.png" /></figure><p>Our source could have some duplicates and updates, to avoid them, in the write part we used merge with insert and update.</p><p>When you have two writers trying to update data that is located in the same target files, we have a conflict, a concurrency problem. Before deep diving into the solution I will explain a little about Isolation levels on Delta lake.</p><h3>Understanding the Isolation Levels On DataBricks</h3><p>Databricks uses delta lake by default, which offers us ACID guarantees, but what does it mean?</p><p>Atomicity: All transactions will succeed or fail completely, it means your readers will never read a partial write.</p><p>Consistency: It means how the data state is observed by simultaneous operations. In simpler words, if I have for example two merge operations occurring at the same time on the same portion of data, databricks will emit an exception because a conflict occurred and this way the consistency is guaranteed between writes by default.</p><p>Isolation: Guarantees the Isolation between table operations, by default Databricks uses Write Serializable Isolation Levels on the write operations and Snapshot Isolation on the reads.</p><p>Durability: Means the committed changes are permanent.</p><p>After this explanation, let’s talk about isolation levels, Databricks has two types:</p><p>Serializable: This is the strongest isolation level and it ensures that all table operations(reads and writes) are executed in a specific order, the same order as you see in the table history. Each operation is executed one by one.</p><p>Write Serializable: It’s the default isolation level and it ensures that only the write operations are serializable, but, the content of the delta table could be different that is expected when you see the order of operations in table history and it happens because this type of isolation allows some types of concurrency.</p><p>If you want to change the isolation level it is simple as this:</p><p>ALTER TABLE &lt;table-name&gt; SET TBLPROPERTIES (‘delta.isolationLevel’ = ‘WriteSerializable’)</p><h3>The Solution: Partition or Retry Logic</h3><p>In our case, each writer was processing data from a different country, which made a lot of sense for us to partition the table by country. When we do that, it ensures that each writer is writing the data in a different partition and it avoids any conflict problem.</p><p>Another information that is very important to add is: our writers are running inside the same cluster, we used python threads to do that which was another reason to use the partition solution, it is a much simpler way to manage the writer’s conflict.</p><p>If creating a partition doesn’t make sense for your situation, another way that you can solve this problem is by creating retry logic, when one of the conflicts exceptions occurs you can implement a sleep time to try to write again. I found a very good code to do that in this article:</p><p><a href="https://medium.com/p/efbafb9ea95d">https://medium.com/p/efbafb9ea95d</a></p><pre>from datetime import datetime<br>from time import sleep<br>from delta.exceptions import (<br>    ConcurrentAppendException,<br>    ConcurrentDeleteReadException,<br>    ConcurrentDeleteDeleteException,<br>)<br>import math<br><br><br>def streaming_write_with_concurrent_retry(<br>    stream, max_attempts=3, indefinite=False, table=None, path=None<br>):<br>    &quot;&quot;&quot;<br>    Handles concurrent write operations to a Delta table or path by retrying the operation<br>    in case of specific concurrent exceptions.<br><br>    :param stream: The data stream to be written.<br>    :param max_attempts: The maximum number of retry attempts. Default is 3.<br>    :param indefinite: If True, will keep retrying indefinitely. Default is False.<br>    :param table: The Delta table to write to.<br>    :param path: The path to write to.<br>    :return: The result of writer.awaitTermination().<br>    &quot;&quot;&quot;<br><br>    attempt = 0  # Initialize attempt counter<br><br>    while True:<br>        try:<br>            # Choose the writer based on whether table or path is provided<br>            if table:<br>                writer = stream.table(table)<br>            elif path:<br>                writer = stream.start(path)<br>            else:<br>                writer = stream.start()<br><br>            # Attempt to write and wait for termination<br>            return writer.awaitTermination()<br><br>        # Handle concurrent exceptions<br>        except (<br>            ConcurrentAppendException,<br>            ConcurrentDeleteReadException,<br>            ConcurrentDeleteDeleteException,<br>        ) as e:<br><br>            # Increment attempt counter<br>            attempt += 1<br><br>            # If indefinite is False and attempts have reached max_attempts, raise the exception<br>            if not indefinite and attempt &gt;= max_attempts:<br>                raise e from None<br><br>            # Calculate sleep time using exponential backoff strategy<br>            sleep_time = min(120, math.pow(2, attempt))<br><br>            # Sleep for the calculated time before retrying<br>            sleep(sleep_time)</pre><p>Databricks 14.2 has a new feature to manage concurrency at the row level and probably it will make our lives easier, but I didn’t test it yet, so, that’s for another article.</p><p>Thank you so much for reading this article so far. Have you had this concurrency problem before? How did you solve it?</p><p>Sources: <br><a href="https://docs.databricks.com/en/optimizations/isolation-level.html#isolation-levels">https://docs.databricks.com/en/optimizations/isolation-level.html#isolation-levels</a><br><a href="https://medium.com/p/efbafb9ea95d">https://medium.com/p/efbafb9ea95d</a><br><a href="https://docs.databricks.com/en/lakehouse/acid.html">https://docs.databricks.com/en/lakehouse/acid.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72d4b7948e7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streaming de dados com Kinesis Stream e Kinesis Firehose]]></title>
            <link>https://medium.com/data-hackers/streaming-de-dados-com-kinesis-stream-e-kinesis-firehose-27a7e10c379?source=rss-d376d103afbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/27a7e10c379</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[kinesis]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Rubens Sôto]]></dc:creator>
            <pubDate>Sun, 10 May 2020 17:35:15 GMT</pubDate>
            <atom:updated>2020-05-10T17:35:15.237Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*9Q4QRfURv5ZLcAGdquwJlQ.png" /></figure><p>Nos últimos dias venho estudando bastante a respeito da AWS e acho que a melhor forma de fixar o que eu aprendi e também me aprofundar mais, é escrevendo.</p><p>Hoje foi dia de aprender sobre Streaming na AWS, utilizei duas ferramentas: o Kinesis Stream que é um serviço de fila altamente escalável, com alto throughput, podendo receber uma imensa quantidade de dados por segundo e o Kinesis Firehose que facilita muito a vida quando queremos carregar os dados de streaming, por exemplo, em um data lake.</p><h3>Guia Passo a Passo de Como Configurar um Streaming de Dados para o S3 na AWS</h3><h3>Arquitetura</h3><p>Nossa arquitetura vai ser algo bem simples, a nossa ideia, é que temos uma aplicação que envia dados para um Kinesis Stream e nós queremos que esses dados fiquem disponíveis no nosso data lake, que será um AWS S3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZRaYsU_LE8xTwXignjr4nw.jpeg" /><figcaption>Arquitetura</figcaption></figure><h3>Criando o Data Lake</h3><p>A partir de agora eu vou levar em consideração que você já tem uma conta na AWS(da pra usar de graça).</p><p><em>Pagina Oficial do AWS S3:</em> <a href="https://aws.amazon.com/pt/s3/">https://aws.amazon.com/pt/s3/</a></p><p>Após logar no console vamos procurar pelo serviço S3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aG-_9B8bCgd_NOgRdBtpeQ.png" /><figcaption>Criação do Data Lake no S3</figcaption></figure><p>No lado superior direito, tem uma botão laranja “Create Bucket”, clica nele, seremos enviados para a tela a seguir:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*1vgS9u5Oc9z-0nPVX127YA.png" /></figure><p>Vamos dar um nome para o nosso bucket e escolher a região que ele ficará localizado, vou utilizar us-east-1, é a região que normalmente tem todos os produtos da AWS e também os mais atualizados.</p><p><em>Obs: Só para lembrar, o nome do bucket tem que ser único globalmente, então não adiantar colocar “teste” ou coisas do gênero, provavelmente alguém já esta usando.</em></p><p>As demais opções, deixa como esta, não queremos que nosso data lake tenha acesso externo, só clicar em “Create Bucket” e ser feliz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAKUoFUgfw6iHJ_CvgPO_w.png" /></figure><h3>Criando o Kinesis Stream</h3><p>Vamos criar nosso Stream, ele que vai receber a massa de dados que iremos gerar com uma aplicação em python.</p><p>Pagina Oficial do AWS Kinesis Stream: <a href="https://aws.amazon.com/pt/kinesis/data-streams/">https://aws.amazon.com/pt/kinesis/data-streams/</a></p><p>No console da AWS, procure por <strong>Kinesis</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pS-PYzlMKb4PDLzPMteAOw.png" /></figure><p>Se você não tem nenhum serviço do Kinesis habilitado, você provavelmente irá se deparar com a tela abaixo, só clicar em “<strong>Get started</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Td_zARZC11X0EJT5Exouzg.png" /></figure><p>O Kinesis oferece alguns tipos de serviços, hoje nós iremos utilizar o Kinesis Stream e o Firehose, mas agora, clica em “<strong>Create data stream</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*dTbOdN7ybefVbtBqntjtMA.png" /></figure><p>Agora também é bem simples, vamos dar um nome para o nosso Stream, o meu vai se chamar “<strong>kinesis_streamrs</strong>”. Também vamos configurar o número de Shards, para os nossos testes 1 shard já é mais do que o suficiente.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*_wDz29ypxxeUJtxhoU2xPQ.png" /></figure><p>Clica em “<strong>Create Kinesis stream</strong>” e pronto, Stream criado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lkWHZP9aGS8eSDegnPsaYg.png" /></figure><h3>Criando o Kinesis Firehose</h3><p>Já temos o Stream pronto para receber os dados, temos o data lake também para armazenar, falta só o cara que irá jogar os dados do Stream para o S3.</p><p>Pagina Oficial do AWS Kinesis Firehose: <a href="https://aws.amazon.com/pt/kinesis/data-firehose/">https://aws.amazon.com/pt/kinesis/data-firehose/</a></p><p>Clica no nome do seu stream, na tela seguinte, canto superior esquerdo, clique em “<strong>Connect Kinesis consumers</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X05ou5hnQS9TbIhZLKVBEw.png" /></figure><p>Na tela que vai aparecer, clica em “<strong>Connect to delivery stream</strong>”, a partir dai vamos começar a configurar o Firehose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*MUG66JVrzrKEM1pPnIcMJA.png" /></figure><p>Vamos dar uma nome para esse cara, e deixar marcado o source como “<strong>Kinesis Data Stream</strong>”, só não alterar nada, essa parte ele já pega sozinho.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*I37UIkDLc7FQ7Ehlqzmlgw.png" /></figure><p>Clicando em <strong>Next</strong>, na próxima tela algumas opções são apresentadas: com o Firehose é possível chamar uma Lambda para fazer algumas transformações nos dados e também alterar o formato do arquivo que será gravado no S3. Por hoje, vamos deixar tudo como esta e clicar em <strong>Next</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EfjbR1dBhNAX7PyoSPC9Zw.png" /></figure><p>Chegou a hora de escolher o destino dos nossos dados, tem algumas opções bem legais, como Redshift, Elasticsearch e o Splunk, mas hoje vamos jogar tudo direto no S3.</p><p>Abaixo, <strong>escolha o nome do nosso bucket</strong> e depois <strong>Next</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*S4FN6nSQeiLfMDI-gZAPgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*DwzGh9jFyAkULyYgGwXwRA.png" /></figure><p>O Firehose te da algumas opções para saber quanto tempo que os dados serão armazenados no buffer, antes de serem gravados no s3.</p><p><strong>Vamos deixar as seguintes configurações:</strong><br>Buffer Size: 5MB<br>Buffer Interval: 300</p><p>Falando de forma bem clara, se o tamanho do Buffer chegar a 5MB, o Firehose vai e grava um arquivo ou se passarem 300 segundos, ele faz a mesma coisa, nesse caso, é o que ocorrer primeiro.</p><p><strong>As demais opções, vou deixar tudo como padrão.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*_J_VdT5iTB_iRglpp2k50g.png" /></figure><p>Lá no final da tela em “<strong>Permissions</strong>” ele esta pedindo uma “<strong>IAM Role</strong>”, que nada mais é uma permissão para o Kinesis Firehose escrever no S3 e também ler dados do Stream.<br>Clica em “<strong>Create new or choose</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*4fb9q7ogOJsS5JRIKKVTKg.png" /></figure><p>Na tela a seguir, só dar um nome para sua IAM Role e clicar em <strong>ALLOW</strong>.</p><p><em>Obs: Em um ambiente produtivo, essas permissões teriam de ser analisadas como muito mais carinho, mas como aqui é teste, segue o jogo!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*Gf8MmPV5zolm6bX-qZMtZw.png" /></figure><p>Ele vai voltar para a nossa tela de configuração, já com a Role selecionada, só clicar em <strong>Next</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*APXnacpOIr1iCL5ANqcx6Q.png" /></figure><p>Na última tela, só clicar em “<strong>Create delivery stream</strong>” e pronto, todos os nossos recursos finalmente estão criados!!!!</p><h3>Enviando Dados para o Stream</h3><p><em>Agora chegou a hora da verdade!!!</em> Vamos ver se esse monte de configurações funcionam mesmo.</p><p>Eu fiz uma pequena aplicação em python para enviar dados de um arquivo csv para o Kinesis Stream. A aplicação envia dados em batchs de 500 em 500 linhas ou até o Batch atingir o tamanho de 800Kb, isso tudo é para respeitar os limites do Stream e não ocorrerem erros.</p><p>Em 5 minutos consegui enviar, a partir da minha máquina, 212.000 eventos, uma performance bastante interessante, 706 eventos por segundo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*3QT6lfMYxfLltos9EW0RQA.png" /></figure><p>Olhando os dados de monitoramento do Kinesis Stream, da para ver algumas coisas interessantes, como a quantidade de bytes ingeridos, latência, eventos ingeridos e por último se houve algum erro por Throughput excedido.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_9SO4hX1ILqTeOJeN9NfIw.png" /></figure><p>No Firehose conseguimos ver as mesmas coisas, no caso abaixo a quantidade de registros lidos do Stream e também a quantidade de Bytes lidos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*IGOb8gp_bRKIQHmjSpTApQ.png" /></figure><p>Por último, mas não menos importante, será que os arquivos foram criados no S3? Vamos lá dar uma olhada.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w2N6K79InPjf5X29X90XEw.png" /></figure><p>Missão dada é missão cumprida rs…Arquivos Criados!</p><p>O código da aplicação esta no GitHub: <a href="https://github.com/rubenssoto/kinesis_producer">https://github.com/rubenssoto/kinesis_producer</a></p><h3>Conclusão</h3><p>Ao final de todos os passos, conseguimos criar um streaming de dados em realtime tendo o S3 como destino.</p><p>Após os dados estarem no S3, o céu é o limite, podemos usar o Spark para processar os dados e jogar no Redshift ou dar acesso a um equipe de ciência de dados para realizar a exploração.</p><p>Estou totalmente aberto a dúvidas e também a sugestões, todos estamos aqui para aprender, muito obrigado por ter lido até aqui!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27a7e10c379" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-hackers/streaming-de-dados-com-kinesis-stream-e-kinesis-firehose-27a7e10c379">Streaming de dados com Kinesis Stream e Kinesis Firehose</a> was originally published in <a href="https://medium.com/data-hackers">Data Hackers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encapsulando Transformações em DataFrames com Pyspark]]></title>
            <link>https://medium.com/data-hackers/encapsulando-transforma%C3%A7%C3%B5es-em-dataframes-com-pyspark-9543e0cc69f1?source=rss-d376d103afbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/9543e0cc69f1</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Rubens Sôto]]></dc:creator>
            <pubDate>Sat, 18 Apr 2020 22:13:31 GMT</pubDate>
            <atom:updated>2020-06-24T01:35:57.855Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*9xn-LVhDUz0ZuI1OoCKqEw.png" /></figure><p>Hoje iremos realizar algumas transformações simples em um dataframe e veremos uma forma de deixar nosso código muito mais legível.</p><p>Considerando que você esta em ambiente com Spark configurado, vamos criar a sessão para começar nossas transformações:</p><blockquote>from pyspark.sql import SparkSession<br><br>spark = SparkSession.builder.appName(&#39;EtlCovid&#39;).getOrCreate()</blockquote><p>Sessão criada, vamos importar nosso data source para um Spark Dataframe.</p><blockquote>df = spark.read.csv(&#39;us-counties.txt&#39;, header = True)</blockquote><h3>Criando Funções de Transformação</h3><p>Nós vamos criar 3 funções simples, a primeira irá adicionar um campo fictício ao dataframe.</p><blockquote>def add_column(df):<br> <br> return df.withColumn(&#39;Contry&#39;, lit(&#39;USA&#39;))</blockquote><p>A segunda irá filtrar o dataframe.</p><blockquote>def filter_state(df):<br> return df.where(col(&#39;state&#39;) == &#39;Washington&#39;)</blockquote><p>Nossa última função, irá agrupar nosso dataframe por dia.</p><blockquote>def group_by_date(df):<br> return df.groupBy(&#39;date&#39;, &#39;Contry&#39;).agg(sum(&#39;cases&#39;).alias(&#39;Cases&#39;), sum(&#39;deaths&#39;).alias(&#39;Deaths&#39;))</blockquote><h3>Utilizando Nossas Funções — Forma 1</h3><p>Nossas funções estão criadas, agora vamos aplicar ao nosso dataframe “df” que foi criado lá em cima.</p><blockquote>df1 = add_column(df)<br><br>df2 = filter_state(df1)<br><br>df3 = group_by_date(df2)</blockquote><p>Será que funcionou? Vamos dar uma olhada no dataframe final o “df3”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*Orup_Jsl8m_NXsClBKlHmQ.png" /><figcaption>Resultado do método show()</figcaption></figure><p>Maravilha!!!!! Todas as nossas transformações funcionaram, tudo certo então? Claro que não!</p><p>Vocês conseguem perceber como o nosso código esta feio? df1, df2, df3…Imagina se fossem 10 transformações, mesmo se você fosse a pessoa mais criativa do mundo em criar nomes, ia ficar uma confusão.</p><p>Será que tem um jeito melhor de fazer isso? Claro que tem!!!</p><h3>Utilizando Nossas Funções — Forma 2</h3><p>Temos que conseguir um jeito, que não seja necessário em cada transformação, ter que criar um novo dataframe.</p><p>Vamos criar uma função para nos ajudar nessa tarefa.</p><blockquote>from pyspark.sql.dataframe import DataFrame</blockquote><blockquote>def transform(self, function):<br> return function(self)</blockquote><blockquote>DataFrame.transform = transform</blockquote><p>A função recebe dois parâmetros, self e function, self será o próprio dataframe a quem estamos querendo realizar a transformação e function, será a função que fará a transformação.</p><p>Agora o nosso código ficará:</p><blockquote>df_transformed = df.transform(add_column)\<br> .transform(filter_state)\<br> .transform(group_by_date)</blockquote><p>Ficou bem mais simples né?? Se o número de transformações crescer, nosso código ficará muito mais simples e organizado.</p><p>O que vocês acharam de realizar as transformações dessa forma? Comentem ai!!</p><p><a href="https://www.linkedin.com/in/rubens-s%C3%B4to">Clique Aqui para Acessar meu Linkedin</a></p><p>Fonte: <a href="https://mungingdata.com/pyspark/chaining-dataframe-transformations/">https://mungingdata.com/pyspark/chaining-dataframe-transformations/</a></p><p>Imagem Docker Utilizada nos Testes: <a href="https://hub.docker.com/r/jupyter/all-spark-notebook/">https://hub.docker.com/r/jupyter/all-spark-notebook/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9543e0cc69f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-hackers/encapsulando-transforma%C3%A7%C3%B5es-em-dataframes-com-pyspark-9543e0cc69f1">Encapsulando Transformações em DataFrames com Pyspark</a> was originally published in <a href="https://medium.com/data-hackers">Data Hackers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>