<?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 Dhanashri Saner  on Medium]]></title>
        <description><![CDATA[Stories by Dhanashri Saner  on Medium]]></description>
        <link>https://medium.com/@dhanashrisaner.30?source=rss-3cb99fed30cb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*E80IkA9x0xTAnh44UVB_9Q.jpeg</url>
            <title>Stories by Dhanashri Saner  on Medium</title>
            <link>https://medium.com/@dhanashrisaner.30?source=rss-3cb99fed30cb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:33:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dhanashrisaner.30/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[Connecting Python to Snowflake: A Practical Guide]]></title>
            <link>https://medium.com/@dhanashrisaner.30/connecting-python-to-snowflake-a-practical-guide-5f0243b580de?source=rss-3cb99fed30cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f0243b580de</guid>
            <category><![CDATA[snowflake-connector]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[connection]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Dhanashri Saner ]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 15:05:01 GMT</pubDate>
            <atom:updated>2024-12-03T16:00:40.651Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*77Xhr7kfnIGUe36iiXnZKg.jpeg" /></figure><h3>Introduction</h3><p>Snowflake is a popular cloud-based platform for storing and analyzing data. Many developers and analysts use it because it’s fast, easy to scale, and works well with different tools. If you’re a Python developer, connecting your Python application to Snowflake can help you easily access and work with data for Machine Learning (ML) or data analysis tasks.</p><h3>Need for Establishing a Snowflake Connection with Python</h3><p>Python is widely used for ML and data analysis because of its powerful libraries like Pandas, Scikit-learn, and TensorFlow. However, raw data for these tasks often lives in databases like Snowflake. By connecting Python to Snowflake, you can:</p><ul><li><strong>Access large datasets</strong> stored in Snowflake directly from your Python scripts.</li><li><strong>Transform and clean data</strong> efficiently before feeding it into ML models.</li><li><strong>Run analytics</strong> on real-time or historical data without downloading huge files.</li></ul><h3>Step 1: Setting Up the Connection</h3><p>To connect Python with Snowflake, follow these steps:</p><h4>1. Install Required Libraries</h4><p>Install the snowflake-connector-python package, which helps Python interact with Snowflake. Open your terminal and run:</p><pre>pip install snowflake-connector-python</pre><h4>2. Get Your Snowflake Credentials</h4><p>You’ll need:</p><ul><li><strong>Account Identifier</strong>: Found in your Snowflake URL (e.g., abc123.us-east-1.snowflakecomputing.com).</li><li><strong>Username and Password</strong>: Provided by your Snowflake admin.</li><li><strong>Database, Schema, and Table Names</strong>: Where your data is stored.</li></ul><h4>3. Configure Snowflake Connection</h4><p>Create a Python script to define your Snowflake connection:</p><pre>import snowflake.connector<br><br># Create a connection to Snowflake<br>conn = snowflake.connector.connect(<br>    user=&#39;your_username&#39;,<br>    password=&#39;your_password&#39;,<br>    account=&#39;your_account_identifier&#39;<br>)<br>print(&quot;Connection successful!&quot;)<br># Create a cursor object to execute SQL queries<br>cursor = conn.cursor()</pre><p><strong>Sample Script:</strong></p><pre>import snowflake.connector<br>import os<br><br>try:<br>    # Establish the connection<br>    connection = snowflake.connector.connect(<br>        user=&#39;abc123&#39;,                # Replace with your Snowflake username<br>        password=&#39;Abc@123$*&#39;,          # Replace with your Snowflake password<br>        account=&#39;pogyowt-gr10141&#39;,   # Replace with your Snowflake account identifier<br>        warehouse=&#39;COMPUTE-WH&#39;,      # Replace with Virtual warehouse<br>        role=&#39;ACCOUNTADMIN&#39;         # Role with necessary permissions<br>    )<br>    print(&quot;Connection successful!&quot;)<br><br>    # Create a cursor object<br>    cursor = connection.cursor()<br><br>    # Execute the query to show databases<br>    cursor.execute(&quot;SHOW DATABASES&quot;)<br><br>    # Fetch and display the results<br>    databases = cursor.fetchall()<br>    print(&quot;List of Databases:&quot;)<br>    for db in databases:<br>        print(db[1])  # The second column typically contains the database name<br><br>except Exception as e:<br>    print(f&quot;Error: {e}&quot;)</pre><p><strong>Note:</strong></p><p>You can locate your account by checking your Snowflake account URL (e.g., <a href="https://pogyowt-gr10141.snowflakecomputing.com)./">https://pogyowt-gr10141.snowflakecomputing.com).</a></p><p>Sample Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*J1-VZenK9g58XHQzvDYWhg.png" /></figure><h3>Step 2: Read Data from Snowflake’s Default ORDERS Table</h3><p>Snowflake provides a sample database called SNOWFLAKE_SAMPLE_DATA. Inside this database, the TPCH_SF1 schema contains a table called <strong>ORDERS</strong>. We’ll use this table for practice.</p><p><strong>1. Write and Execute a Query</strong></p><p>To retrieve data, write a SQL query and execute it using the Snowflake cursor:</p><pre># SQL query to select data from the ORDERS table<br>query = &quot;SELECT * FROM SNOWFLAKE_SAMPLE_DATA.TPCH_SF1.ORDERS LIMIT 10;&quot;<br>cursor.execute(query)<br><br># Fetch the results<br>rows = cursor.fetchall()<br><br># Display the results<br>for row in rows:<br>    print(row)</pre><h4>Output:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*VHP2vJYKybrUconkayRDVw.png" /></figure><p><strong>2. Convert Data to Pandas DataFrame</strong></p><p>For easier manipulation and analysis, load the data into a Pandas DataFrame:</p><pre>import pandas as pd<br><br># Load data into a Pandas DataFrame<br>df = pd.DataFrame(rows, columns=[desc[0] for desc in cursor.description])<br><br># Display the first few rows<br>df.head()</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*0KyxALcYQfybU_WE0w2bNg.png" /></figure><p>Now you can explore the <strong>ORDERS</strong> table, which includes fields like:</p><ul><li><strong>O_ORDERKEY</strong>: Order ID.</li><li><strong>O_CUSTKEY</strong>: Customer ID.</li><li><strong>O_ORDERSTATUS</strong>: Order status.</li><li><strong>O_TOTALPRICE</strong>: Total price of the order.</li><li><strong>O_ORDERDATE</strong>: The date the order was placed.</li></ul><h4>3. Basic Data Exploration (optional)</h4><p>Let’s do some basic data exploration techniques to understand the dataset&#39;s structure.</p><pre># Display the first few rows of the DataFrame<br>print(&#39;First Five Records:\n\n&#39;,df.head())<br><br># Check the data types of each column<br>print(&#39;\n\nData type of each columns:&#39;,df.dtypes)<br><br># Get summary statistics of numerical columns<br>print(&#39;\n\nGet summary statistics of numerical columns&#39;,df.describe())<br><br># Check for any missing values in the DataFrame<br>print(&#39;\n\nCheck for any missing values in the DataFrame&#39;,df.isnull().sum())</pre><h4>4. Basic Data Visualization</h4><p>Data visualization techniques can help in understanding patterns, trends, and relationships in the data.</p><pre>import matplotlib.pyplot as plt<br><br># Plot a histogram for a specific column<br>plt.figure(figsize=(15,6))<br>df[&#39;O_TOTALPRICE&#39;].hist(bins=20)<br>plt.title(&#39;Distribution of Total Price&#39;)<br>plt.xlabel(&#39;Total Price&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br>plt.show()<br></pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*5dX5kC7_pVJHvGnRi1MwkA.png" /></figure><h4>4. Data Aggregation and Grouping</h4><p>If you want to perform any analytical tasks, it might be necessary to group the data into certain columns and aggregate it</p><pre># Example: Grouping by order status and calculating the average total price<br>grouped_df = df.groupby(&#39;O_ORDERSTATUS&#39;)[&#39;O_TOTALPRICE&#39;].mean()<br>print(grouped_df)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*hSCyigeWzpGAC7kkswF99g.png" /></figure><h3>Step 3: Close the Connection</h3><p>Once you’re done, always close the cursor and connection to free up resources:</p><pre>cursor.close()<br>conn.close()</pre><h3>Conclusion</h3><p>Connecting Python to Snowflake is a straightforward process that opens up many possibilities for data analysis and machine learning. With Snowflake’s default SNOWFLAKE_SAMPLE_DATA you can start exploring data like the <strong>ORDERS</strong> table right away, even if you don’t have a custom database set up.</p><p>Start practicing today, and take the first step toward mastering cloud data analytics with Python and Snowflake!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f0243b580de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Snowflake: Step-by-Step Account Setup]]></title>
            <link>https://medium.com/@dhanashrisaner.30/getting-started-with-snowflake-step-by-step-account-setup-9b6c2731e21a?source=rss-3cb99fed30cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b6c2731e21a</guid>
            <category><![CDATA[setup]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Dhanashri Saner ]]></dc:creator>
            <pubDate>Sat, 23 Nov 2024 16:19:21 GMT</pubDate>
            <atom:updated>2024-11-27T16:42:01.658Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mThRca9O_bK_lwzi_jBLiQ.jpeg" /></figure><h4>Introduction</h4><p>Snowflake has revolutionized data warehousing with its cloud-native platform, offering unparalleled scalability and ease of use. For beginners, setting up a Snowflake account is the first step toward unlocking its powerful capabilities. This article will guide you through setting up your Snowflake account from scratch, exploring the interface, and running your first query.</p><h3>Why Set Up Snowflake?</h3><p>Before diving in, let’s understand why Snowflake’s setup process is worth exploring:</p><ul><li><strong>Zero Infrastructure Management</strong>: Everything is managed for you in the cloud.</li><li><strong>Elastic Scalability</strong>: Pay for what you use with the ability to scale resources instantly.</li><li><strong>Built-in Security</strong>: Enterprise-grade security features are included out of the box.</li><li><strong>Easy-to-Use Interface</strong>: The platform is intuitive, making it easy even for beginners.</li></ul><h3>Step 1: Signing Up for Snowflake</h3><ol><li><strong>Navigate to the Snowflake Website</strong><br>Visit <a href="https://www.snowflake.com/">Snowflake’s official website</a> and click on the “Start for Free” button.</li><li><strong>Choose a Cloud Provider</strong><br>Snowflake allows you to choose between <strong>AWS</strong>, <strong>Azure</strong>, or <strong>Google Cloud</strong>. Select the one that aligns with your organization’s cloud strategy or personal preference.</li><li><strong>Fill Out Your Details</strong></li></ol><ul><li>Enter your <strong>work email address</strong>.</li><li>Create a <strong>password</strong>.</li><li>Provide the necessary company details.</li><li>Choose your <strong>region</strong>, ensuring it is closest to your geographical location for optimal performance.</li></ul><p>4.<strong> Activate Your Account</strong><br>After signing up, check your email for an activation link. Click the link to activate your Snowflake account and log in to your new account.</p><h3>Step 2: Exploring the Snowflake UI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BlTwRYsnBjzsShN1R57RGA.png" /><figcaption>Snowflake UI</figcaption></figure><p>Once logged in, you’ll encounter Snowflake’s intuitive interface:</p><ol><li><strong>Dashboard Overview</strong>:</li></ol><ul><li><strong>Databases</strong>: Central hub for all your data.</li><li><strong>Warehouses</strong>: Virtual compute clusters used for executing queries.</li><li><strong>Shares</strong>: Facilitates secure data sharing across accounts.</li><li><strong>Marketplace</strong>: A place to explore third-party datasets.</li></ul><p><strong>2. Navigation Pane</strong>:<br>Located on the left-hand side, it allows quick access to:</p><ul><li>Worksheets</li><li>Account settings</li><li>Activity logs</li></ul><p><strong>3. Worksheet Interface</strong>:<br>This is where you’ll write and execute SQL queries.</p><h3>Step 3: Setting Up Your First Database</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gl18HyQlLIYrK5Dxaps7Xw.png" /><figcaption>Databases tab</figcaption></figure><ol><li><strong>Create a Database</strong></li></ol><ul><li>Go to the <strong>Databases</strong> tab in the navigation pane.</li><li>Click <strong>Create</strong> and provide a name for your database (e.g., my_first_database).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A4i6KSnugWLCo6GgBMDmCw.png" /><figcaption>create database my_first_database</figcaption></figure><p><strong>2. Create a Schema</strong></p><ul><li>Inside the database, click on <strong>Schemas</strong> and create a new schema (e.g., TEST).</li><li>Schemas help organize your tables logically.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_z27NTtUs7BjJXmob3wzA.png" /><figcaption>my_first_database ---&gt; click on + schema</figcaption></figure><h3>Step 4: Configuring a Virtual Warehouse</h3><p>A virtual warehouse is a compute cluster used to process queries.</p><ol><li><strong>Navigate to Warehouses</strong>:<br>Click on <strong>Warehouses</strong> in the navigation pane.</li></ol><p><strong>2. Create a Warehouse</strong>:</p><ul><li>Click <strong>Create</strong> and name your warehouse (e.g., demo_warehouse).</li><li>Select a <strong>size</strong> (start with X-Small for practice).</li><li>Enable <strong>Auto-Suspend</strong> (e.g., 5 minutes) to save costs when idle.</li></ul><h3>Step 5: Loading Data into Snowflake</h3><ol><li><strong>Prepare Your Data</strong>:<br>Have a CSV or JSON file ready (e.g., sales_data.csv).</li><li><strong>Create a Table</strong>:</li></ol><ul><li>Open a worksheet.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x7kHK-1QbsrFa1YKVwa_Pw.png" /><figcaption>click on + projects → create worksheet → select database name — -&gt; select schema name</figcaption></figure><ul><li>Run the following SQL query to create a table:</li></ul><pre>CREATE TABLE sales_data (<br>    id INT,<br>    product_name STRING,<br>    quantity INT,<br>    price FLOAT<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*uP8FS2SmLpkETTJ7Raoleg.png" /><figcaption>sales_data table created successfully</figcaption></figure><p>3. <strong>Load Data</strong>:</p><ul><li>Go to the <strong>Databases</strong> tab, select your database, and navigate to <strong>Tables</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*S6zPGJKecaG6kAj0zLDnMw.png" /><figcaption>databases tab</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*QYT2LOwjB6VpP5MGFMAwDQ.png" /><figcaption>my_first_database --&gt; Test(schema) ---&gt; sales_data (table)</figcaption></figure><ul><li>Click on your table, then click <strong>Load Data</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*EhqRxlYvYC5HZuPqj6xZEA.png" /></figure><ul><li>Upload your file and map the columns.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*5bzPWtxjE5uQVSErE9fmvg.png" /><figcaption>click on Browse to laod the data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-5NoekaeSViThniT0sQHbA.png" /><figcaption>click on load</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBXOnN1dxdENLiTd6YlZlA.png" /></figure><h3>Step 6: Running Your First Query</h3><p>With your data loaded, it’s time to query it!</p><ol><li>Open a worksheet and run:</li></ol><pre>SELECT * FROM sales_data;</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Xrtx9dunEqZBEmJvyoVqQ.png" /></figure><p>2. Run an aggregated query to analyze your data:</p><pre>SELECT product_name, SUM(quantity * price) AS total_sales<br>FROM sales_data<br>GROUP BY product_name<br>ORDER BY total_sales DESC;</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*80XgEq2RoNlb_ZZrrs00Kg.png" /></figure><h3>Step 7: Best Practices for Beginners</h3><ol><li><strong>Enable Resource Monitoring</strong>:</li></ol><ul><li>Set budgets for computing usage to avoid unexpected costs.</li></ul><p><strong>2. Use Auto-Suspend for Warehouses</strong>:</p><ul><li>Always enable auto-suspend for warehouses to minimize idle compute charges.</li></ul><p><strong>3. Experiment with Small Datasets</strong>:</p><ul><li>Practice with small datasets before working with production-level data.</li></ul><h3>Conclusion</h3><p>Setting up Snowflake is straightforward, even for beginners. From creating your account to loading and querying data, Snowflake’s intuitive interface and cloud-native design ensure a seamless experience. With your first setup complete, you’re now ready to explore more advanced features, such as Snowflake’s architecture and its capabilities for analytics, data sharing, and beyond.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b6c2731e21a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake: Transforming Cloud Data Warehousing]]></title>
            <link>https://medium.com/@dhanashrisaner.30/snowflake-transforming-cloud-data-warehousing-a909ee04c680?source=rss-3cb99fed30cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a909ee04c680</guid>
            <category><![CDATA[cloud-warehouse]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-warehousing]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Dhanashri Saner ]]></dc:creator>
            <pubDate>Fri, 22 Nov 2024 16:26:01 GMT</pubDate>
            <atom:updated>2024-11-22T16:26:01.490Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-zZQAN2WM8sPxGNoKfAtvA.jpeg" /></figure><h3>Introduction</h3><p>As businesses collect more data, managing it efficiently has become a huge challenge. Traditional data warehouses often fall short in terms of scalability, flexibility, and cost-efficiency. This is where <strong>Snowflake</strong> comes in. Built from the ground up for the cloud, Snowflake offers a flexible, scalable, and easy-to-use solution that is changing how organizations store, process, and analyze data.</p><h3>Why Snowflake Stands Out</h3><p>Think of Snowflake as the <strong>Spotify for data</strong>. Just like Spotify lets you stream music on demand without worrying about storage or setup, Snowflake allows you to store, query, and analyze data with zero infrastructure management.</p><p>Before Snowflake, businesses had to rely on expensive, on-prem systems that required constant maintenance. Snowflake eliminates that with its cloud-native, pay-as-you-go model.</p><h3>What is Snowflake?</h3><p><strong>Snowflake</strong> is a <strong>Software-as-a-Service (SaaS)</strong> platform for data storage and analytics, built entirely on the cloud. It’s not just a data warehouse — it’s a unified platform for diverse workloads, from traditional data warehousing to real-time data sharing and analytics.</p><h3>Why is Snowflake Gaining Popularity?</h3><p>Snowflake’s rise to prominence can be attributed to several game-changing features:</p><h4>1. Separation of Storage and Compute</h4><p>Snowflake introduced a novel architecture that allows storage and computing to scale independently. This means:</p><ul><li>You pay only for what you use.</li><li>Heavy queries don’t block smaller ones.</li></ul><h4>2. Cloud-Native and Multi-Cloud</h4><p>Unlike traditional warehouses, Snowflake doesn’t just run in the cloud; it is <strong>built for the cloud</strong>. It supports multi-cloud setups across AWS, Azure, and Google Cloud, giving businesses flexibility and redundancy.</p><h4>3. Support for Semi-Structured Data</h4><p>With Snowflake, you can directly store and query semi-structured formats like JSON, Avro, and Parquet, eliminating the need for complex ETL pipelines.</p><h4>4. Zero Maintenance</h4><p>No more worrying about managing hardware, indexing, or backups. Snowflake automatically handles optimization, security, and scaling, freeing up engineering resources.</p><h4>5. Time Travel</h4><p>With <strong>Time Travel</strong>, you can query historical data or recover deleted data, offering a powerful tool for audit, compliance, and recovery.</p><h4>6. Data Sharing</h4><p>Snowflake lets you share live data with stakeholders or partners without moving or copying it, making it easy to collaborate and maintain data consistency.</p><h3>When to Use Snowflake?</h3><p>Snowflake is ideal for businesses dealing with:</p><ul><li><strong>Big Data Analytics</strong>: Easily handle large-scale data processing with minimal cost.</li><li><strong>Real-Time Collaboration</strong>: Enable multiple teams to access and work with the same data without conflict.</li><li><strong>Elastic Workloads</strong>: Scale your compute resources on-demand based on data processing needs.</li><li><strong>Machine Learning</strong>: Integrate with ML tools and frameworks like <strong>Python</strong> and <strong>Spark</strong> for end-to-end data pipelines.</li></ul><h3>Competitors</h3><p>Snowflake is not alone in the data warehousing space. Key competitors include:</p><ul><li><strong>Amazon Redshift</strong>: AWS’s managed data warehouse solution.</li><li><strong>Google BigQuery</strong>: Known for its serverless architecture and real-time analytics capabilities.</li><li><strong>Azure Synapse Analytics</strong>: A hybrid data analytics service from Microsoft that combines big data and data warehousing.</li><li><strong>Databricks</strong>: A unified platform built for AI and machine learning with strong support for data lakes.</li></ul><h3>Why Snowflake is Winning?</h3><ol><li><strong>Ease of Use</strong>: Snowflake’s SQL-based interface is beginner-friendly yet powerful.</li><li><strong>Pay-as-You-Go Pricing</strong>: Highly cost-efficient for variable workloads.</li><li><strong>Broad Ecosystem</strong>: Integrates seamlessly with BI tools (Tableau, Power BI), ETL platforms, and ML frameworks.</li><li><strong>Future-Proof</strong>: Designed for scalability and flexibility, ensuring it adapts to future needs.</li></ol><h3>Conclusion</h3><p>Snowflake isn’t just a tool; it’s a paradigm shift in how we think about data in the cloud era. Its ability to simplify complex problems while scaling to meet the demands of the largest organizations is what sets it apart.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a909ee04c680" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[File Formats and Data Sources in PySpark]]></title>
            <link>https://medium.com/@dhanashrisaner.30/file-formats-and-data-sources-in-pyspark-14de6a029b74?source=rss-3cb99fed30cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/14de6a029b74</guid>
            <category><![CDATA[avro]]></category>
            <category><![CDATA[file-format]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[parquet]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Dhanashri Saner ]]></dc:creator>
            <pubDate>Wed, 20 Nov 2024 16:42:43 GMT</pubDate>
            <atom:updated>2024-11-20T16:42:43.803Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tr6SbBtCbmg5iiPHIiLTZA.jpeg" /></figure><h3>Introduction</h3><p>As a data engineer, understanding how to work with different file formats and data sources is fundamental to building efficient data pipelines. Apache Spark, particularly PySpark, offers robust capabilities for reading from and writing to a wide variety of data sources. This article will provide a detailed explanation of the most common file formats used in PySpark, how to read and write these files, and the advantages of using each format.</p><h3>Common File Formats in PySpark</h3><p>PySpark supports multiple file formats such as <strong>CSV</strong>, <strong>JSON</strong>, <strong>Parquet</strong>, <strong>ORC</strong>, and <strong>Avro.</strong></p><h4>1. CSV (Comma-Separated Values)</h4><p>CSV is one of the simplest and most widely used formats to store tabular data. Each row in a CSV file represents a record, and each value within a row is separated by a delimiter, usually a comma.</p><p><strong>Advantages of CSV</strong>:</p><ul><li>Simple and human-readable.</li><li>Common format for data interchange and is easy to use in many applications.</li><li>Supported by almost all data systems.</li></ul><p><strong>Disadvantages</strong>:</p><ul><li>Lack of schema (data types are inferred).</li><li>Poor performance on large datasets due to the lack of optimization.</li><li>No support for complex data types like nested structures.</li></ul><p><strong>Reading CSV Files in PySpark</strong>:</p><pre>from pyspark.sql import SparkSession<br><br># Initialize Spark Session<br>spark = SparkSession.builder.appName(&quot;FileFormats&quot;).getOrCreate()<br><br># Read CSV file<br>csv_df = spark.read.csv(&quot;path/to/file.csv&quot;, header=True, inferSchema=True)<br>csv_df.show()</pre><p><strong>Sample CSV file</strong>:</p><p><a href="https://www.kaggle.com/datasets/kyanyoga/sample-sales-data?select=sales_data_sample.csv">https://www.kaggle.com/datasets/kyanyoga/sample-sales-data?select=sales_data_sample.csv</a></p><p><strong>Writing CSV Files in PySpark</strong>:</p><pre>df.write.csv(&quot;output/sample_output.csv&quot;, header=True)</pre><h4>2. JSON (JavaScript Object Notation)</h4><p>JSON is a popular format for exchanging data between web applications. It is a lightweight, text-based format that stores data in a key-value pair structure, making it ideal for representing complex data.</p><p><strong>Advantages of JSON</strong>:</p><ul><li>Supports complex data types like arrays and nested objects.</li><li>Human-readable and widely used in web services.</li></ul><p><strong>Disadvantages</strong>:</p><ul><li>Slower read and write performance compared to optimized formats like Parquet.</li><li>Inefficient for large datasets.</li></ul><p><strong>Reading JSON Files in PySpark</strong>:</p><pre># Load JSON file into DataFrame<br>df_json = spark.read.json(&quot;data/sample.json&quot;)<br><br># Show data<br>df_json.show()</pre><p><strong>Sample JSON file:</strong></p><p><a href="https://www.kaggle.com/datasets/rtatman/iris-dataset-json-version">https://www.kaggle.com/datasets/rtatman/iris-dataset-json-version</a></p><p><strong>Writing JSON Files in PySpark</strong>:</p><pre>df_json.write.json(&quot;output/sample_output.json&quot;)</pre><h4>3. Parquet</h4><p>Parquet is a columnar storage file format designed to bring efficiency compared to row-based formats like CSV. It is highly optimized for large-scale data processing and analytics, supporting complex nested data types.</p><p><strong>Advantages of Parquet</strong>:</p><ul><li>Columnar format, which allows for better compression and more efficient querying.</li><li>Ideal for large-scale analytics and data pipelines.</li><li>Supports schema evolution and is highly efficient for big data workloads.</li></ul><p><strong>Disadvantages of Parquet</strong>:</p><ul><li>Less human-readable than CSV or JSON.</li><li>Might require additional tooling or libraries for processing outside of Spark.</li></ul><p><strong>Reading Parquet Files in PySpark</strong>:</p><pre># Load Parquet file into DataFrame<br>df_parquet = spark.read.parquet(&quot;data/sample.parquet&quot;)<br>df_parquet.show()</pre><p><strong>Sample Parquet File</strong>: <a href="https://www.kaggle.com/datasets/samuelcortinhas/tps-nov-22-dataset-in-parquet-format">https://www.kaggle.com/datasets/samuelcortinhas/tps-nov-22-dataset-in-parquet-format</a></p><p><strong>Writing Parquet Files in PySpark</strong>:</p><pre>df.write.parquet(&quot;output/sample_output.parquet&quot;)</pre><h4>4. ORC (Optimized Row Columnar)</h4><p>ORC is another columnar storage format, primarily used in the Hadoop ecosystem. It offers higher compression ratios and performance than Parquet in certain scenarios, especially when dealing with large-scale read-heavy operations.</p><p><strong>Advantages of ORC</strong>:</p><ul><li>Better compression and read performance compared to Parquet.</li><li>Optimized for Hive queries.</li></ul><p><strong>Disadvantages of ORC</strong>:</p><ul><li>Less widely supported than Parquet outside the Hadoop ecosystem.</li><li>Not as suitable for complex nested data structures.</li></ul><p><strong>Reading ORC Files in PySpark</strong>:</p><pre># Load ORC file into DataFrame<br>df_orc = spark.read.format(&quot;orc&quot;).load(&quot;data/sample.orc&quot;)<br>df_orc.show()</pre><p><strong>Writing ORC Files in PySpark</strong>:</p><pre>df.write.format(&quot;orc&quot;).save(&quot;output/sample_output.orc&quot;)</pre><h4>5. Avro</h4><p>Avro is a compact, fast, binary data format that is commonly used for storing large-scale data in Hadoop ecosystems. It supports both schema evolution and nested data structures.</p><p><strong>Advantages of Avro</strong>:</p><ul><li>Compact and efficient binary format.</li><li>Supports schema evolution.</li><li>Ideal for high-volume data ingestion and streaming applications.</li></ul><p><strong>Disadvantages of Avro</strong>:</p><ul><li>Binary format, so not human-readable.</li><li>Can be slower for simple, small datasets compared to CSV or JSON.</li></ul><p><strong>Reading Avro Files in PySpark</strong>:</p><pre># Load Avro file into DataFrame<br>df_avro = spark.read.format(&quot;avro&quot;).load(&quot;data/sample.avro&quot;)<br>df_avro.show()</pre><p><strong>Writing Avro Files in PySpark</strong>:</p><pre>df_avro.write.format(&quot;avro&quot;).save(&quot;output/sample_output.avro&quot;)</pre><h3>Integration with Data Sources</h3><p>PySpark seamlessly connects to a variety of data sources:</p><ol><li><strong>HDFS (Hadoop Distributed File System): </strong>Common for storing distributed data in big data ecosystems.</li></ol><p><strong>Example:</strong></p><pre>hdfs_df = spark.read.csv(&quot;hdfs://namenode:9000/path/to/file.csv&quot;)</pre><p>2. <strong>Amazon S3: </strong>Widely used cloud storage for data lakes.</p><p><strong>Example:</strong></p><pre>s3_df = spark.read.parquet(&quot;s3://bucket-name/path/to/file.parquet&quot;)</pre><p><strong>3. JDBC (Relational Databases): </strong>Supports databases like MySQL, Postgres, and SQL Server.</p><p><strong>Example:</strong></p><pre>jdbc_url = &quot;jdbc:postgresql://host:port/database&quot;<br>properties = {&quot;user&quot;: &quot;username&quot;, &quot;password&quot;: &quot;password&quot;}<br>jdbc_df = spark.read.jdbc(jdbc_url, &quot;table_name&quot;, properties=properties)</pre><p><strong>4. Kafka: </strong>Used for real-time data streaming.</p><p><strong>Example:</strong></p><pre>kafka_df = spark.readStream \<br>    .format(&quot;kafka&quot;) \<br>    .option(&quot;kafka.bootstrap.servers&quot;, &quot;localhost:9092&quot;) \<br>    .option(&quot;subscribe&quot;, &quot;topic_name&quot;) \<br>    .load()</pre><h3>Best Practices for File Handling</h3><ol><li><strong>Compression:</strong><br>Use Snappy or Gzip for Parquet and ORC to save storage and speed up reads.</li><li><strong>Schema Management:</strong><br>Explicitly define schemas to avoid issues with schema inference.</li><li><strong>Partitioning:</strong><br>Partition data for distributed processing.</li></ol><h3>Conclusion</h3><p>Understanding file formats and data sources in PySpark is essential for building efficient and scalable data pipelines. Whether you’re analyzing data from a JSON API, querying a relational database, or optimizing Parquet storage for analytics, PySpark provides the tools to work seamlessly across diverse formats and systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14de6a029b74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PySpark Window Functions]]></title>
            <link>https://medium.com/@dhanashrisaner.30/pyspark-window-functions-820ce4046b0b?source=rss-3cb99fed30cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/820ce4046b0b</guid>
            <category><![CDATA[window-functions]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Dhanashri Saner ]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 16:59:14 GMT</pubDate>
            <atom:updated>2024-11-18T16:59:14.347Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCHcRJDYww2E9myywTAJhg.jpeg" /></figure><h3>Introduction</h3><p>In data engineering and analytics, <strong>window functions</strong> are essential for performing calculations across a set of rows that are related to the current row. Unlike aggregate functions, window functions retain the original rows and compute results for subsets of data. PySpark provides robust support for window functions.</p><h3>What Are Window Functions?</h3><p>Window functions operate over a subset of rows (called a “<strong>window</strong>”) and return a result for each row while retaining all rows. These functions are powerful for analyzing trends, ranking data, and calculating cumulative statistics.</p><h3>How Window Functions Work in PySpark</h3><ol><li><strong>Partitioning</strong>: Divides the dataset into groups, similar to SQL’s GROUP BY.<br>Example: Partitioning by Category will create groups for Electronics, Clothing, etc.</li><li><strong>Ordering</strong>: Specifies the order of rows within each partition.<br>Example: Ordering by Amount sorts spending amounts in ascending or descending order within each category.</li><li><strong>Frame Specification</strong> <em>(optional)</em>: Defines the subset of rows in the window to include for the calculation.</li></ol><p>Now that we understand the foundation, let’s explore the <strong>three categories</strong> of window functions in PySpark.</p><h3>1. PySpark Window Ranking Functions</h3><p>These functions assign ranks or numbers to rows based on specified criteria within each window.</p><h4>Key Functions</h4><ul><li><strong>row_number()</strong>: Sequentially assigns a unique number to each row.</li><li><strong>rank()</strong>: Assigns a rank to rows, with ties resulting in gaps (e.g., 1, 2, 2,4)</li><li><strong>dense_rank()</strong>: Similar to rank() but without gaps in ranking.</li><li><strong>percent_rank()</strong>: Computes the relative rank of rows as a percentage.</li><li><strong>ntile(n)</strong>: Divides rows into n approximately equal parts.</li></ul><h4>Example</h4><p><strong>Scenario</strong>: Ranking customers based on their spending within a product category.</p><p><strong>Importing Required Libraries:</strong></p><pre>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import row_number, rank, dense_rank<br>from pyspark.sql import Window</pre><p><strong>SparkSession </strong>is the entry point to working with Spark. You create it to access the Spark APIs and perform operations.</p><p><strong>Creating the Spark Session:</strong></p><pre>spark = SparkSession.builder.appName(&quot;WindowFunctions&quot;).getOrCreate()</pre><p>This creates a SparkSession named &quot;WindowFunctions&quot;. The builder is used to configure and instantiate the session. The getOrCreate() method either creates a new session or retrieves the existing one if it&#39;s already created.</p><p><strong>Sample Data:</strong></p><pre>data = [(&quot;Alice&quot;, &quot;Electronics&quot;, 1200),<br>        (&quot;Bob&quot;, &quot;Electronics&quot;, 800),<br>        (&quot;Eve&quot;, &quot;Electronics&quot;, 1200),<br>        (&quot;Alice&quot;, &quot;Clothing&quot;, 500),<br>        (&quot;Bob&quot;, &quot;Clothing&quot;, 300)]</pre><p><strong>data </strong>is<strong> </strong>a<strong> </strong>list of tuples where each tuple represents a row.</p><p><strong>Creating the DataFrame:</strong></p><pre>df = spark.createDataFrame(data, [&quot;Customer&quot;, &quot;Category&quot;, &quot;Amount&quot;])<br>df.show()</pre><p>This converts the data list into a Spark DataFrame, with the specified column names: &quot;Customer&quot;, &quot;Category&quot;, and &quot;Amount&quot;.</p><p><strong>Output:</strong></p><pre>+--------+-----------+------+<br>|Customer|   Category|Amount|<br>+--------+-----------+------+<br>|   Alice|Electronics|  1200|<br>|     Bob|Electronics|   800|<br>|     Eve|Electronics|  1200|<br>|   Alice|   Clothing|   500|<br>|     Bob|   Clothing|   300|<br>+--------+-----------+------+</pre><p><strong>Defining the Window Specification:</strong></p><pre>window_spec = Window.partitionBy(&quot;Category&quot;).orderBy(&quot;Amount&quot;)</pre><p><strong>Window specification </strong>defines how the data should be grouped and ordered for applying the window functions.</p><p><strong>Applying Ranking Window Functions</strong></p><pre>df_ranked = df.withColumn(&quot;row_number&quot;, row_number().over(window_spec)) \<br>    .withColumn(&quot;rank&quot;, rank().over(window_spec)) \<br>    .withColumn(&quot;dense_rank&quot;, dense_rank().over(window_spec))<br>df_ranked.show()</pre><p>Output:</p><pre>+--------+-----------+------+----------+----+----------+<br>|Customer|   Category|Amount|row_number|rank|dense_rank|<br>+--------+-----------+------+----------+----+----------+<br>|     Bob|   Clothing|   300|         1|   1|         1|<br>|   Alice|   Clothing|   500|         2|   2|         2|<br>|     Bob|Electronics|   800|         1|   1|         1|<br>|   Alice|Electronics|  1200|         2|   2|         2|<br>|     Eve|Electronics|  1200|         3|   2|         2|<br>+--------+-----------+------+----------+----+----------+</pre><p><strong>Explanation of Output</strong>:</p><p>Let’s take the row for <strong>Bob in Clothing</strong> with Amount = 300:</p><ul><li><strong>row_number</strong>: Assigns a unique number to each row in the partition. Since Bob is the lowest in Clothing, he gets row_number = 1</li><li><strong>rank</strong>: Assigns the same rank for ties, but skips ranks after ties. Since Bob has the lowest amount, he gets rank = 1</li><li><strong>dense_rank</strong>: Assigns the same rank for ties but doesn&#39;t skip ranks. Since Bob has the lowest amount, he gets dense_rank = 1</li></ul><h3>2. PySpark Window Analytic Functions</h3><p>Used to access data from previous or next rows within a partition, enabling time-series analysis or trend comparisons.</p><h4>Key Functions</h4><ul><li><strong>lag(column, offset)</strong>: Fetches the value from a previous row in the same window.</li><li><strong>lead(column, offset)</strong>: Fetches the value from the next row in the same window.</li></ul><h4>Example</h4><p><strong>Scenario</strong>: Comparing a customer’s spending to the previous transaction in the same category.</p><pre>from pyspark.sql.functions import lag, lead<br><br># Apply analytic functions<br>df_trends = df.withColumn(&quot;prev_amount&quot;, lag(&quot;Amount&quot;, 1).over(window_spec)) \<br>    .withColumn(&quot;next_amount&quot;, lead(&quot;Amount&quot;, 1).over(window_spec))<br><br>df_trends.show()</pre><p><strong>Output:</strong></p><pre>+--------+-----------+------+-----------+-----------+<br>|Customer|   Category|Amount|prev_amount|next_amount|<br>+--------+-----------+------+-----------+-----------+<br>|     Bob|   Clothing|   300|       NULL|        500|<br>|   Alice|   Clothing|   500|        300|       NULL|<br>|     Bob|Electronics|   800|       NULL|       1200|<br>|   Alice|Electronics|  1200|        800|       1200|<br>|     Eve|Electronics|  1200|       1200|       NULL|<br>+--------+-----------+------+-----------+-----------+</pre><p><strong>Explanation of Output</strong>:</p><ul><li><strong>prev_amount</strong>: Displays the spending amount of the previous customer.</li><li><strong>next_amount</strong>: Displays the spending amount of the next customer.</li></ul><h3>3. PySpark Window Aggregate Functions</h3><p>Aggregate functions calculate summary statistics over a window, such as totals, averages, and extremes.</p><h4>Key Functions</h4><ul><li><strong>sum()</strong>: Computes the sum of a column within the window.</li><li><strong>avg()</strong>: Computes the average value within the window.</li><li><strong>max()</strong>: Returns the maximum value.</li><li><strong>min()</strong>: Returns the minimum value.</li></ul><h4>Example</h4><p><strong>Scenario</strong>: Calculating total spending by customers in a category.</p><pre>from pyspark.sql.functions import sum, avg<br><br># Apply aggregate functions<br>df_aggregates = df.withColumn(&quot;total_amount&quot;, sum(&quot;Amount&quot;).over(window_spec)) \<br>    .withColumn(&quot;avg_amount&quot;, avg(&quot;Amount&quot;).over(window_spec))<br><br>df_aggregates.show()</pre><p>Output:</p><pre>+--------+-----------+------+------------+------------------+<br>|Customer|   Category|Amount|total_amount|        avg_amount|<br>+--------+-----------+------+------------+------------------+<br>|     Bob|   Clothing|   300|         300|             300.0|<br>|   Alice|   Clothing|   500|         800|             400.0|<br>|     Bob|Electronics|   800|         800|             800.0|<br>|   Alice|Electronics|  1200|        3200|1066.6666666666667|<br>|     Eve|Electronics|  1200|        3200|1066.6666666666667|<br>+--------+-----------+------+------------+------------------+</pre><h3>Conclusion</h3><p>Window functions are a versatile tool in PySpark for performing complex calculations without losing the original row context. Whether you’re ranking rows, analyzing trends, or calculating aggregates, window functions can simplify your code and enhance your data engineering pipelines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=820ce4046b0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Joins in PySpark for Efficient Data Merging]]></title>
            <link>https://medium.com/@dhanashrisaner.30/understanding-joins-in-pyspark-for-efficient-data-merging-a15b365b621c?source=rss-3cb99fed30cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a15b365b621c</guid>
            <category><![CDATA[data-merge]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[joins-in-spark]]></category>
            <dc:creator><![CDATA[Dhanashri Saner ]]></dc:creator>
            <pubDate>Fri, 15 Nov 2024 16:55:25 GMT</pubDate>
            <atom:updated>2024-11-15T16:55:25.167Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4kqPKUR4yN7R3_x4rsSsEg.jpeg" /></figure><h3>Introduction</h3><p>Data processing in distributed environments often requires merging datasets from different sources to create meaningful insights. In PySpark, joins are one of the most commonly used operations to combine datasets. This article provides a comprehensive look at join types in PySpark with practical examples.</p><h3>What Are Joins in PySpark?</h3><p>A join operation combines rows from two DataFrames based on a related column or condition. PySpark has several types of joins, each suited to different use cases. Joins are integral to creating unified datasets, enriching data, and analyzing relationships between datasets.</p><h3>Types of Joins in PySpark</h3><p>Let’s dive into each join type with relevant examples.</p><h4>1. Inner Join</h4><p>The <strong>inner join</strong> returns rows where the key exists in both DataFrames.</p><p><strong>Scenario:</strong><br>You have an <strong>employee</strong> dataset and a <strong>timesheet</strong> dataset. You want to find employees who have submitted timesheets.</p><pre>from pyspark.sql import SparkSession<br>spark = SparkSession.builder.appName(&quot;PySpark Joins&quot;).getOrCreate()</pre><pre># Employees DataFrame<br>employees = spark.createDataFrame(<br>    [(&quot;E1&quot;, &quot;Alice&quot;), (&quot;E2&quot;, &quot;Bob&quot;), (&quot;E3&quot;, &quot;Eve&quot;)],<br>    [&quot;EmpID&quot;, &quot;Name&quot;]<br>)<br><br># Timesheets DataFrame<br>timesheets = spark.createDataFrame(<br>    [(&quot;E1&quot;, 40), (&quot;E2&quot;, 35), (&quot;E4&quot;, 20)],<br>    [&quot;EmpID&quot;, &quot;HoursWorked&quot;]<br>)<br><br># Inner Join<br>inner_join = employees.join(timesheets, on=&quot;EmpID&quot;, how=&quot;inner&quot;)<br>inner_join.show()</pre><p>Output:</p><pre>+-----+-----+-----------+<br>|EmpID| Name|HoursWorked|<br>+-----+-----+-----------+<br>|   E1|Alice|         40|<br>|   E2|  Bob|         35|<br>+-----+-----+-----------+</pre><h4>2. Left Join (Left Outer Join)</h4><p>The <strong>left join</strong> returns all rows from the left DataFrame, and matches from the right DataFrame where available. Unmatched rows will have NULL values.</p><p><strong>Scenario:</strong><br>Get a list of all employees, including those who haven’t submitted timesheets.</p><pre>left_join = employees.join(timesheets, on=&quot;EmpID&quot;, how=&quot;left&quot;)<br>left_join.show()</pre><pre>+-----+-----+-----------+<br>|EmpID| Name|HoursWorked|<br>+-----+-----+-----------+<br>|   E1|Alice|         40|<br>|   E2|  Bob|         35|<br>|   E3|  Eve|       NULL|<br>+-----+-----+-----------+</pre><h4>3. Right Join (Right Outer Join)</h4><p>The <strong>right join</strong> returns all rows from the right DataFrame, and matches from the left DataFrame where available.</p><p><strong>Scenario:</strong><br>List all timesheet records, even for non-registered employees.</p><pre>right_join = employees.join(timesheets, on=&quot;EmpID&quot;, how=&quot;right&quot;)<br>right_join.show()</pre><p>Output:</p><pre>+-----+-----+-----------+<br>|EmpID| Name|HoursWorked|<br>+-----+-----+-----------+<br>|   E1|Alice|         40|<br>|   E2|  Bob|         35|<br>|   E4| NULL|         20|<br>+-----+-----+-----------+</pre><h4>4. Full Outer Join</h4><p>The <strong>full outer join</strong> combines all rows from both DataFrames, filling NULL where there’s no match.</p><p><strong>Scenario:</strong><br>Combine employee and timesheet data comprehensively.</p><pre>full_outer_join = employees.join(timesheets, on=&quot;EmpID&quot;, how=&quot;outer&quot;)<br>full_outer_join.show()</pre><p>Output:</p><pre>+-----+-----+-----------+<br>|EmpID| Name|HoursWorked|<br>+-----+-----+-----------+<br>|   E1|Alice|         40|<br>|   E2|  Bob|         35|<br>|   E3|  Eve|       NULL|<br>|   E4| NULL|         20|<br>+-----+-----+-----------+</pre><h4>5. Semi Join</h4><p>The <strong>semi-join</strong> returns rows from the left DataFrame where there’s a match in the right DataFrame. It does not include columns from the right DataFrame.</p><p><strong>Scenario:</strong><br>Find employees who have submitted timesheets.</p><pre>semi_join = employees.join(timesheets, on=&quot;EmpID&quot;, how=&quot;leftsemi&quot;)<br>semi_join.show()</pre><pre>+-----+-----+<br>|EmpID| Name|<br>+-----+-----+<br>|   E1|Alice|<br>|   E2|  Bob|<br>+-----+-----+</pre><h4>6. Anti Join</h4><p>The <strong>anti-join</strong> returns rows from the left DataFrame where there’s no match in the right DataFrame.</p><p><strong>Scenario:</strong><br>Identify employees who haven’t submitted timesheets.</p><pre>anti_join = employees.join(timesheets, on=&quot;EmpID&quot;, how=&quot;leftanti&quot;)<br>anti_join.show()</pre><p>Output:</p><pre>+-----+-----+<br>|EmpID| Name|<br>+-----+-----+<br>|   E3|  Eve|<br>+-----+-----+</pre><h4>7. Joining Multiple Columns</h4><p>You can perform joins on multiple columns when you have multiple keys for matching rows.</p><p><strong>Scenario:</strong><br>Match customers with their orders using CustomerID and Region.</p><pre># Customers DataFrame<br>customers = spark.createDataFrame(<br>    [(&quot;C1&quot;, &quot;Alice&quot;, &quot;North&quot;), (&quot;C2&quot;, &quot;Bob&quot;, &quot;South&quot;), (&quot;C3&quot;, &quot;Eve&quot;, &quot;East&quot;)],<br>    [&quot;CustomerID&quot;, &quot;Name&quot;, &quot;Region&quot;]<br>)<br><br># Orders DataFrame<br>orders = spark.createDataFrame(<br>    [(&quot;C1&quot;, &quot;North&quot;, 500), (&quot;C2&quot;, &quot;South&quot;, 300), (&quot;C3&quot;, &quot;West&quot;, 700)],<br>    [&quot;CustomerID&quot;, &quot;Region&quot;, &quot;OrderAmount&quot;]<br>)<br><br># Multi-key Join<br>multi_key_join = customers.join(orders, on=[&quot;CustomerID&quot;, &quot;Region&quot;], how=&quot;inner&quot;)<br>multi_key_join.show()</pre><p>Output:</p><pre>+----------+-----+-----+-----------+<br>|CustomerID| Name|Region|OrderAmount|<br>+----------+-----+-----+-----------+<br>|        C1|Alice|North|        500|<br>|        C2|  Bob|South|        300|<br>+----------+-----+-----+-----------+</pre><h3>Conclusion</h3><p>Joins in PySpark are versatile and allow data engineers to combine datasets in various ways, depending on the requirements. The examples above illustrate different join types with practical use cases to make the concepts easy to understand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a15b365b621c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Aggregations and Grouping in PySpark]]></title>
            <link>https://medium.com/@dhanashrisaner.30/advanced-aggregations-and-grouping-in-pyspark-89ee7c9dcd6d?source=rss-3cb99fed30cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/89ee7c9dcd6d</guid>
            <category><![CDATA[pivot]]></category>
            <category><![CDATA[group-by]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Dhanashri Saner ]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 18:13:37 GMT</pubDate>
            <atom:updated>2024-11-14T18:13:37.189Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OOmpCFYts4Ht66fEKuTFNg.jpeg" /></figure><p>In the realm of big data, efficient data summarization is essential for generating meaningful insights. Aggregation and grouping help us derive patterns, trends, and overall summaries that are otherwise hidden in large datasets. When working with data at scale, PySpark’s distributed processing engine allows us to perform these operations quickly and efficiently.</p><p>Let’s consider a <strong>real-world scenario</strong> in which a retail company wants to analyze its sales data. The company has a large dataset of customer purchases, and they’re interested in understanding the spending patterns of individual customers, the total sales in various categories, and overall trends in the business. To derive these insights, we need to use <strong>grouping</strong> and <strong>aggregation</strong> functions, which will allow us to break down and summarize the data in a meaningful way.</p><p>In this guide, we’ll walk through essential techniques in PySpark to achieve these goals, including:</p><ul><li>Performing basic and advanced groupings with groupBy</li><li>Using pivot for dynamic aggregations</li><li>Leveraging rollup for multi-level aggregations</li></ul><h3>Setting Up the PySpark Environment</h3><p>Before we start, ensure the PySpark is installed and initialize a Spark session to work with our data.</p><pre>from pyspark.sql import SparkSession<br>spark = SparkSession.builder.appName(&quot;AdvancedAggregations&quot;).getOrCreate()</pre><p>Now, let’s create a sample dataset that represents customer purchases in different product categories.</p><pre><br>data = [<br>    (&quot;Alice&quot;, &quot;Electronics&quot;, 500),<br>    (&quot;Bob&quot;, &quot;Electronics&quot;, 200),<br>    (&quot;Alice&quot;, &quot;Clothing&quot;, 150),<br>    (&quot;Bob&quot;, &quot;Clothing&quot;, 100),<br>    (&quot;Alice&quot;, &quot;Electronics&quot;, 250),<br>    (&quot;Eve&quot;, &quot;Clothing&quot;, 300)<br>]<br>columns = [&quot;Customer&quot;, &quot;Category&quot;, &quot;Amount&quot;]<br><br># Create DataFrame<br>df = spark.createDataFrame(data, schema=columns)<br>df.show()</pre><p>Output:</p><pre>+--------+-----------+------+<br>|Customer|   Category|Amount|<br>+--------+-----------+------+<br>|   Alice|Electronics|   500|<br>|     Bob|Electronics|   200|<br>|   Alice|   Clothing|   150|<br>|     Bob|   Clothing|   100|<br>|   Alice|Electronics|   250|<br>|     Eve|   Clothing|   300|<br>+--------+-----------+------+</pre><h3>Grouping and Aggregating Data with groupBy</h3><p>The groupBy function in PySpark allows us to group data based on one or more columns, followed by applying an aggregation function such as sum, count, or avg. This operation is essential for generating insights like total sales, customer-wise spending, or average purchases.</p><p><strong>Example 1: Total Amount Spent by Each Customer</strong></p><pre>total_spent = df.groupBy(&quot;Customer&quot;).sum(&quot;Amount&quot;)<br>total_spent.show()</pre><p>Output:</p><pre>+--------+-----------+<br>|Customer|sum(Amount)|<br>+--------+-----------+<br>|   Alice|        900|<br>|     Bob|        300|<br>|     Eve|        300|<br>+--------+-----------+</pre><p>In this example, we group data by customer to get the total amount each customer has spent. This provides a quick way to identify high-value customers.</p><h4>Example 2: Total Amount Spent by Each Customer in Each Category</h4><pre>category_spent = df.groupBy(&quot;Customer&quot;, &quot;Category&quot;).sum(&quot;Amount&quot;)<br>category_spent.show()</pre><p>Output:</p><pre>+--------+-----------+-----------+<br>|Customer|   Category|sum(Amount)|<br>+--------+-----------+-----------+<br>|   Alice|Electronics|        750|<br>|     Bob|Electronics|        200|<br>|   Alice|   Clothing|        150|<br>|     Bob|   Clothing|        100|<br>|     Eve|   Clothing|        300|<br>+--------+-----------+-----------+</pre><p>Here, we can see the total amount each customer spent in each product category, giving a more detailed view of their spending habits.</p><h3>Using pivot for Dynamic Aggregations</h3><p>The pivot function in PySpark allows us to transform distinct values in a column into new columns, creating a pivot table. This is helpful for building reports and dynamic summaries where you want to see data split by categories.</p><p><strong>Example: Total Amount Spent by Each Customer Across Categories</strong></p><pre>pivot_df = df.groupBy(&quot;Customer&quot;).pivot(&quot;Category&quot;).sum(&quot;Amount&quot;)<br>pivot_df.show()</pre><pre>+--------+--------+-----------+<br>|Customer|Clothing|Electronics|<br>+--------+--------+-----------+<br>|     Bob|     100|        200|<br>|   Alice|     150|        750|<br>|     Eve|     300|       NULL|<br>+--------+--------+-----------+</pre><p>This code groups by each customer and dynamically creates a column for each category with the total amount spent in that category. It allows us to see a customer’s spending across all categories in a single row.</p><h3>Multi-Level Aggregations with rollup</h3><p>The rollup function in PySpark enables multi-level aggregations, providing subtotals and grand totals in a single query. It’s especially useful for hierarchical data summaries, where we want to see totals at multiple levels.</p><p><strong>Example: Rollup for Total Sales per Customer and Overall Total</strong></p><pre>rollup_df = df.rollup(&quot;Customer&quot;, &quot;Category&quot;).sum(&quot;Amount&quot;).orderBy(&quot;Customer&quot;, &quot;Category&quot;)<br>rollup_df.show()</pre><p>Output:</p><pre>+--------+-----------+-----------+<br>|Customer|   Category|sum(Amount)|<br>+--------+-----------+-----------+<br>|    NULL|       NULL|       1500|<br>|   Alice|       NULL|        900|<br>|   Alice|   Clothing|        150|<br>|   Alice|Electronics|        750|<br>|     Bob|       NULL|        300|<br>|     Bob|   Clothing|        100|<br>|     Bob|Electronics|        200|<br>|     Eve|       NULL|        300|<br>|     Eve|   Clothing|        300|<br>+--------+-----------+-----------+</pre><p>Output explanation</p><p><strong>(NULL, NULL, 1500)</strong>:</p><ul><li>This row represents the <strong>grand total</strong> for all Customer and Category combinations in the dataset, which is 1500.</li></ul><p><strong>(Alice, NULL, 900)</strong>:</p><ul><li>This row represents the <strong>subtotal for Alice</strong> across all categories, which is 900.</li><li>Alice spent a total of 750 on Electronics and 150 on Clothing, so her subtotal is 750 + 150 = 900.</li></ul><p><strong>(Alice, Clothing, 150)</strong> and <strong>(Alice, Electronics, 750)</strong>:</p><ul><li>These rows show the total amount spent by <strong>Alice</strong> on each individual Category.</li><li>Alice spent 150 on Clothing and 750 on Electronics.</li></ul><h3>Combining Multiple Aggregations</h3><p>PySpark allows us to perform multiple aggregations in a single operation using agg. This is useful when we want various statistical measures simultaneously, such as totals, averages, and counts.</p><h4>Example: Calculating Total and Average Amount Spent by Each Customer</h4><pre>multi_agg_df = df.groupBy(&quot;Customer&quot;).agg({&quot;Amount&quot;: &quot;sum&quot;, &quot;Amount&quot;: &quot;avg&quot;})<br>multi_agg_df.show()</pre><p>Output:</p><pre>+--------+-----------+<br>|Customer|avg(Amount)|<br>+--------+-----------+<br>|   Alice|      300.0|<br>|     Bob|      150.0|<br>|     Eve|      300.0|<br>+--------+-----------+</pre><p>This groups by Customer and calculates both the total and average amount spent. We gain more insights about each customer’s spending behavior without writing separate aggregation statements.</p><h3>Conclusion</h3><p>Efficient aggregation and grouping in PySpark allow data engineers to quickly analyze and summarize large datasets. Techniques like groupBy, pivot, and rollup empower you to produce detailed, multi-level reports that provide valuable insights, especially when working with large-scale data in a distributed environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89ee7c9dcd6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring PySpark SQL and User-Defined Functions (UDFs)]]></title>
            <link>https://medium.com/@dhanashrisaner.30/exploring-pyspark-sql-and-user-defined-functions-udfs-abd6d454fc28?source=rss-3cb99fed30cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/abd6d454fc28</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[pyspark-udf]]></category>
            <dc:creator><![CDATA[Dhanashri Saner ]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 17:16:41 GMT</pubDate>
            <atom:updated>2024-11-11T17:16:41.465Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7W4OygQdasS6VrXJFBv8wA.jpeg" /></figure><h3>Introduction</h3><p>Managing and transforming massive datasets quickly and efficiently in data engineering is a core requirement. Traditional SQL works well for many relational database operations, but more than SQL alone may be needed as data volume and complexity grow. This is where <strong>PySpark</strong> becomes invaluable: it extends SQL capabilities to handle distributed data processing on large datasets, leveraging the parallel computing power of Apache Spark.</p><h3>PySpark SQL</h3><p>PySpark SQL provides an interface to run SQL queries on distributed data, making it a natural choice for teams familiar with SQL who need to scale out their data operations.</p><h4>Key Features of PySpark SQL:</h4><ol><li><strong>Unified Data Processing:</strong> Enables seamless transition between SQL and other Spark operations, integrating with Spark’s RDD (Resilient Distributed Datasets).</li><li><strong>DataFrame API:</strong> Abstracts complex data operations, making it easy to use for data manipulation, similar to pandas DataFrames but optimized for distributed computing.</li><li><strong>Interoperability:</strong> Supports a variety of data formats and sources, like Parquet, ORC, JSON, and CSV.</li><li><strong>SQL Compatibility:</strong> Allows standard SQL queries, making it easy for SQL users to adopt PySpark with minimal learning curve.</li></ol><p>Let’s go through a quick example of loading data with PySpark SQL.</p><p><strong>dataset link:</strong></p><p><a href="https://www.kaggle.com/datasets/anninasimon/employee-salary-dataset">https://www.kaggle.com/datasets/anninasimon/employee-salary-dataset</a></p><pre>from pyspark.sql import SparkSession<br>spark = SparkSession.builder.appName(&quot;EmployeeData&quot;).getOrCreate()<br><br># Load data into DataFrame<br>df = spark.read.csv(&quot;path/to/employee_data.csv&quot;, header=True, inferSchema=True)<br>df.show()</pre><p>Output:</p><pre>+---+----------------+---+------+-------+<br>| ID|Experience_Years|Age|Gender| Salary|<br>+---+----------------+---+------+-------+<br>|  1|               5| 28|Female| 250000|<br>|  2|               1| 21|  Male|  50000|<br>|  3|               3| 23|Female| 170000|<br>|  4|               2| 22|  Male|  25000|<br>|  5|               1| 17|  Male|  10000|<br>|  6|              25| 62|  Male|5001000|<br>|  7|              19| 54|Female| 800000|<br>|  8|               2| 21|Female|   9000|<br>|  9|              10| 36|Female|  61500|<br>| 10|              15| 54|Female| 650000|<br>| 11|               4| 26|Female| 250000|<br>| 12|               6| 29|  Male|1400000|<br>| 13|              14| 39|  Male|6000050|<br>| 14|              11| 40|  Male| 220100|<br>| 15|               2| 23|  Male|   7500|<br>| 16|               4| 27|Female|  87000|<br>| 17|              10| 34|Female| 930000|<br>| 18|              15| 54|Female|7900000|<br>| 19|               2| 21|  Male|  15000|<br>| 20|              10| 36|  Male| 330000|<br>+---+----------------+---+------+-------+<br>only showing top 20 rows</pre><p>Now that the data is loaded, we’ll register the DataFrame as an SQL temporary table and perform SQL queries to retrieve specific information.</p><pre># Register DataFrame as a SQL temporary view<br>df.createOrReplaceTempView(&quot;employees&quot;)<br>result = spark.sql(&quot;SELECT ID, Age, Salary FROM employees WHERE Experience_Years &gt; 5 AND Salary &gt; 50000&quot;)<br>result.show()</pre><p>Output:</p><pre>+---+---+--------+<br>| ID|Age|  Salary|<br>+---+---+--------+<br>|  6| 62| 5001000|<br>|  7| 54|  800000|<br>|  9| 36|   61500|<br>| 10| 54|  650000|<br>| 12| 29| 1400000|<br>| 13| 39| 6000050|<br>| 14| 40|  220100|<br>| 17| 34|  930000|<br>| 18| 54| 7900000|<br>| 20| 36|  330000|<br>| 21| 54| 6570000|<br>| 28| 62|10000000|<br>| 29| 54| 5000000|<br>| 31| 34|   80000|<br>| 32| 54|  900000|<br>| 33| 55| 1540000|<br>| 34| 53| 9300000|<br>| 35| 49| 7600000|<br>+---+---+--------+</pre><p>This query selects employees who have over 5 years of experience and earn more than $50,000, leveraging PySpark’s distributed processing.</p><h3>PySpark UDFs (User-Defined Functions)</h3><p>While PySpark SQL covers many common operations, there are times when you’ll need custom transformations. PySpark UDFs allow you to define Python functions to process data in ways that standard SQL functions cannot.</p><h4>Why Use UDFs?</h4><ol><li><strong>Custom Logic</strong>: Enables complex transformations and calculations beyond standard SQL.</li><li><strong>Reusability</strong>: UDFs can be reused across multiple DataFrames and pipelines.</li><li><strong>Flexibility</strong>: Allows custom multi-column transformations and advanced business logic.</li></ol><p>Suppose you want to calculate a performance-based bonus of 15% for employees with over 10 years of experience. Let’s walk through how to create and apply this UDF.</p><h4>Example: Creating and Using a PySpark UDF</h4><ol><li><strong>Define the UDF</strong>: Create a Python function to calculate the bonus.</li><li><strong>Register and Apply the UDF</strong>: Convert the function into a PySpark UDF and add a new column.</li></ol><pre>from pyspark.sql.functions import udf<br>from pyspark.sql.types import DoubleType<br><br># Define a Python function to calculate bonus<br>def calculate_bonus(experience_years, salary):<br>    if experience_years &gt; 10:<br>        return salary * 0.15  # 15% bonus for &gt; 10 years of experience<br>    return 0  # No bonus otherwise<br><br>bonus_udf = udf(calculate_bonus, DoubleType())<br>df_with_bonus = df.withColumn(&quot;Bonus&quot;, bonus_udf(df[&quot;Experience_Years&quot;], df[&quot;Salary&quot;]))<br>df_with_bonus.show()</pre><p>Output:</p><pre>+---+----------------+---+------+-------+---------+<br>| ID|Experience_Years|Age|Gender| Salary|    Bonus|<br>+---+----------------+---+------+-------+---------+<br>|  1|               5| 28|Female| 250000|     NULL|<br>|  2|               1| 21|  Male|  50000|     NULL|<br>|  3|               3| 23|Female| 170000|     NULL|<br>|  4|               2| 22|  Male|  25000|     NULL|<br>|  5|               1| 17|  Male|  10000|     NULL|<br>|  6|              25| 62|  Male|5001000| 750150.0|<br>|  7|              19| 54|Female| 800000| 120000.0|<br>|  8|               2| 21|Female|   9000|     NULL|<br>|  9|              10| 36|Female|  61500|     NULL|<br>| 10|              15| 54|Female| 650000|  97500.0|<br>| 11|               4| 26|Female| 250000|     NULL|<br>| 12|               6| 29|  Male|1400000|     NULL|<br>| 13|              14| 39|  Male|6000050| 900007.5|<br>| 14|              11| 40|  Male| 220100|  33015.0|<br>| 15|               2| 23|  Male|   7500|     NULL|<br>| 16|               4| 27|Female|  87000|     NULL|<br>| 17|              10| 34|Female| 930000|     NULL|<br>| 18|              15| 54|Female|7900000|1185000.0|<br>| 19|               2| 21|  Male|  15000|     NULL|<br>| 20|              10| 36|  Male| 330000|     NULL|<br>+---+----------------+---+------+-------+---------+<br>only showing top 20 rows</pre><p>In this example:</p><ul><li>calculate_bonus applies a 15% bonus for employees with more than 10 years of experience.</li><li>udf() registers the function as a PySpark UDF with DoubleType() the return type.</li><li>withColumn() applies the UDF to add a Bonus column in the DataFrame.</li></ul><h3>Conclusion</h3><p>PySpark SQL and UDFs make a powerful toolkit for data engineers working with large datasets. With PySpark SQL, you can perform complex SQL-like queries on distributed data, while UDFs allow custom transformations that go beyond standard SQL. These tools empower data engineers to efficiently build scalable, flexible pipelines for complex data workflows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abd6d454fc28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering PySpark Transformations and Actions]]></title>
            <link>https://medium.com/@dhanashrisaner.30/mastering-pyspark-transformations-and-actions-b4c6341835c3?source=rss-3cb99fed30cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4c6341835c3</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Dhanashri Saner ]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 16:49:29 GMT</pubDate>
            <atom:updated>2024-11-10T16:49:29.285Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rEC_HLIm53IYnOEKISenXw.jpeg" /></figure><h3>Introduction</h3><p>When working with big data, efficient data handling is critical. PySpark provides a powerful distributed processing framework, with transformations and actions as its core components. This guide explains these operations and sheds light on the difference between narrow and wide transformations and what happens internally when they are executed.</p><h3>Transformations in PySpark</h3><p>Transformations in PySpark create new datasets by applying operations to existing ones. They come in two main types: <strong>narrow</strong> and <strong>wide</strong>.</p><h4>1. Narrow Transformations</h4><p>A <strong>narrow transformation</strong> operates on data within a single partition, meaning each partition processes its own data independently. Examples include map(), filter(), and withColumn(). Since narrow transformations don’t require shuffling data between partitions, they are faster and more efficient.</p><p>Example: Scenario: E-commerce Orders Dataset</p><p>Let’s start with a sample dataset that we’ll use throughout the examples.</p><pre>from pyspark.sql import SparkSession<br><br># Initialize Spark session<br>spark = SparkSession.builder.appName(&quot;PySpark Examples&quot;).getOrCreate()<br><br># Sample data<br>data = [(&quot;1&quot;, &quot;101&quot;, &quot;Laptop&quot;, 1200), (&quot;2&quot;, &quot;102&quot;, &quot;Headphones&quot;, 150),<br>        (&quot;3&quot;, &quot;101&quot;, &quot;Mouse&quot;, 25), (&quot;4&quot;, &quot;103&quot;, &quot;Laptop&quot;, 1200),<br>        (&quot;5&quot;, &quot;104&quot;, &quot;Monitor&quot;, 300)]<br>columns = [&quot;Order_ID&quot;, &quot;Customer_ID&quot;, &quot;Product&quot;, &quot;Price&quot;]<br><br># Create DataFrame<br>df = spark.createDataFrame(data, schema=columns)<br>df.show()</pre><p><strong>Output</strong>:</p><pre>+--------+-----------+----------+-----+<br>|Order_ID|Customer_ID|   Product|Price|<br>+--------+-----------+----------+-----+<br>|       1|        101|    Laptop| 1200|<br>|       2|        102|Headphones|  150|<br>|       3|        101|     Mouse|   25|<br>|       4|        103|    Laptop| 1200|<br>|       5|        104|   Monitor|  300|<br>+--------+-----------+----------+-----+</pre><ol><li><strong>map()</strong>: Transforms each element in the DataFrame individually.</li></ol><p><strong>Example</strong>: Apply a transformation to add a 10% tax to each price.</p><pre><br>df_with_tax = df.rdd.map(lambda row: (row.Order_ID, row.Customer_ID, row.Product, row.Price * 1.1)).toDF(columns)<br>df_with_tax.show()</pre><p><strong>Output</strong>:</p><pre>+--------+-----------+----------+------------------+<br>|Order_ID|Customer_ID|   Product|             Price|<br>+--------+-----------+----------+------------------+<br>|       1|        101|    Laptop|            1320.0|<br>|       2|        102|Headphones|             165.0|<br>|       3|        101|     Mouse|27.500000000000004|<br>|       4|        103|    Laptop|            1320.0|<br>|       5|        104|   Monitor|             330.0|<br>+--------+-----------+----------+------------------+</pre><p>2. <strong>filter()</strong>: Filters rows based on a specified condition.</p><p><strong>Example:</strong> Filter orders where Price &gt; 100</p><pre><br>high_value_orders = df.filter(df[&quot;Price&quot;] &gt; 100)<br>high_value_orders.show()</pre><pre>+--------+-----------+----------+-----+<br>|Order_ID|Customer_ID|   Product|Price|<br>+--------+-----------+----------+-----+<br>|       1|        101|    Laptop| 1200|<br>|       2|        102|Headphones|  150|<br>|       4|        103|    Laptop| 1200|<br>|       5|        104|   Monitor|  300|<br>+--------+-----------+----------+-----+</pre><p>3. <strong>withColumn()</strong>: Adds a new column or updates an existing column in the DataFrame.</p><p><strong>Example:</strong> Add a new column “<strong>Discounted_Price</strong>” with a 20% discount</p><pre>from pyspark.sql.functions import col<br><br>df_with_discount = df.withColumn(&quot;Discounted_Price&quot;, col(&quot;Price&quot;) * 0.8)<br>df_with_discount.show()</pre><p><strong>Output:</strong></p><pre>+--------+-----------+----------+-----+----------------+<br>|Order_ID|Customer_ID|   Product|Price|Discounted_Price|<br>+--------+-----------+----------+-----+----------------+<br>|       1|        101|    Laptop| 1200|           960.0|<br>|       2|        102|Headphones|  150|           120.0|<br>|       3|        101|     Mouse|   25|            20.0|<br>|       4|        103|    Laptop| 1200|           960.0|<br>|       5|        104|   Monitor|  300|           240.0|<br>+--------+-----------+----------+-----+----------------+</pre><h3>Wide Transformations</h3><p>A <strong>wide transformation</strong> requires shuffling, moving data between partitions or nodes to reorganize and redistribute data. Examples include groupBy(), join(), and repartition(), which rely on aggregating data across partitions.</p><ol><li><strong>groupBy()</strong>: Groups data based on one or more columns and performs aggregation.</li></ol><p><strong>Example:</strong> Calculate total spending by each customer</p><pre>total_spent = df.groupBy(&quot;Customer_ID&quot;).sum(&quot;Price&quot;).withColumnRenamed(&quot;sum(Price)&quot;, &quot;Total_Spent&quot;)<br>total_spent.show()</pre><p><strong>Output:</strong></p><pre>+-----------+-----------+<br>|Customer_ID|Total_Spent|<br>+-----------+-----------+<br>|        101|       1225|<br>|        102|        150|<br>|        104|        300|<br>|        103|       1200|<br>+-----------+-----------+</pre><p>2. <strong>join()</strong>: Combines two DataFrames based on a common key.</p><p><strong>Example:</strong> Perform a join between orders and customer data on Customer_ID</p><pre># Sample customer data to join with orders<br>customer_data = [(&quot;101&quot;, &quot;Alice&quot;), (&quot;102&quot;, &quot;Bob&quot;), (&quot;103&quot;, &quot;Charlie&quot;), (&quot;104&quot;, &quot;David&quot;)]<br>customer_df = spark.createDataFrame(customer_data, schema=[&quot;Customer_ID&quot;, &quot;Customer_Name&quot;])<br><br># Perform a join between orders and customer data on Customer_ID<br>order_with_customer = df.join(customer_df, on=&quot;Customer_ID&quot;, how=&quot;inner&quot;)<br>order_with_customer.show()</pre><p><strong>Output:</strong></p><pre>+-----------+--------+----------+-----+-------------+<br>|Customer_ID|Order_ID|   Product|Price|Customer_Name|<br>+-----------+--------+----------+-----+-------------+<br>|        101|       1|    Laptop| 1200|        Alice|<br>|        101|       3|     Mouse|   25|        Alice|<br>|        102|       2|Headphones|  150|          Bob|<br>|        103|       4|    Laptop| 1200|      Charlie|<br>|        104|       5|   Monitor|  300|        David|<br>+-----------+--------+----------+-----+-------------+</pre><p>3. <strong>repartition()</strong>: Redistributes data across a specified number of partitions for optimized processing.</p><p><strong>Example:</strong> Repartition data into 3 partitions</p><pre><br>repartitioned_df = df.repartition(3)<br>print(&quot;Number of partitions after repartition:&quot;, repartitioned_df.rdd.getNumPartitions())</pre><p><strong>Output:</strong></p><p>Number of partitions after repartition: 3</p><h3>What Happens Internally with Narrow and Wide Transformations?</h3><ol><li><strong>Narrow Transformations</strong>:</li></ol><ul><li>PySpark processes data within each partition independently, without any network communication.</li><li>A chain of narrow transformations can be combined and processed together in a single stage of execution.</li></ul><p><strong>2. Wide Transformations</strong>:</p><ul><li>When PySpark encounters a wide transformation, it must redistribute data across partitions, known as a <strong>shuffle</strong>.</li><li>Spark creates new stages in the job and moves data between partitions (shuffling) to ensure data with the same key (like Customer_ID) ends up in the same partition.</li><li>If multiple narrow transformations precede a wide transformation, PySpark first completes all narrow transformations and then triggers the shuffle. This design minimizes data movement and allows Spark to execute stages efficiently.</li></ul><h3>Actions in PySpark</h3><p>Actions trigger the execution of the transformations. Common actions include count(), collect(), and show(), each forcing Spark to compute the data pipeline built from transformations.</p><p><strong>Examples of Actions</strong>:</p><ul><li>count(): Counts the rows in the DataFrame.</li><li>show(): Displays rows of the DataFrame.</li><li>collect(): Brings the dataset to the driver, which can cause memory issues if the data is too large.</li></ul><h3>Conclusion</h3><p>Understanding transformations and actions in PySpark, and how narrow and wide transformations impact data shuffling, is crucial for efficient distributed processing. Mastering these basics allows you to optimize PySpark jobs for scalability and performance.</p><p>By building a strong foundation in transformations, you’ll be well-equipped to develop efficient, scalable pipelines for handling large-scale datasets in PySpark.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4c6341835c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing PySpark Performance: Smart Use of Caching and Execution Planning]]></title>
            <link>https://medium.com/@dhanashrisaner.30/enhancing-pyspark-performance-smart-use-of-caching-and-execution-planning-f58fa3935492?source=rss-3cb99fed30cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f58fa3935492</guid>
            <category><![CDATA[lazy-evaluation]]></category>
            <category><![CDATA[pyspark-dataframes]]></category>
            <category><![CDATA[cashing]]></category>
            <dc:creator><![CDATA[Dhanashri Saner ]]></dc:creator>
            <pubDate>Fri, 08 Nov 2024 16:58:31 GMT</pubDate>
            <atom:updated>2024-11-08T16:58:31.855Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4u5ovz2X7FJq8AiKbntmng.jpeg" /></figure><h3>Introduction</h3><p>Efficiently processing massive datasets is key in big data applications, and PySpark offers optimization features that make it incredibly powerful. Two such features are <strong>lazy evaluation</strong> and <strong>caching</strong>, which can significantly enhance PySpark’s performance. This guide will walk you through these concepts with examples.</p><h3>Understanding Lazy Evaluation in PySpark</h3><p>When you apply transformations (like filter or select) to a DataFrame in PySpark, these transformations are not executed immediately. Instead, PySpark builds a <strong>logical plan</strong> of all the operations. This approach is called <strong>lazy evaluation</strong>.</p><h4>How Lazy Evaluation Works</h4><p>Lazy evaluation delays the computation of transformations until an <strong>action</strong> is called. Actions (such as show(), count(), and collect()) force Spark to execute the entire logical plan at once, allowing for better optimization and performance.</p><p><strong>Example Code for Lazy Evaluation:</strong></p><p>Let’s start with a basic DataFrame containing sales transaction data:</p><pre>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import col<br><br>spark = SparkSession.builder.appName(&quot;LazyEvaluationExample&quot;).getOrCreate()<br><br>data = [<br>    (1, &quot;2023-11-01&quot;, &quot;Electronics&quot;, 1200),<br>    (2, &quot;2023-11-02&quot;, &quot;Apparel&quot;, 300),<br>    (3, &quot;2023-11-03&quot;, &quot;Electronics&quot;, 2000),<br>    (4, &quot;2023-11-04&quot;, &quot;Furniture&quot;, 1500)<br>]<br>columns = [&quot;transaction_id&quot;, &quot;date&quot;, &quot;category&quot;, &quot;amount&quot;]<br><br>transactions_df = spark.createDataFrame(data, columns)<br><br># Define transformations<br>filtered_df = transactions_df.filter(col(&quot;amount&quot;) &gt; 1000)<br>selected_df = filtered_df.select(&quot;transaction_id&quot;, &quot;amount&quot;)<br><br># No transformation is executed yet because of lazy evaluation<br></pre><p>Here, <strong>no actual computation</strong> happens until we call show() on selected_df. At that point, Spark optimizes and runs the entire transformation pipeline.</p><pre># Execute an action to trigger the transformations<br>selected_df.show()</pre><p>Output:</p><pre>+--------------+------+<br>|transaction_id|amount|<br>+--------------+------+<br>|             1|  1200|<br>|             3|  2000|<br>|             4|  1500|<br>+--------------+------+</pre><h3>Caching and Persisting DataFrames in PySpark</h3><p>When working with large datasets, it’s common to use a DataFrame multiple times in your pipeline. <strong>Caching</strong> and <strong>persisting</strong> allow you to save intermediate DataFrames in memory (or on disk) after their initial computation, avoiding redundant operations.</p><h4>Why Cache DataFrames?</h4><ul><li><strong>Efficiency</strong>: Prevents recomputation of costly transformations.</li><li><strong>Reduced Latency</strong>: Speeds up processing for repeated data access.</li></ul><h4>Different Storage Levels in Caching</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*zRbfHjpt5okEJJfFUKzaDg.png" /></figure><p><strong>Example Code: Caching and Storage Levels</strong></p><pre># Cache the filtered DataFrame in memory<br>filtered_df.cache()<br><br># Alternatively, persist with a specified storage level<br>from pyspark import StorageLevel<br>filtered_df.persist(StorageLevel.MEMORY_AND_DISK)<br><br># Perform actions on the cached DataFrame<br>print(filtered_df.count())   # First action (will cache filtered_df)<br>print(filtered_df.groupBy(&quot;category&quot;).count().show())  # Second action (no recomputation)</pre><p>24/11/08 20:33:20 WARN CacheManager: Asked to cache already cached data.</p><pre>3<br><br>+-----------+-----+<br>|   category|count|<br>+-----------+-----+<br>|Electronics|    2|<br>|  Furniture|    1|<br>+-----------+-----+</pre><p>In this example, caching filtered_df ensures that we don’t re-run the filter operation when accessing it again. Using persist() with StorageLevel.MEMORY_AND_DISK is helpful when data is too large to fit entirely in memory.</p><p><strong>Example: Performance Gains with Caching</strong></p><p>To illustrate the performance benefits, let’s look at the time difference between cached and non-cached operations on a larger dataset. Here, we create a larger DataFrame and run operations with and without caching.</p><pre># Generate a larger dataset<br>large_data = [(i, &quot;2023-11-&quot; + str(i % 30 + 1), &quot;Category&quot; + str(i % 5), i * 100) for i in range(1, 100001)]<br>large_df = spark.createDataFrame(large_data, columns)<br><br># Without caching<br>import time<br><br># Measure time for repeated actions without caching<br>start_time = time.time()<br>filtered_large_df = large_df.filter(col(&quot;amount&quot;) &gt; 100000)<br>print(filtered_large_df.count())  # First action<br>print(filtered_large_df.groupBy(&quot;category&quot;).count().show())  # Second action<br>end_time = time.time()<br>print(&quot;Execution time without caching:&quot;, end_time - start_time, &quot;seconds&quot;)<br><br># With caching<br>start_time = time.time()<br>filtered_large_df.cache()<br>print(filtered_large_df.count())  # First action (caches filtered_large_df)<br>print(filtered_large_df.groupBy(&quot;category&quot;).count().show())  # Second action<br>end_time = time.time()<br>print(&quot;Execution time with caching:&quot;, end_time - start_time, &quot;seconds&quot;)</pre><pre>99000<br>                                                                                <br>+---------+-----+<br>| category|count|<br>+---------+-----+<br>|Category2|19800|<br>|Category1|19800|<br>|Category3|19800|<br>|Category0|19800|<br>|Category4|19800|<br>+---------+-----+<br><br>None<br>Execution time without caching: 2.573596477508545 seconds<br>                                                                                <br>99000<br>+---------+-----+<br>| category|count|<br>+---------+-----+<br>|Category2|19800|<br>|Category1|19800|<br>|Category3|19800|<br>|Category0|19800|<br>|Category4|19800|<br>+---------+-----+<br><br>None<br>Execution time with caching: 2.1816089153289795 seconds</pre><h4>Best Practices for PySpark Optimization</h4><ul><li><strong>Filter Early</strong>: Apply filters at the beginning of the data pipeline to reduce data size.</li><li><strong>Choose Appropriate Storage Level</strong>: Based on data size, select a storage level that balances memory and disk usage.</li><li><strong>Avoid Unnecessary Actions</strong>: Minimize actions collect() that pull large amounts of data into memory.</li><li><strong>Use Broadcast Joins for Small Datasets</strong>: When joining a large dataset with a small one, use broadcast() it to avoid shuffling.</li></ul><h3>Conclusion</h3><p>Mastering lazy evaluation and caching transforms your PySpark experience, making your data processing pipelines more efficient and scalable. Understanding when and how to cache data can lead to significant time savings, especially for large-scale data engineering tasks. By leveraging these optimization techniques, you can handle massive datasets with ease and efficiency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f58fa3935492" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>