<?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 Prasad Khode on Medium]]></title>
        <description><![CDATA[Stories by Prasad Khode on Medium]]></description>
        <link>https://medium.com/@khodeprasad?source=rss-42d8d94b74ee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OlqD1s8pS0lRLTUXvGMtww.jpeg</url>
            <title>Stories by Prasad Khode on Medium</title>
            <link>https://medium.com/@khodeprasad?source=rss-42d8d94b74ee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:33:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khodeprasad/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[How to Get/Pull a Branch From a Forked Git Repository]]></title>
            <link>https://khodeprasad.medium.com/how-to-get-pull-a-branch-from-a-forked-git-repository-d8b15f1644be?source=rss-42d8d94b74ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8b15f1644be</guid>
            <category><![CDATA[gitfork]]></category>
            <category><![CDATA[git-repositories]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[git-for-engineer]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Prasad Khode]]></dc:creator>
            <pubDate>Sat, 31 Jan 2026 06:37:19 GMT</pubDate>
            <atom:updated>2026-01-31T06:37:19.004Z</atom:updated>
            <content:encoded><![CDATA[<p>When you fork a Git repository on GitHub, it is easy to assume that you get everything.<br>In reality, you usually work only with the default branch, often called master or main.</p><p>This becomes a problem when a tutorial later asks you to check out a different branch.<br>If you already forked the repository, you might wonder if you need to start over.</p><p>Good news: <strong>you don’t</strong>.</p><p>This article explains why the confusion happens and how to fix it properly.</p><h3>The Common Mistake</h3><p>After forking and cloning a repository, you run:</p><pre>git branch</pre><p>You only see:</p><pre>* master</pre><p>This makes it feel like the other branches do not exist.</p><p>But they do exist — <strong>they are just not local yet</strong>.</p><h3>Why This Happens</h3><p>Git has two types of branches:</p><ul><li><strong>Local branches</strong> — branches you have created on your machine</li><li><strong>Remote-tracking branches</strong> — branches that exist on a remote repository</li></ul><p>The command:</p><pre>git branch</pre><p>shows <strong>only local branches</strong>.</p><p>That is why you only see master.</p><h3>Step 1: Add the Original Repository as a Remote</h3><p>Your fork already has a remote called origin. This points to <em>your fork</em>.</p><p>Now you need to add the <strong>original repository</strong> as another remote. This is usually called upstream.</p><pre>git remote add upstream https://github.com/ORIGINAL_OWNER/REPO_NAME.git</pre><p>You can confirm it with:</p><pre>git remote</pre><p>You should see:</p><pre>origin<br>upstream</pre><h3>Step 2: Fetch All Branches</h3><p>Adding a remote is not enough.<br>You must <strong>fetch</strong> the branches from it.</p><pre>git fetch --all</pre><p>This downloads all branches from both origin and upstream.</p><h3>Step 3: List All Branches (Local + Remote)</h3><p>Now run:</p><pre>git branch --all</pre><p>You will see something like:</p><pre>* master<br>  remotes/origin/master<br>  remotes/upstream/master<br>  remotes/upstream/develop<br>  remotes/upstream/feature-x</pre><p>These remotes/upstream/* branches are real branches. They are just not local yet.</p><h3>Step 4: Check Out the Branch You Need</h3><p>Let’s say you want to work on the develop branch.</p><p>You can simply run:</p><pre>git switch develop</pre><p>Git will:</p><ul><li>Create a local develop branch</li><li>Link it to upstream/develop</li></ul><p>You are now working on that branch locally.</p><h3>Step 5: Push the Branch to Your Fork (Optional)</h3><p>If you want this branch to exist in <strong>your fork</strong>, push it to origin:</p><pre>git push origin develop</pre><p>Now your fork also has this branch.</p><h3>Why the Original Approach Failed</h3><p>Commands like this fail:</p><pre>git checkout source/branch</pre><p>because:</p><ul><li>source/branch is not a commit</li><li>The branch was never fetched</li><li>The remote-tracking branch did not exist locally</li></ul><p>Git cannot create a branch from something it does not know about.</p><h3>Important Tip</h3><p>When you clone a repository, Git automatically checks out the default branch.<br>That is why master appears even though you never created it manually.</p><p>If you want <strong>no local branches at all</strong>, you can clone with:</p><pre>git clone --no-checkout &lt;repo-url&gt;</pre><p>This is optional, but useful in advanced workflows.</p><h3>Final Thoughts</h3><p>You do <strong>not</strong> need to fork the repository again.<br>You do <strong>not</strong> need to start from scratch.</p><p>All you need is:</p><ol><li>Add the original repo as upstream</li><li>Fetch all branches</li><li>Check out the branch you want</li></ol><p>Once you understand the difference between <strong>local branches</strong> and <strong>remote branches</strong>, Git becomes much clearer.</p><p>Happy coding 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8b15f1644be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding SQL Self Joins with Scenarios]]></title>
            <link>https://khodeprasad.medium.com/understanding-sql-self-joins-with-scenarios-4b557e465f7e?source=rss-42d8d94b74ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b557e465f7e</guid>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[self-join]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[joins-in-sql]]></category>
            <dc:creator><![CDATA[Prasad Khode]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 09:22:10 GMT</pubDate>
            <atom:updated>2024-10-10T09:22:10.130Z</atom:updated>
            <content:encoded><![CDATA[<p>Self joins can often be an overlooked aspect of SQL, yet they are incredibly useful for querying hierarchical or related data within a single table. In this article, we’ll explore what a self join is, how it works, and we’ll illustrate its application through various real-world scenarios.</p><h3>What is a Self Join?</h3><p>A self join is a regular join that joins a table to itself. This technique is particularly useful when dealing with hierarchical data, such as organizational structures, where relationships exist between rows of the same table.</p><p>To perform a self join, you typically use table aliases to distinguish between the two instances of the table in the query. The basic syntax looks like this:</p><pre>SELECT a.column_name, b.column_name<br>FROM table_name AS a<br>JOIN table_name AS b ON a.common_field = b.common_field;</pre><h3>Scenario 1: Employee Hierarchy</h3><h3>The Problem</h3><p>Imagine a company where you have an employees table that contains information about employees and their managers. The table structure might look like this:</p><pre>| employee_id | name         | manager_id |<br>|-------------|--------------|------------|<br>| 1           | Amit Sharma  | NULL       |<br>| 2           | Priya Rao    | 1          |<br>| 3           | Rohan Gupta  | 1          |<br>| 4           | Neha Desai   | 2          |<br>| 5           | Suresh Verma | 2          |</pre><h3>The Self Join Query</h3><p>To retrieve a list of employees along with their managers’ names, you would use a self join:</p><pre>SELECT e.name AS employee_name, m.name AS manager_name<br>FROM employees AS e<br>LEFT JOIN employees AS m ON e.manager_id = m.employee_id;</pre><h3>The Result</h3><p>This query will produce the following result:</p><pre>| employee_name   | manager_name   |<br>|-----------------|----------------|<br>| Amit Sharma     | NULL           |<br>| Priya Rao       | Amit Sharma    |<br>| Rohan Gupta     | Amit Sharma    |<br>| Neha Desai      | Priya Rao      |<br>| Suresh Verma    | Priya Rao      |</pre><p>In this scenario, we can see how the self join helps us establish a clear relationship between employees and their respective managers, even when both are stored in the same table.</p><h3>Scenario 2: Finding Duplicate Entries</h3><h3>The Problem</h3><p>In some cases, you may need to find duplicate entries within a single table. Let’s say we have a users table with the following structure:</p><pre>| user_id | username      | email                 |<br>|---------|---------------|-----------------------|<br>| 1       | rahul_mehta   | rahul@example.com     |<br>| 2       | priyanka      | priyanka@example.com  |<br>| 3       | rahul_mehta   | rahul@anothermail.com |</pre><h3>The Self Join Query</h3><p>To identify users with duplicate usernames, we can use a self join as follows:</p><pre>SELECT a.username<br>FROM users AS a<br>JOIN users AS b ON a.username = b.username<br>WHERE a.user_id &lt;&gt; b.user_id;</pre><h3>The Result</h3><p>This query will output:</p><pre>| username      |<br>+---------------+<br>| rahul_mehta   |</pre><p>This indicates that rahul_mehta appears multiple times in the users table, helping to identify potential duplicates.</p><h3>Conclusion</h3><p>Self joins are a powerful tool in SQL that can help simplify complex queries involving hierarchical or related data. By using table aliases, you can effectively join a table to itself to extract meaningful relationships. In this article, we’ve explored various scenarios that demonstrate how self joins can be applied in real-world situations. Whether you’re working with employee hierarchies or identifying duplicates, mastering self joins will enhance your SQL skills and make data analysis much more efficient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b557e465f7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Grouping a Spark DataFrame and Creating JSON Lists in Scala]]></title>
            <link>https://khodeprasad.medium.com/grouping-a-spark-dataframe-and-creating-json-lists-in-scala-a4fddd3c79b0?source=rss-42d8d94b74ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4fddd3c79b0</guid>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[group-by]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Prasad Khode]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 07:25:58 GMT</pubDate>
            <atom:updated>2024-10-09T07:26:47.263Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, we’ll explore how to group a Spark DataFrame by a specific column and create a list of JSON objects from other columns. This operation is useful when you want to combine data into a structured format for further analysis or export.</p><h3>Problem Scenario</h3><p>Let’s say we have the following DataFrame:</p><pre>+----+----+----+<br>|col1|col2|col3|<br>+----+----+----+<br>|A   |1   |x   |<br>|B   |2   |y   |<br>|A   |3   |z   |<br>|B   |4   |w   |<br>|A   |5   |v   |<br>+----+----+----+</pre><p>We want to group by col1 and generate a list of JSON objects containing col2 and col3 for each unique value in col1.</p><h3>Steps to Solve</h3><p>Here’s how we can achieve this using Apache Spark and Scala:</p><ol><li><strong>Import Required Libraries</strong>: We’ll start by importing necessary Spark libraries.</li><li><strong>Create the DataFrame</strong>: For this example, we’ll create a simple DataFrame with sample data.</li><li><strong>Convert Columns into JSON</strong>: We’ll use Spark’s built-in to_json and struct functions to convert the columns col2 and col3 into JSON format.</li><li><strong>Group by and Aggregate</strong>: Finally, we’ll group the DataFrame by col1 and collect the JSON objects into a list.</li></ol><p>Let’s dive into the implementation.</p><h3>Code Implementation</h3><pre>import org.apache.spark.sql.functions._<br>import org.apache.spark.sql.SparkSession<br><br>// Step 1: Create a Spark session<br>val spark = SparkSession.builder().appName(&quot;GroupByJSON&quot;).getOrCreate()<br>import spark.implicits._<br><br>// Step 2: Define the sample data and create a DataFrame<br>val data = Seq(<br>  (&quot;A&quot;, 1, &quot;x&quot;),<br>  (&quot;B&quot;, 2, &quot;y&quot;),<br>  (&quot;A&quot;, 3, &quot;z&quot;),<br>  (&quot;B&quot;, 4, &quot;w&quot;),<br>  (&quot;A&quot;, 5, &quot;v&quot;)<br>)<br>val df = data.toDF(&quot;col1&quot;, &quot;col2&quot;, &quot;col3&quot;)<br><br>// Step 3: Create a JSON representation of col2 and col3<br>val dfWithJson = df.withColumn(&quot;json_column&quot;, to_json(struct($&quot;col2&quot;, $&quot;col3&quot;)))<br><br>// Step 4: Group by col1 and collect JSON objects into a list<br>val result = dfWithJson.groupBy(&quot;col1&quot;).agg(collect_list(&quot;json_column&quot;).as(&quot;json_list&quot;))<br><br>// Step 5: Show the result<br>result.show(false)</pre><ul><li>We initiate a Spark session which serves as the entry point for Spark operations.</li><li>We create a sample DataFrame with three columns (col1, col2, and col3). You can replace this with any data you are working with.</li><li>We use struct to combine col2 and col3 into a structured format, and then use to_json to convert this structure into a JSON string.</li><li>We group the data by col1 and use the collect_list function to aggregate the JSON objects for each group.</li></ul><h3>Output</h3><p>Here’s what the final result looks like:</p><pre>+----+---------------------------------------------------------------------+<br>|col1|json_list                                                            |<br>+----+---------------------------------------------------------------------+<br>|A   |[{&quot;col2&quot;:1,&quot;col3&quot;:&quot;x&quot;}, {&quot;col2&quot;:3,&quot;col3&quot;:&quot;z&quot;}, {&quot;col2&quot;:5,&quot;col3&quot;:&quot;v&quot;}]|<br>|B   |[{&quot;col2&quot;:2,&quot;col3&quot;:&quot;y&quot;}, {&quot;col2&quot;:4,&quot;col3&quot;:&quot;w&quot;}]                       |<br>+----+---------------------------------------------------------------------+</pre><p>Each row now has a list of JSON objects that represent the combination of col2 and col3 for each unique value of col1.</p><h3>Use Cases</h3><p>This technique can be applied in several scenarios:</p><ul><li><strong>Data transformation</strong>: Reshaping your data into a nested JSON structure can be useful when preparing data for APIs or exporting it to document-based databases like MongoDB.</li><li><strong>Data aggregation</strong>: Combining related data into lists simplifies reporting and analysis, especially when working with grouped data.</li></ul><h3>Conclusion</h3><p>We’ve successfully demonstrated how to group a Spark DataFrame by one column and generate a list of JSON objects from other columns. This approach is efficient for transforming structured data into more flexible, readable formats.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4fddd3c79b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Dynamic Partition Overwrite in Spark: A Guide to PartitionOverwriteMode]]></title>
            <link>https://khodeprasad.medium.com/simplifying-dynamic-partition-overwrite-in-spark-a-guide-to-partitionoverwritemode-29fd984e15de?source=rss-42d8d94b74ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/29fd984e15de</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[dynamic-partitioning]]></category>
            <category><![CDATA[data-partitioning]]></category>
            <dc:creator><![CDATA[Prasad Khode]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 07:06:27 GMT</pubDate>
            <atom:updated>2024-10-09T07:06:27.775Z</atom:updated>
            <content:encoded><![CDATA[<p>When you’re dealing with large amounts of data in Apache Spark, managing your data efficiently becomes important. One way to do this is by breaking your data into smaller, manageable parts using <strong>partitioning</strong>. However, updating only specific partitions without overwriting everything can be tricky. That’s where Spark’s <strong>PartitionOverwriteMode</strong> comes in.</p><p>In this guide, we’ll explore how to overwrite specific partitions dynamically using both PySpark and Scala. We’ll also cover how this feature helps make your data handling more efficient.</p><h3>What Is Data Partitioning in Spark?</h3><p>Partitioning means dividing data into chunks based on specific column values. This division makes it easier to handle large datasets by speeding up queries and reducing the amount of data processed at one time.</p><p>For example, a partitioned dataset might be stored like this:</p><pre>/data/year=2023/month=08/day=15/</pre><p>Each folder represents a partition, and when you query your data, Spark can easily skip unnecessary partitions, making the process faster.</p><h3>The Problem with Overwriting Partitions</h3><p>By default, when you overwrite partitioned data in Spark, the entire partition is replaced. This can lead to several issues:</p><ul><li><strong>Loss of Data</strong>: All data in the partition might be replaced, even if only part of it needs updating.</li><li><strong>Resource Waste</strong>: If only a small portion of the data changed, replacing the entire partition is inefficient.</li><li><strong>Inconsistent Data</strong>: Updating part of a partition incorrectly may lead to incomplete data.</li></ul><p>To avoid these issues, Spark provides a way to overwrite only specific partitions while leaving others untouched.</p><h3>Introduction to PartitionOverwriteMode</h3><p>Starting from Spark 2.3, a new feature called PartitionOverwriteMode was introduced. It allows you to choose between two modes:</p><ol><li><strong>STATIC</strong> (default): Overwrites the entire partition folder.</li><li><strong>DYNAMIC</strong>: Overwrites only the partitions included in the new data, leaving others unchanged.</li></ol><h3>How to Enable Dynamic Partition Overwrite</h3><p>By default, Spark uses the static mode, which replaces the entire partition. To enable dynamic partition overwrite, you need to change a configuration setting.</p><p>In PySpark, you can do it like this:</p><pre>spark.conf.set(&quot;spark.sql.sources.partitionOverwriteMode&quot;, &quot;dynamic&quot;)</pre><p>For Scala users, the setting is the same:</p><pre>spark.conf.set(&quot;spark.sql.sources.partitionOverwriteMode&quot;, &quot;dynamic&quot;)</pre><p>Once enabled, Spark only updates the affected partitions instead of replacing the entire dataset.</p><h3>Example: Using Dynamic Partition Overwrite with Indian Data</h3><p>Let’s see an example using PySpark, where we write data about Indian customers to partitioned directories and update only the relevant partitions.</p><pre>from pyspark.sql import SparkSession<br><br>spark = SparkSession.builder.appName(&quot;PartitionOverwriteExample&quot;).getOrCreate()<br><br># Sample data about customers from different months<br>data = [(&quot;Rajesh&quot;, &quot;2023&quot;, &quot;08&quot;), (&quot;Sunita&quot;, &quot;2023&quot;, &quot;09&quot;)]<br>columns = [&quot;name&quot;, &quot;year&quot;, &quot;month&quot;]<br><br>df = spark.createDataFrame(data, schema=columns)<br><br># Enable dynamic partition overwrite<br>spark.conf.set(&quot;spark.sql.sources.partitionOverwriteMode&quot;, &quot;dynamic&quot;)<br><br># Write data partitioned by year and month<br>df.write.partitionBy(&quot;year&quot;, &quot;month&quot;).mode(&quot;overwrite&quot;).format(&quot;parquet&quot;).save(&quot;/data/output/&quot;)</pre><p>In this example, Spark will only update the partitions for year=2023 and month=08 and month=09, leaving other partitions untouched. This way, the partitions that don’t need updating are preserved, saving time and resources.</p><h3>Handling Schema Changes</h3><p>When working with dynamic partition overwrite, it’s important to keep the schema (the structure of your data) consistent. If the schema changes, especially the partition columns, Spark might raise errors or overwrite data incorrectly.</p><p>To handle this, you can define the schema explicitly, like this:</p><pre>from pyspark.sql.types import StructType, StructField, StringType<br><br>schema = StructType([<br>    StructField(&quot;name&quot;, StringType(), True),<br>    StructField(&quot;year&quot;, StringType(), True),<br>    StructField(&quot;month&quot;, StringType(), True)<br>])<br><br>df = spark.createDataFrame(data, schema=schema)</pre><p>This ensures that the partition columns stay consistent across different write operations.</p><h3>Best Practices for Using Dynamic Partition Overwrite</h3><p>To get the most out of dynamic partition overwrite, here are some simple tips:</p><ol><li><strong>Choose Your Partition Columns Carefully</strong>: Select columns based on how you frequently query the data. Don’t over-partition, as too many small partitions can slow things down.</li><li><strong>Use Bucketing</strong>: For large datasets, consider combining partitioning with bucketing to distribute data evenly and improve performance.</li><li><strong>Keep Schema Consistent</strong>: Make sure your partition columns have the same names and types across different jobs to avoid errors.</li><li><strong>Use Efficient File Formats</strong>: Use formats like <strong>Parquet</strong> or <strong>ORC</strong>, which store data efficiently and improve query performance.</li><li><strong>Check Spark Version</strong>: Ensure you’re using Spark 2.3 or later, as dynamic partition overwrite is only available in these versions.</li></ol><h3>Conclusion</h3><p>Dynamic partition overwrite is a powerful feature that helps you manage partitioned datasets more efficiently in Spark. By only updating the partitions that need to change, you avoid unnecessary data overwrites and save time and resources.</p><p>By following best practices, like choosing the right partition columns, keeping schema consistent, and using efficient file formats, you can make your data pipelines faster and more reliable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29fd984e15de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Run Ollama Locally Using Docker]]></title>
            <link>https://khodeprasad.medium.com/how-to-run-ollama-locally-using-docker-2a5bdd90cc20?source=rss-42d8d94b74ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a5bdd90cc20</guid>
            <category><![CDATA[local-deployment]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Prasad Khode]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 08:48:13 GMT</pubDate>
            <atom:updated>2024-09-02T09:17:08.111Z</atom:updated>
            <content:encoded><![CDATA[<p>Running AI models locally can be a great way to leverage the power of machine learning without relying on cloud services. In this guide, I will show you how to set up and run Ollama locally using Docker. This includes pulling the necessary images, setting up containers, and executing models. Let’s dive in!</p><h3>Prerequisites</h3><p>Before we begin, ensure you have Docker installed on your machine. If not, you can download it from the official Docker website.</p><h3>Step 1: Pull the Ollama Docker Image</h3><p>First, we need to pull the Ollama Docker image from Docker Hub. This image contains everything you need to run Ollama.</p><pre>docker pull ollama/ollama</pre><h3>Step 2: Run the Ollama Container</h3><p>Once the image is pulled, we can run the container. This step will start Ollama and expose it on port 11434.</p><pre>docker run -d -p 11434:11434 --name ollama ollama/ollama</pre><ul><li>-d: Runs the container in detached mode.</li><li>-p 11434:11434: Maps the container&#39;s port 11434 to your machine&#39;s port 11434.</li><li>--name ollama: Names the container &quot;ollama&quot;.</li></ul><h3>Step 3: Execute Models within the Ollama Container</h3><p>Now that the container is running, you can execute different models within it. For example, to run the llama3 model, use the following command:</p><pre>docker exec -it ollama ollama run llama3</pre><p>Similarly, to run the gemma model, use:</p><pre>docker exec -it ollama ollama run gemma</pre><ul><li>docker exec -it: Executes a command in a running container.</li><li>ollama run llama3: Runs the llama3 model in the Ollama container.</li></ul><h3>Step 4: Set Up Ollama with a Web UI</h3><p>If you prefer to interact with Ollama via a web interface, you can set up a web UI using Docker. There are two options:</p><h3>Option 1: Open-WebUI</h3><p>This option sets up a generic web interface for AI models.</p><pre>docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main</pre><h3>Option 2: Ollama-WebUI</h3><p>This option is specifically tailored for Ollama.</p><pre>docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v ollama-webui:/app/backend/data --name ollama-webui --restart always ghcr.io/ollama-webui/ollama-webui:main</pre><ul><li>-v ollama-webui:/app/backend/data: Mounts a volume for persistent data storage.</li><li>--restart always: Ensures the container restarts automatically if it stops.</li></ul><p>Open localhost:3000 in your browser, complete the setup to access Ollama model over web ui</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VRyTOx851Fdt7Djoq7Y42A.png" /></figure><h3>Conclusion</h3><p>By following these steps, you’ve successfully set up Ollama to run locally on your machine using Docker. Whether you’re running models directly or interacting through a web interface, you now have a powerful tool at your disposal. Feel free to explore the capabilities of Ollama and experiment with different models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a5bdd90cc20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up Apache Airflow for Local Development]]></title>
            <link>https://khodeprasad.medium.com/setting-up-apache-airflow-for-local-development-ec0fefcb1d4b?source=rss-42d8d94b74ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec0fefcb1d4b</guid>
            <category><![CDATA[data-pipeline-tool]]></category>
            <category><![CDATA[apache-airflow]]></category>
            <category><![CDATA[workflow-automation]]></category>
            <category><![CDATA[airflow-setup]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Prasad Khode]]></dc:creator>
            <pubDate>Thu, 29 Aug 2024 12:17:34 GMT</pubDate>
            <atom:updated>2024-08-29T12:17:34.415Z</atom:updated>
            <content:encoded><![CDATA[<p>In this guide, we’ll walk through setting up Apache Airflow on a local machine using Conda to manage the Python environment.</p><h4>1. Create a Conda Environment</h4><p>First, create a Conda environment that will house the necessary Python libraries for Airflow:</p><pre>conda create -n airflow python=3.11 -y</pre><h4>2. Activate the Conda Environment</h4><p>Once the environment is created, activate it with the following command:</p><pre>conda activate airflow</pre><h4>3. Install Apache Airflow</h4><p>To install Airflow, you’ll need to use a constraints file specific to your Python and Airflow versions. Start by setting up the environment variables and then proceed with the installation:</p><pre>export AIRFLOW_HOME=~/airflow<br><br>AIRFLOW_VERSION=2.10.0<br><br>PYTHON_VERSION=&quot;$(python -c &#39;import sys; print(f&quot;{sys.version_info.major}.{sys.version_info.minor}&quot;)&#39;)&quot;<br><br>CONSTRAINT_URL=&quot;https://raw.githubusercontent.com/apache/airflow/constraints-${AIRFLOW_VERSION}/constraints-${PYTHON_VERSION}.txt&quot;<br><br>pip install &quot;apache-airflow==${AIRFLOW_VERSION}&quot; --constraint &quot;${CONSTRAINT_URL}&quot;</pre><h4>4. Verify the Installation</h4><p>Check if Airflow was installed successfully by running:</p><pre>airflow version</pre><p>You should see output similar to:</p><pre>2.10.0</pre><h4>5. Run Airflow Standalone</h4><p>Start Airflow in standalone mode, which initializes the database, creates a user, and launches all components:</p><pre>airflow standalone</pre><h4>6. Access the Airflow UI</h4><p>To access the Airflow UI, open your web browser and navigate to localhost:8080. You can log in using the admin credentials provided in the terminal when Airflow started. Here, you&#39;ll find the default/example DAGs ready to be explored and tested.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLTldx-YPJu-IdlpsRO5_w.png" /></figure><h4>7. Running Airflow Components Manually</h4><p>If you prefer to run each part of Airflow separately instead of using the all-in-one standalone command, you can do so with the following commands:</p><ol><li>Initialise the database</li><li>Create an admin user</li><li>Start the web server</li><li>Launch the scheduler</li></ol><pre>airflow db migrate<br><br>airflow users create \<br>    --username khodeprasad \<br>    --firstname Prasad \<br>    --lastname Khode \<br>    --role Admin \<br>    --email khodeprasad@test.org<br><br>airflow webserver --port 8080<br><br>airflow scheduler</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec0fefcb1d4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Dynamic JSON Schemas in Apache Spark: A Step-by-Step Guide Using Scala]]></title>
            <link>https://khodeprasad.medium.com/handling-dynamic-json-schemas-in-apache-spark-a-step-by-step-guide-using-scala-7bec1f046999?source=rss-42d8d94b74ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bec1f046999</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-transformation]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[dynamic-schema]]></category>
            <dc:creator><![CDATA[Prasad Khode]]></dc:creator>
            <pubDate>Wed, 21 Aug 2024 11:23:19 GMT</pubDate>
            <atom:updated>2024-08-21T11:23:19.229Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of big data, working with JSON data is a common task. However, handling JSON schemas that may vary or are not predefined can be challenging, especially when working with large datasets in Apache Spark. In this tutorial, I’ll guide you through the process of dynamically inferring and handling JSON schemas using Scala in a Spark environment.</p><h3>Why Dynamic JSON Handling?</h3><p>When processing JSON data in Spark, the schema can either be predefined or inferred. In scenarios where the schema is not known upfront or may vary, dynamically inferring the schema becomes crucial. This approach allows for greater flexibility and reduces the risk of errors related to schema mismatches.</p><h3>Step 1: Setting Up the DataFrame</h3><p>Let’s start by creating a sample DataFrame. Suppose you have a DataFrame with an id and an address column, where address contains a JSON array as a string:</p><pre><br>import org.apache.spark.sql.functions._<br>import org.apache.spark.sql.types._<br><br>// New sample data with varied JSON structures<br>val data = Seq(<br>  (&quot;a1&quot;, &quot;&quot;&quot;[{&quot;address_category&quot;:&quot;Home&quot;,&quot;address_line_1&quot;:&quot;123 Main St&quot;,&quot;pincode&quot;:&quot;10001&quot;,&quot;state_code&quot;:&quot;NY&quot;,&quot;address_type&quot;:&quot;Residential&quot;,&quot;residence_code&quot;:&quot;RC1&quot;}]&quot;&quot;&quot;),<br>  (&quot;b2&quot;, &quot;&quot;&quot;[{&quot;address_category&quot;:&quot;Work&quot;,&quot;address_line_1&quot;:&quot;456 Elm St&quot;,&quot;pincode&quot;:&quot;20002&quot;,&quot;state_code&quot;:&quot;CA&quot;,&quot;address_type&quot;:&quot;Office&quot;,&quot;residence_code&quot;:&quot;RC2&quot;},{&quot;address_category&quot;:&quot;Secondary Home&quot;,&quot;address_line_1&quot;:&quot;789 Oak St&quot;,&quot;pincode&quot;:&quot;30003&quot;,&quot;state_code&quot;:&quot;TX&quot;,&quot;address_type&quot;:&quot;Secondary&quot;,&quot;residence_code&quot;:&quot;RC3&quot;}]&quot;&quot;&quot;),<br>  (&quot;c3&quot;, &quot;&quot;&quot;[{&quot;address_category&quot;:&quot;Permanent&quot;,&quot;address_line_1&quot;:&quot;321 Pine St&quot;,&quot;pincode&quot;:&quot;40004&quot;,&quot;state_code&quot;:&quot;FL&quot;,&quot;address_type&quot;:&quot;Primary&quot;,&quot;enrichMode&quot;:&quot;R&quot;,&quot;residence_code&quot;:&quot;RC4&quot;},{&quot;address_category&quot;:&quot;Vacation Home&quot;,&quot;address_line_1&quot;:&quot;654 Cedar St&quot;,&quot;pincode&quot;:&quot;50005&quot;,&quot;state_code&quot;:&quot;CO&quot;,&quot;address_type&quot;:&quot;Vacation&quot;,&quot;enrichMode&quot;:&quot;R&quot;,&quot;residence_code&quot;:&quot;RC5&quot;}]&quot;&quot;&quot;),<br>  (&quot;d4&quot;, &quot;&quot;&quot;[{&quot;address_category&quot;:&quot;Billing&quot;,&quot;address_line_1&quot;:&quot;987 Birch St&quot;,&quot;pincode&quot;:&quot;60006&quot;,&quot;state_code&quot;:&quot;NV&quot;,&quot;address_type&quot;:&quot;Billing&quot;,&quot;enrichMode&quot;:&quot;M&quot;,&quot;residence_code&quot;:&quot;RC6&quot;},{&quot;address_category&quot;:&quot;Shipping&quot;,&quot;address_line_1&quot;:&quot;321 Spruce St&quot;,&quot;address_line_2&quot;:&quot;Apt 5&quot;,&quot;pincode&quot;:&quot;70007&quot;,&quot;state_code&quot;:&quot;AZ&quot;,&quot;address_type&quot;:&quot;Shipping&quot;,&quot;enrichMode&quot;:&quot;M&quot;,&quot;residence_code&quot;:&quot;RC7&quot;},{&quot;address_category&quot;:&quot;Temporary&quot;,&quot;address_line_1&quot;:&quot;123 Willow St&quot;,&quot;pincode&quot;:&quot;80008&quot;,&quot;state_code&quot;:&quot;WA&quot;,&quot;address_type&quot;:&quot;Temporary&quot;,&quot;enrichMode&quot;:&quot;M&quot;,&quot;residence_code&quot;:&quot;RC8&quot;}]&quot;&quot;&quot;),<br>  (&quot;e5&quot;, &quot;&quot;&quot;[{&quot;address_category&quot;:&quot;Office&quot;,&quot;address_line_1&quot;:&quot;999 Maple St&quot;,&quot;address_line_2&quot;:&quot;Suite 100&quot;,&quot;pincode&quot;:&quot;90009&quot;,&quot;state_code&quot;:&quot;IL&quot;,&quot;address_type&quot;:&quot;Office&quot;,&quot;residence_code&quot;:&quot;RC9&quot;}]&quot;&quot;&quot;)<br>)<br><br>val df = data.toDF(&quot;id&quot;, &quot;address&quot;)<br>df.show(false)</pre><h3>Step 2: Inferring the JSON Schema Dynamically</h3><p>One of the strengths of Spark is its ability to infer schemas on the fly. To handle the JSON data dynamically, we first need to infer the schema from the JSON string:</p><pre>// Infer the schema by selecting the first row<br>val jsonSchema = spark.read.json(df.select(&quot;address&quot;).as[String]).schema<br><br>// Print the inferred schema for verification<br>println(jsonSchema.prettyJson)<br></pre><p>In this step, we read the JSON string from the address column, and Spark automatically infers the schema. This schema is crucial for the next steps, where we&#39;ll parse and explode the JSON data.</p><h3>Step 3: Parsing the JSON Column</h3><p>With the inferred schema in hand, we can now parse the JSON column. This process converts the JSON string into a structured column:</p><pre>// Parse the JSON column using the inferred schema<br>val dfParsed = df.withColumn(&quot;address&quot;, from_json(col(&quot;address&quot;), ArrayType(jsonSchema)))</pre><h3>Step 4: Exploding and Flattening the JSON Data</h3><p>After parsing, the address column is now an array of structs. To work with this data effectively, we need to explode this array into individual rows and flatten the nested fields:</p><pre>// Explode the array of JSON objects into separate rows<br>val dfExploded = dfParsed.withColumn(&quot;address&quot;, explode(col(&quot;address&quot;)))<br><br>// Select and flatten the individual fields<br>val dfFinal = dfExploded.select(<br>  col(&quot;id&quot;),<br>  col(&quot;address.*&quot;)  // This will select all fields from the exploded JSON object<br>)<br><br>// Show the final DataFrame<br>dfFinal.show(false)</pre><p>Result / Output:</p><pre>+---+----------------+--------------+--------------+------------+----------+-------+--------------+----------+<br>|id |address_category|address_line_1|address_line_2|address_type|enrichMode|pincode|residence_code|state_code|<br>+---+----------------+--------------+--------------+------------+----------+-------+--------------+----------+<br>|a1 |Home            |123 Main St   |NULL          |Residential |NULL      |10001  |RC1           |NY        |<br>|b2 |Work            |456 Elm St    |NULL          |Office      |NULL      |20002  |RC2           |CA        |<br>|b2 |Secondary Home  |789 Oak St    |NULL          |Secondary   |NULL      |30003  |RC3           |TX        |<br>|c3 |Permanent       |321 Pine St   |NULL          |Primary     |R         |40004  |RC4           |FL        |<br>|c3 |Vacation Home   |654 Cedar St  |NULL          |Vacation    |R         |50005  |RC5           |CO        |<br>|d4 |Billing         |987 Birch St  |NULL          |Billing     |M         |60006  |RC6           |NV        |<br>|d4 |Shipping        |321 Spruce St |Apt 5         |Shipping    |M         |70007  |RC7           |AZ        |<br>|d4 |Temporary       |123 Willow St |NULL          |Temporary   |M         |80008  |RC8           |WA        |<br>|e5 |Office          |999 Maple St  |Suite 100     |Office      |NULL      |90009  |RC9           |IL        |<br>+---+----------------+--------------+--------------+------------+----------+-------+--------------+----------+</pre><h3>Final Thoughts</h3><p>Handling JSON data with unknown or dynamic schemas is a common requirement when processing large datasets. By dynamically inferring the schema and using Spark’s powerful functions, you can efficiently manage and process JSON data in your Scala-based Spark applications.</p><p>The approach outlined here ensures that you can handle any variations in your JSON data without hardcoding schemas, making your Spark applications more robust and adaptable to changing data structures.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bec1f046999" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Retrieve the Input File Name as a Column Value in Apache Spark]]></title>
            <link>https://khodeprasad.medium.com/how-to-retrieve-the-input-file-name-as-a-column-value-in-apache-spark-ec84cbcf0ef1?source=rss-42d8d94b74ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec84cbcf0ef1</guid>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[datasource]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <dc:creator><![CDATA[Prasad Khode]]></dc:creator>
            <pubDate>Fri, 16 Aug 2024 07:23:00 GMT</pubDate>
            <atom:updated>2024-08-16T07:23:00.078Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with large datasets in Apache Spark, there are scenarios where you might need to identify the origin of each row of data — particularly, the specific file it was read from. This can be crucial for data auditing, debugging, or when dealing with data that has varying schemas or formats.</p><p>In this post, I’ll show you how to easily capture the input file name as a column value while reading data into a Spark DataFrame.</p><h3>The Problem: Identifying the Source File</h3><p>Let’s say you have multiple JSON files stored in a directory, and you’re reading them into a Spark DataFrame for further processing. However, you also need to keep track of which file each row of data originated from. Spark provides a handy function, input_file_name, that lets you achieve this.</p><h3>The Scenario: Multiple Files</h3><p>For this example, suppose you have the following five JSON files:</p><pre>$ ll /Users/prasadkhode/sample_data/<br>-rw-r--r--  1 prasadkhode  staff  1690 Aug 16 12:20 file_1.json<br>-rw-r--r--  1 prasadkhode  staff  1716 Aug 16 12:20 file_2.json<br>-rw-r--r--  1 prasadkhode  staff  1684 Aug 16 12:21 file_3.json<br>-rw-r--r--  1 prasadkhode  staff  1707 Aug 16 12:21 file_4.json<br>-rw-r--r--  1 prasadkhode  staff  1675 Aug 16 12:21 file_5.json</pre><h3>Step 1: Reading the Files</h3><p>First, let’s load these files into a DataFrame using Spark’s read.json method:</p><pre>val df = spark.read.json(&quot;/Users/prasadkhode/sample_data/&quot;)</pre><h3>Step 2: Understanding the Data</h3><p>Let’s check the schema and take a quick look at the data:</p><pre>df.printSchema()<br>df.show(5, false)</pre><p>The schema and sample data might look something like this:</p><pre>root<br> |-- city: string (nullable = true)<br> |-- email: string (nullable = true)<br> |-- first_name: string (nullable = true)<br> |-- gender: string (nullable = true)<br> |-- last_name: string (nullable = true)<br> |-- state: string (nullable = true)<br> |-- username: string (nullable = true)<br> |-- zip: string (nullable = true)<br><br>+------------+------------------------+----------+------+---------+--------------+--------------+-----+<br>|city        |email                   |first_name|gender|last_name|state         |username      |zip  |<br>+------------+------------------------+----------+------+---------+--------------+--------------+-----+<br>|Cranford    |mary_g_perry@gmail.com  |Mary      |F     |Perry    |New Jersey    |shortcushion  |07016|<br>|Carrington  |kdphillips@hotmail.com  |Kevin     |M     |Phillips |North Dakota  |wanderingbooks|58421|<br>|Silver Star |b.f.lewis@live.com      |Brian     |M     |Lewis    |Montana       |prettysnow    |59751|<br>|Charlotte   |e.hall1@rocketmail.com  |Erin      |F     |Hall     |North Carolina|wickedsteam   |28229|<br>|Jacksonville|zacharysmith@hotmail.com|Zachary   |M     |Smith    |Florida       |bigjar        |32214|<br>+------------+------------------------+----------+------+---------+--------------+--------------+-----+</pre><h3>Step 3: Adding the File Name as a Column</h3><p>To append the input file name as a new column to your DataFrame, you can use the input_file_name function from org.apache.spark.sql.functions:</p><p>Now to get the file name as one of the column, we can use the function `input_file_name` from `org.apache.spark.sql.functions` like below</p><pre>import org.apache.spark.sql.functions.input_file_name<br>val dfWithFileName = df.withColumn(&quot;input_file_name&quot;, input_file_name())</pre><p>Now, let’s inspect the DataFrame to see how the new column looks:</p><pre>dfWithFileName.select(&quot;first_name&quot;, &quot;last_name&quot;, &quot;gender&quot;, &quot;username&quot;, &quot;input_file_name&quot;).show(false)</pre><p>Here’s an example of the output:</p><pre>+----------+---------+------+----------------+-------------------------------------------------+<br>|first_name|last_name|gender|username        |input_file_name                                  |<br>+----------+---------+------+----------------+-------------------------------------------------+<br>|Mary      |Perry    |F     |shortcushion    |file:///Users/prasadkhode/sample_data/file_2.json|<br>|Kevin     |Phillips |M     |wanderingbooks  |file:///Users/prasadkhode/sample_data/file_2.json|<br>|Brian     |Lewis    |M     |prettysnow      |file:///Users/prasadkhode/sample_data/file_2.json|<br>|Erin      |Hall     |F     |wickedsteam     |file:///Users/prasadkhode/sample_data/file_2.json|<br>|Zachary   |Smith    |M     |bigjar          |file:///Users/prasadkhode/sample_data/file_2.json|<br>|Steven    |Coleman  |M     |mellowforce     |file:///Users/prasadkhode/sample_data/file_2.json|<br>|Allison   |Phillips |F     |absentnote      |file:///Users/prasadkhode/sample_data/file_2.json|<br>|Lauren    |Brooks   |F     |animatedcrate   |file:///Users/prasadkhode/sample_data/file_2.json|<br>|Joseph    |Flores   |M     |steadyhope      |file:///Users/prasadkhode/sample_data/file_2.json|<br>|Anna      |Roberts  |F     |absentroof      |file:///Users/prasadkhode/sample_data/file_2.json|<br>|Eric      |Baker    |M     |lackinghope     |file:///Users/prasadkhode/sample_data/file_4.json|<br>|Kimberly  |Alexander|F     |chemicalthumb   |file:///Users/prasadkhode/sample_data/file_4.json|<br>|Eric      |Allen    |M     |greenairplane   |file:///Users/prasadkhode/sample_data/file_4.json|<br>|Sophia    |Carter   |F     |jazzyjewel      |file:///Users/prasadkhode/sample_data/file_4.json|<br>|Haley     |Brown    |F     |certaintomatoes |file:///Users/prasadkhode/sample_data/file_4.json|<br>|Abigail   |Coleman  |F     |damphook        |file:///Users/prasadkhode/sample_data/file_4.json|<br>|Sophia    |Robinson |F     |stormyactivity  |file:///Users/prasadkhode/sample_data/file_4.json|<br>|Ethan     |Wilson   |M     |hurriedsilk     |file:///Users/prasadkhode/sample_data/file_4.json|<br>|Michael   |Butler   |M     |clutteredchicken|file:///Users/prasadkhode/sample_data/file_4.json|<br>|Erin      |Brown    |F     |highfalutinjewel|file:///Users/prasadkhode/sample_data/file_4.json|<br>+----------+---------+------+----------------+-------------------------------------------------+</pre><h3>Step 4: Checking Distinct File Names</h3><p>To verify that the DataFrame includes data from all your files, you can check the distinct file names:</p><pre>dfWithFileName.select(&quot;input_file_name&quot;).distinct.show(false)</pre><p>Output:</p><pre>+-------------------------------------------------+<br>|input_file_name                                  |<br>+-------------------------------------------------+<br>|file:///Users/prasadkhode/sample_data/file_2.json|<br>|file:///Users/prasadkhode/sample_data/file_4.json|<br>|file:///Users/prasadkhode/sample_data/file_1.json|<br>|file:///Users/prasadkhode/sample_data/file_3.json|<br>|file:///Users/prasadkhode/sample_data/file_5.json|<br>+-------------------------------------------------+</pre><h3>Conclusion</h3><p>Using the input_file_name function in Spark is a straightforward way to track the source of each row of data in a DataFrame, particularly when working with multiple files. This can be an essential technique for ensuring data integrity, debugging, or handling diverse datasets with ease.</p><p>Now you can confidently identify the origin of every piece of data you process in Spark, ensuring that your data pipelines are as transparent and traceable as possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec84cbcf0ef1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding External and Maven JARs to Spark Shell for Ad-Hoc Analysis]]></title>
            <link>https://khodeprasad.medium.com/adding-external-and-maven-jars-to-spark-shell-for-ad-hoc-analysis-28d6fa1ae637?source=rss-42d8d94b74ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/28d6fa1ae637</guid>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[jar]]></category>
            <category><![CDATA[spark-shell]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[Prasad Khode]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 11:08:54 GMT</pubDate>
            <atom:updated>2024-08-13T11:08:54.694Z</atom:updated>
            <content:encoded><![CDATA[<p>When performing ad-hoc data analysis using Apache Spark, you may encounter situations where you need additional libraries to process your data. These libraries could be external JARs available from Maven repositories or custom JARs that you’ve developed locally. In this post, we’ll walk through how to add both types of JARs to your Spark shell session.</p><h4>Adding a Maven JAR</h4><p>Let’s start with an example where we need to include a library that is available in Maven. We’ll use the org.mongodb.bson library as our example, which is available on <a href="https://mvnrepository.com/artifact/org.mongodb/bson/5.1.3">Maven Central</a>. The SBT dependency for this library looks like this:</p><pre>// https://mvnrepository.com/artifact/org.mongodb/bson<br>libraryDependencies += &quot;org.mongodb&quot; % &quot;bson&quot; % &quot;5.1.3&quot;</pre><p>To include this Maven JAR in your Spark shell session, you can use the --packages option. The format for specifying a Maven package is &lt;groupId&gt;:&lt;artifactId&gt;:&lt;version&gt;. Here’s how you can start the Spark shell with the org.mongodb.bson package included:</p><pre>spark-shell --master spark://$(hostname -f):7077 \<br> --driver-memory 4G --executor-memory 4G \<br> --executor-cores 2 --total-executor-cores 4 \<br> --packages org.mongodb:bson:5.1.3</pre><p>Once you execute this command, the Spark shell will resolve the dependency and download the required JAR. You’ll see output similar to this in your terminal:</p><pre>:: loading settings :: url = jar:file:/e2deepde/spark-3.4.1-bin-hadoop3/jars/ivy-2.5.1.jar!/org/apache/ivy/core/settings/ivysettings.xml<br>Ivy Default Cache set to: /home/deuser/.ivy2/cache<br>The jars for the packages stored in: /home/deuser/.ivy2/jars<br>org.mongodb#bson added as a dependency<br>:: resolving dependencies :: org.apache.spark#spark-submit-parent-0d4af84f-28c1-4692-937e-7f9b9b405559;1.0<br> confs: [default]<br> found org.mongodb#bson;5.1.3 in central<br>downloading https://repo1.maven.org/maven2/org/mongodb/bson/5.1.3/bson-5.1.3.jar ...<br> [SUCCESSFUL ] org.mongodb#bson;5.1.3!bson.jar (813ms)<br>:: resolution report :: resolve 903ms :: artifacts dl 816ms<br> :: modules in use:<br> org.mongodb#bson;5.1.3 from central in [default]<br> ---------------------------------------------------------------------<br> |                  |            modules            ||   artifacts   |<br> |       conf       | number| search|dwnlded|evicted|| number|dwnlded|<br> ---------------------------------------------------------------------<br> |      default     |   1   |   1   |   1   |   0   ||   1   |   1   |<br> ---------------------------------------------------------------------<br>:: retrieving :: org.apache.spark#spark-submit-parent-0d4af84f-28c1-4692-937e-7f9b9b405559<br> confs: [default]<br> 1 artifacts copied, 0 already retrieved (496kB/5ms)</pre><p>This output confirms that the Spark shell has successfully downloaded the Maven artifact, and you can now use the org.mongodb.bson library within your Spark session.</p><h4>Adding a Local JAR</h4><p>If you have a JAR file that you’ve developed locally, or one that isn’t available on Maven, you can add it to your Spark shell using the --jars option. This option allows you to specify the full path to your JAR files. Here’s an example:</p><pre>spark-shell --master spark://$(hostname -f):7077 \<br> --driver-memory 4G --executor-memory 4G \<br> --executor-cores 2 --total-executor-cores 4 \<br> --jars ~/local_jars/*.jar</pre><p>If you need to add multiple JAR files, you can separate them with a comma:</p><pre>spark-shell --master spark://$(hostname -f):7077 \<br> --driver-memory 4G --executor-memory 4G \<br> --executor-cores 2 --total-executor-cores 4 \<br> --packages org.mongodb:bson:5.1.3,org.json:json:20240303 \<br> --jars ~/local_jars/*.jar,~/other_jars/*.jar</pre><p>This approach gives you the flexibility to include any JARs necessary for your analysis, whether they are external libraries or custom implementations.</p><h4>Conclusion</h4><p>Adding external or local JARs to your Spark shell session is straightforward and allows you to extend the capabilities of Spark for ad-hoc analysis. By using the --packages option for Maven JARs and the --jars option for local files, you can seamlessly integrate additional libraries into your Spark environment, enabling more robust and flexible data processing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28d6fa1ae637" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Invalid Column Names in Spark: A Step-by-Step Guide]]></title>
            <link>https://khodeprasad.medium.com/handling-invalid-column-names-in-spark-a-step-by-step-guide-de8583ea67f0?source=rss-42d8d94b74ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/de8583ea67f0</guid>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[invalid-column]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <dc:creator><![CDATA[Prasad Khode]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 10:40:30 GMT</pubDate>
            <atom:updated>2024-08-12T10:42:46.639Z</atom:updated>
            <content:encoded><![CDATA[<p>In data processing, it’s common to encounter files where the first line contains invalid or dummy column names, which can disrupt the reading of data into a structured format. This post explores how to handle such scenarios using Apache Spark.</p><h3>The Problem: Dummy Column Names</h3><p>Consider the following input file:</p><pre>DummyCol1,DummyCol2<br>EmployeeId,LastName,FirstName,Title<br>1,Adams,Andrew,General Manager<br>2,Edwards,Nancy,Sales Manager<br>3,Peacock,Jane,Sales Support Agent<br>4,Park,Margaret,Sales Support Agent<br>5,Johnson,Steve,Sales Support Agent<br>6,Mitchell,Michael,IT Manager<br>7,King,Robert,IT Staff<br>8,Callahan,Laura,IT Staff</pre><p>In this file, the actual column names start from the second row. The first row contains dummy columns that aren’t useful and can cause issues when reading the file into a DataFrame in Spark.</p><h3>Attempting to Read the File</h3><p>Let’s first see what happens when we try to read this file directly using Spark’s csv reader:</p><pre>val df = spark.read.csv(&quot;data_dump.csv&quot;)<br>df.show()</pre><p>The resulting DataFrame might look like this:</p><pre>+----------+---------+<br>|       _c0|      _c1|<br>+----------+---------+<br>| DummyCol1|DummyCol2|<br>|EmployeeId| LastName|<br>|         1|    Adams|<br>|         2|  Edwards|<br>|         3|  Peacock|<br>|         4|     Park|<br>|         5|  Johnson|<br>|         6| Mitchell|<br>|         7|     King|<br>|         8| Callahan|<br>+----------+---------+</pre><p>As you can see, Spark has incorrectly inferred the schema, leading to only two columns being read, with the actual data not being properly parsed.</p><h3>The Solution: Custom Handling of Column Names</h3><p>To correctly read all the columns and ignore the dummy ones, you can follow these steps:</p><ol><li><strong>Read the Entire File as Text</strong>: First, read the file as a text file so that each line is treated as a single string.</li><li><strong>Generate Row IDs</strong>: Add a unique identifier to each row using monotonically_increasing_id.</li><li><strong>Extract and Set Correct Column Names</strong>: Use the second row to extract the actual column names.</li><li><strong>Split the Data into Columns</strong>: Finally, split each line into columns based on commas and apply the correct column names.</li></ol><p>Here’s how you can implement this in Spark:</p><pre>import org.apache.spark.sql.functions._<br><br>val df = spark.read.text(&quot;data_dump.csv&quot;).withColumn(&quot;row_id&quot;,monotonically_increasing_id)<br><br>val cols=df.select(&quot;value&quot;).filter($&quot;row_id&quot;===1).first.mkString.split(&quot;,&quot;)  <br><br>val df2 = df.filter($&quot;row_id&quot;&gt;1).withColumn(&quot;temp&quot;, split(col(&quot;value&quot;), &quot;,&quot;)).<br> select((0 until cols.length).map(i =&gt; col(&quot;temp&quot;).getItem(i).as(cols.apply(i))): _*)<br><br>df2.show()</pre><h3>Final Output</h3><p>The final DataFrame, after applying the above steps, will look like this:</p><pre>+----------+--------+---------+-------------------+<br>|EmployeeId|LastName|FirstName|              Title|<br>+----------+--------+---------+-------------------+<br>|         1|   Adams|   Andrew|    General Manager|<br>|         2| Edwards|    Nancy|      Sales Manager|<br>|         3| Peacock|     Jane|Sales Support Agent|<br>|         4|    Park| Margaret|Sales Support Agent|<br>|         5| Johnson|    Steve|Sales Support Agent|<br>|         6|Mitchell|  Michael|         IT Manager|<br>|         7|    King|   Robert|           IT Staff|<br>|         8|Callahan|    Laura|           IT Staff|<br>+----------+--------+---------+-------------------+</pre><h3>Conclusion</h3><p>By reading the file as text and manually processing the first few lines, you can effectively handle files with invalid or dummy column names in Spark. This method ensures that your DataFrame accurately represents the data, with all columns properly named and parsed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de8583ea67f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>