<?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 Samhitha Poreddy on Medium]]></title>
        <description><![CDATA[Stories by Samhitha Poreddy on Medium]]></description>
        <link>https://medium.com/@samhitha.lfa54?source=rss-a8a22b5bf23c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WQpr_goz0pbp4Qv97dIrxg@2x.jpeg</url>
            <title>Stories by Samhitha Poreddy on Medium</title>
            <link>https://medium.com/@samhitha.lfa54?source=rss-a8a22b5bf23c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 13:58:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samhitha.lfa54/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[Designing an SLA-aware incident monitoring pipeline using Kafka]]></title>
            <link>https://medium.com/towards-data-engineering/designing-an-sla-aware-incident-monitoring-pipeline-using-kafka-93ab6c614f64?source=rss-a8a22b5bf23c------2</link>
            <guid isPermaLink="false">https://medium.com/p/93ab6c614f64</guid>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[incident-management]]></category>
            <category><![CDATA[streaming]]></category>
            <dc:creator><![CDATA[Samhitha Poreddy]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 16:06:09 GMT</pubDate>
            <atom:updated>2026-01-23T05:12:42.410Z</atom:updated>
            <content:encoded><![CDATA[<h4>From scattered logs to a unified, real‑time alerting backbone for your services</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*k8XjwkFzsksInniKF34LPw.png" /></figure><p>Recently, I began learning Apache Kafka to deepen my understanding of real-time streaming systems and how event-driven pipelines are designed in practice. As data engineers, most of us have experienced production failures — often at the worst possible times. While failures are inevitable, delayed detection and fragmented visibility are not. Different teams rely on different tools for metrics, logs, and alerts, often resulting in slow response times, noisy notifications, and unclear ownership.</p><p>In this article, I want to explore how an SLA-aware incident monitoring pipeline, built on Kafka, can provide a unified, real-time backbone for operational signals — enabling faster detection, safer alerting, and better reliability.</p><p><strong>The Problem: SLAs without real‑time visibility:</strong></p><p>Service Level Agreements (SLAs) and Service Level Objectives (SLOs) define the expectations we set for reliability, latency, and availability. However, in many production environments, these promises exist only on paper. The core issue is not the absence of monitoring tools, but the lack of real-time, unified visibility across systems.</p><p>Typical pain points today:</p><ul><li>Metrics in one system, logs in another, incidents in a third.</li><li>Alerts firing too late or too noisy.</li><li>No single stream of truth for what is happening across services.</li></ul><h4>Requirements:</h4><p>In production, failures aren’t the problem — <em>late detection is</em>. What the pipeline must do:</p><ul><li>Continuously ingest SLA‑relevant signals: latency, error rates, job status, Kafka lag, infra metrics.</li><li>Detect SLA breaches and risky trends in near real time, not via hourly batch checks.</li><li>Route normalized incident events to alerting tools and analytics with minimal loss and the ability to replay.​</li></ul><p>We want all SLA‑relevant signals to flow as events through a central streaming bus.</p><p>To meet these requirements, the following Kafka‑centric architecture ties our signals together. Kafka can act as a central event bus for metrics, incidents, and SLA violations, enabling fan-out, backpressure, and reliable alerting without overwhelming downstream systems. The architecture diagram below shows how these pieces fit together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vagi-yoHS4pCmFBG0aTlYA.jpeg" /></figure><h3>How the pipeline works end‑to‑end</h3><ol><li>Producers: emitting SLA signals<br>Each service and platform component continuously emits signals about its health: microservice latency and error metrics, batch job success/failure events, Kafka consumer lag, and infrastructure metrics like CPU and disk usage. These signals are produced as small, structured events so they can be routed and processed consistently across the platform.​</li><li>Kafka topics: the event backbone<br>All signals land on a set of well‑named Kafka topics such as service.metrics.raw, job.status.events, consumer.lag.events, and incident.signals. Kafka becomes the shared “nervous system” for reliability data, allowing multiple downstream consumers (alerting, dashboards, storage) to tap into the same real‑time feed without coupling directly to each service.​</li><li>Stream processing and SLA evaluation<br>A streaming application continuously aggregates metrics in time windows, evaluates them against SLO thresholds, scores severity, and de‑duplicates or suppresses noisy events. When an SLI crosses a threshold or an incident pattern is detected, the job emits normalized incident events (for example, alerts.dispatch or incident.tickets) back into Kafka.​<em> </em>For instance <em>(Metrics → SLIs → evaluated against SLOs → incidents/alerts → SLA impact)</em></li><li>Outputs and consumers: where action happens<br>Dedicated consumers subscribe to these alert and incident topics: one pushes notifications to Teams or on‑call pagers, another opens or updates tickets in Jira, others update dashboards and archive data to S3 or Snowflake for later analysis. Because everything flows through Kafka, new tools can be added — like anomaly‑detection services or audit stores — simply by subscribing to the existing topics, without changing the producers.​</li></ol><p><strong>Why this matters for SLAs </strong><br>Instead of scattered logs and siloed dashboards, the team gets a single, streaming view of system health and SLA status, with alerts triggered as soon as metrics drift out of bounds. This reduces detection time for incidents and makes post‑mortems easier, because every signal and alert is captured as an event in the same pipeline.​</p><p><strong>Why Kafka is a good fit for this pipeline</strong></p><p>Kafka is a good fit because it turns all SLA‑relevant signals (metrics, job status, consumer lag, infra health) into durable, ordered event streams that many tools can consume in parallel, without tight coupling between services and alerting systems. Its ability to buffer spikes, scale horizontally, and replay historical events lets you handle incident storms safely and reprocess data later to tune thresholds and improve detection quality</p><p>In this article, the focus was on the <em>why</em> and the <em>high‑level architecture</em> of an SLA‑aware incident monitoring pipeline using Kafka. In Part 2, the plan is to bring this design to life and share a GitHub repo with a minimal implementation and sample dashboards</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93ab6c614f64" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/designing-an-sla-aware-incident-monitoring-pipeline-using-kafka-93ab6c614f64">Designing an SLA-aware incident monitoring pipeline using Kafka</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IPL Data Analysis: ETL with Spark]]></title>
            <link>https://medium.com/towards-data-engineering/ipl-data-analysis-etl-with-spark-16559f549047?source=rss-a8a22b5bf23c------2</link>
            <guid isPermaLink="false">https://medium.com/p/16559f549047</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Samhitha Poreddy]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 22:42:07 GMT</pubDate>
            <atom:updated>2024-10-15T17:09:19.626Z</atom:updated>
            <content:encoded><![CDATA[<p>Are you a cricket enthusiast looking to dive into data analytics? Or perhaps a data professional interested in mastering complex transformations and basic predictive analysis with Spark? If so, this article is for you! Sparked by a recent YouTube video by Manoj T, I decided to explore IPL data in greater depth and offer valuable insights on building a “Match Dynamics and Patterns” analysis using Databricks and Spark. Here, we’ll focus on key phases of a cricket match, such as Powerplays, Middle, and Death overs, to reveal patterns that often correlate with winning performances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*HqmNgNrIlNeYvEQZfulGPg.png" /></figure><h3><strong>Match Dynamics and Patterns</strong></h3><p>In any cricket match, certain phases can significantly impact the outcome. Powerplays, where teams aim to score quickly, Middle overs, where teams balance scoring and risk, and Death overs, known for high-stake runs and wicket losses, each play unique roles. This article walks you through creating a data frame for each phase, exploring scoring patterns and wicket loss rates, and evaluating their impact on match outcomes.</p><p>To start, build a data frame to study different teams’ scoring patterns and wicket loss rates. I’ve started by extracting CSV data and loading it into the Databricks DBFS folder.</p><pre>from pyspark.sql import SparkSession<br><br># Initialize Spark session<br>spark = SparkSession.builder.appName(&quot;IPLDataAnalysis&quot;).getOrCreate()<br><br># Load the data<br>ipl_df = spark.read.csv(&quot;dbfs:/FileStore/ipl_data.csv&quot;,header=True,inferSchema=True)</pre><p>Now, Define these phases within your DataFrame and Calculate Runs and Wickets per Phase</p><p>Segment the overs into match phases:</p><p>Powerplay Overs: Generally, overs 0–6.</p><p>Middle Overs: Typically overs 7–15.</p><p>Death Overs: Usually overs 16–20.</p><pre>from pyspark.sql import functions as F<br><br># Add phase column based on over number<br>MatchPhases_df = ipl_df.withColumn(<br>    &quot;phase&quot;,<br>    F.when((ipl_df[&#39;over&#39;] &gt;= 0) &amp; (ipl_df[&#39;over&#39;] &lt;= 6), &quot;Powerplay&quot;)<br>    .when((ipl_df[&#39;over&#39;] &gt;= 7) &amp; (ipl_df[&#39;over&#39;] &lt;= 15), &quot;Middle&quot;)<br>    .when((ipl_df[&#39;over&#39;] &gt;= 16) &amp; (ipl_df[&#39;over&#39;] &lt;= 20), &quot;Death&quot;)<br>)<br><br>phase_metrics = MatchPhases_df.groupBy(&quot;match_id&quot;, &quot;batting_team&quot;, &quot;phase&quot;) \<br>                  .agg(F.sum(&quot;total_runs&quot;).alias(&quot;total_runs&quot;),<br>                       F.sum(when(col(&quot;is_wicket&quot;) == 1, 1).otherwise(0)).alias(&quot;total_wickets&quot;)<br>                       )\<br>                  .withColumnRenamed(&quot;batting_team&quot;, &quot;team&quot;)</pre><p>Now that we’ve calculated the metrics for each phase, let’s create a table summarizing match results and determine the winning team.</p><pre>from pyspark.sql import functions as F<br><br># Calculate total runs per team per match<br>team_scores = ipl_df.groupBy(&quot;match_id&quot;, &quot;inning&quot;, &quot;batting_team&quot;) \<br>                    .agg(F.sum(&quot;total_runs&quot;).alias(&quot;team_total_runs&quot;))<br><br># Pivot to get both innings in the same row for comparison<br>match_totals = team_scores.groupBy(&quot;match_id&quot;) \<br>                          .pivot(&quot;inning&quot;) \<br>                          .agg(F.first(&quot;batting_team&quot;).alias(&quot;team&quot;),<br>                               F.first(&quot;team_total_runs&quot;).alias(&quot;total_runs&quot;))<br><br># Rename columns for clarity<br>match_totals = match_totals.withColumnRenamed(&quot;1_team&quot;, &quot;team1&quot;) \<br>                           .withColumnRenamed(&quot;1_total_runs&quot;, &quot;team1_runs&quot;) \<br>                           .withColumnRenamed(&quot;2_team&quot;, &quot;team2&quot;) \<br>                           .withColumnRenamed(&quot;2_total_runs&quot;, &quot;team2_runs&quot;)<br><br># Determine the winning team<br>match_results = match_totals.withColumn(<br>    &quot;winning_team&quot;,<br>    F.when(F.col(&quot;team1_runs&quot;) &gt; F.col(&quot;team2_runs&quot;), F.col(&quot;team1&quot;))<br>     .when(F.col(&quot;team2_runs&quot;) &gt; F.col(&quot;team1_runs&quot;), F.col(&quot;team2&quot;))<br>     .otherwise(&quot;Tie&quot;)<br>).select(&quot;match_id&quot;, &quot;team1&quot;, &quot;team1_runs&quot;, &quot;team2&quot;, &quot;team2_runs&quot;, &quot;winning_team&quot;)<br></pre><p>With the match_results table ready, we can now join it with phase_metrics to analyze how performances in different phases impact the match results.</p><pre># Join phase_metrics with match_results to evaluate winning patterns<br>phase_with_results = phase_metrics.join(match_results, on=&quot;match_id&quot;)<br><br># Filter for phases where the team was the winning team<br>winning_phase_metrics = phase_with_results.filter(phase_with_results.team == phase_with_results.winning_team)</pre><h3><strong>Insights and Analysis by Phase</strong></h3><h4>Powerplay Effectiveness</h4><p>To measure Powerplay effectiveness, analyze if teams scoring more runs in the Powerplay phase have a higher winning probability.</p><pre># Filter for Powerplay phase and calculate average runs in Powerplay for winning teams<br>powerplay_insights = phase_with_results.filter(phase_with_results.phase == &quot;Powerplay&quot;) \<br>                                       .groupBy(&quot;winning_team&quot;) \<br>                                       .agg(F.avg(&quot;total_runs&quot;).alias(&quot;avg_powerplay_runs&quot;),<br>                                            F.count(&quot;match_id&quot;).alias(&quot;matches_won&quot;))<br><br># Calculate average Powerplay runs across all teams for comparison<br>overall_powerplay = phase_with_results.filter(phase_with_results.phase == &quot;Powerplay&quot;) \<br>                                      .agg(F.avg(&quot;total_runs&quot;).alias(&quot;overall_avg_powerplay_runs&quot;))</pre><p>Interpretation: If avg_powerplay_runs is consistently higher for winning teams compared to overall_avg_powerplay_runs, then Powerplay scoring has a positive impact on winning probability.</p><h4>Death Over Impact</h4><p>To evaluate if high scores in Death overs lead to a higher winning probability, examine runs scored in the Death phase for winning teams.</p><pre>death_over_insights = phase_with_results.filter(phase_with_results.phase==&quot;death&quot;)\<br>                                        .groupBy(&quot;winning_team&quot;)\<br>                                        .agg(F.avg(&quot;total_runs&quot;).alias(&quot;avg_death_over_runs&quot;),<br>                                            F.count(&quot;match_id&quot;).alias(&quot;matches_won&quot;))<br># Calculate a benchmark score that typically indicates a strong finish<br>benchmark_death_score = 30  # (or any relevant threshold based on data)<br><br># Filter instances where teams scored above this benchmark in Death overs<br>death_over_above_threshold = phase_with_results.filter((phase_with_results.phase == &quot;Death&quot;) &amp; <br>                                                       (phase_with_results.total_runs &gt;= benchmark_death_score)) \<br>                                               .groupBy(&quot;winning_team&quot;) \<br>                                               .count().alias(&quot;high_death_over_count&quot;)</pre><p>Interpretation: Check if avg_death_over_runs is generally higher among winning teams, and if exceeding the benchmark consistently correlates with match wins.</p><h4>Risk Factor in Middle Overs</h4><p>Analyze if a steady middle phase (fewer wickets) results in higher match wins by observing wickets lost in the Middle phase for winning vs. losing teams.</p><pre># Filter for Middle phase and calculate average wickets lost for winning teams<br>middle_overs_insights = phase_with_results.filter(phase_with_results.phase == &quot;Middle&quot;) \<br>                                          .groupBy(&quot;winning_team&quot;) \<br>                                          .agg(F.avg(&quot;total_wickets&quot;).alias(&quot;avg_middle_wickets&quot;),<br>                                               F.count(&quot;match_id&quot;).alias(&quot;matches_won&quot;))<br><br># Calculate average wickets lost by all teams for reference<br>overall_middle_wickets = phase_with_results.filter(phase_with_results.phase == &quot;Middle&quot;) \<br>                                           .agg(F.avg(&quot;total_wickets&quot;).alias(&quot;overall_avg_middle_wickets&quot;))</pre><p>Interpretation: If winning teams tend to lose fewer wickets on average than the overall team benchmark, then maintaining stability in the Middle overs impacts match outcomes positively.</p><h3>Conclusion</h3><p>Through this analysis, we’ve uncovered valuable insights into how different phases influence match outcomes. Key findings suggest:</p><ul><li>Higher scores in Powerplay and Death overs positively impact the probability of winning.</li><li>Minimizing wicket loss in the Middle overs can also play a significant role in determining the outcome.</li></ul><p>These insights can help teams devise strategies around phase-based performance metrics, potentially enhancing their winning probabilities.</p><p>Thanks for reading. Have a good day!</p><p>I hope you find this article helpful! 😊I’d love to hear your thoughts on applying data analytics to sports!</p><p><strong>Connect with me on LinkedIn:</strong></p><p><a href="https://www.linkedin.com/in/samhitha-poreddy/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16559f549047" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/ipl-data-analysis-etl-with-spark-16559f549047">IPL Data Analysis: ETL with Spark</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Engaging with Upstream Stakeholders Matters in Data Engineering]]></title>
            <link>https://medium.com/towards-data-engineering/why-engaging-with-upstream-stakeholders-matters-in-data-engineering-35dc28ebc7d8?source=rss-a8a22b5bf23c------2</link>
            <guid isPermaLink="false">https://medium.com/p/35dc28ebc7d8</guid>
            <category><![CDATA[collaboration]]></category>
            <category><![CDATA[data-ingestion]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Samhitha Poreddy]]></dc:creator>
            <pubDate>Sun, 06 Oct 2024 14:23:50 GMT</pubDate>
            <atom:updated>2024-10-10T14:58:59.514Z</atom:updated>
            <content:encoded><![CDATA[<p>How often have unexpected job failures or data quality issues caught you off guard because of unplanned changes from upstream sources? Such surprises often arise because of a lack of consistent communication.</p><p>As data engineers, we play a crucial role in transforming raw data into high-quality, consistent information for end users. Our job involves collecting data from various sources, performing data transformations, and delivering the refined data to downstream users. Throughout my journey, I’ve learned that building a reliable data pipeline requires proactive engagement not only with downstream users but also with upstream stakeholders, the people behind the data sources. In this article, I’ll share my learnings about the significance of interacting with upstream stakeholders to build a more robust data ingestion process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1TEYODWJHeDV9z-I" /><figcaption>Photo by <a href="https://unsplash.com/@m_accelerator?utm_source=medium&amp;utm_medium=referral">M ACCELERATOR</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong><em>Are we engaging with upstream stakeholders effectively?</em></strong></p><p>I’ve realized that it’s crucial to consider the needs of downstream users(business analysts, stakeholders, and data scientists) to whom we deliver the data. Engaging with upstream users who provide the raw data is equally important. This interaction is essential for establishing a strong foundation for your data storage layer.</p><p><strong><em>The Road Trip Analogy:</em></strong></p><p>Imagine you’re planning a road trip with friends. Without discussing the route or weather conditions, you set off without a map, supplies, or even checking the road closures ahead. As you drive, you suddenly hit a detour because of road construction you didn’t know about, forcing you to find an alternative route, which adds hours to your journey. You also didn’t pack extra water or fuel, so now everyone is uncomfortable and anxious about reaching the destination.</p><p>Now, let’s say you planned this trip by collaborating with locals and checking the route ahead. You’d know about potential roadblocks, rest stops, and where to refuel, allowing you to reach your destination smoothly and without unexpected stops.</p><p>In data ingestion, upstream stakeholders are like the locals who know the lay of the land. Without interacting with them, data pipelines can hit unforeseen roadblocks (schema changes, outages) that lead to production failures or delays. But with a solid interaction, you get a roadmap, ensuring smoother, more reliable data flow and fewer surprises along the way.</p><p><strong>Identifying Key Stakeholders?</strong></p><p>Upstream stakeholders are those responsible for developing and maintaining the source systems from which you ingest raw data. Your upstream stakeholders are often the software engineers who build the source system you’re working with. They can also be product managers with a holistic view of the product, including upcoming changes that could affect data collection. Sometimes, these stakeholders can also be DBAs and compliance teams as well.</p><p><strong>Benefits of Engaging with Source Owners:</strong></p><p>You will understand the volume, frequency, format, data security, and regulatory compliance information that might impact the data engineering lifecycle.</p><p>Some of the high-level questions that you can start considering asking your Source owners are:</p><ol><li>What is the data generation process?</li></ol><p>This helps you understand how data flows within the source system and whether there are any dependencies or potential bottlenecks in the source system that may affect your ingestion process.</p><p>2. What is the expected volume and growth of data?</p><p>This question helps you anticipate scale and ensure that your data ingestion solution is future-proof for larger datasets.</p><p>3. Are there any upcoming changes to the system or product?</p><p>Knowing this helps you prepare for updates that could impact schema, format, or the data itself. You can anticipate the need for flexibility in your pipeline by understanding how dynamic the source system is, so you can set up monitoring for schema drift or breaking changes.</p><p>4. How frequently is the data updated, and what’s the latency expectation?</p><p>This helps you plan for near real-time or batch processing, based on how fast data is produced and how soon your downstream stakeholders expect it to be available.</p><p>5. What are the failure and recovery mechanisms for the source system?</p><p>Understanding this allows you to build redundancy and fault-tolerance into your pipeline. You’ll know how often failures occur and how they are handled by the upstream system.</p><p>6. What are the compliance or data security requirements?</p><p>This ensures you capture all necessary regulations and guidelines right from the source, such as HIPAA, or industry-specific security protocols.</p><p>7. Who are the key contacts in case of emergencies or issues?</p><p>This question helps establish a communication line in case of data outages or unexpected changes to the system.</p><p>8. What tools or APIs are available for data extraction?</p><p>This is vital for understanding how you can access data — whether through APIs, direct database queries, or file-based transfers (like CSV or JSON)</p><p>9. How does the data lifecycle work from creation to retirement?</p><p>Understanding this allows you to track the data’s validity period, whether retention policies are in place, and when it is archived, deleted, or modified.</p><p><strong>A Lesson in Compliance:</strong></p><p>Sharing one failure that I have faced as part of my journey. I had a requirement to ingest a table into my data warehouse. Unfortunately, I had ingested sensitive information without the required encryption, leading to compliance issues and potential legal consequences. If I had stayed in touch with compliance and upstream teams, I would have been notified about the new data privacy requirements. I would implement the necessary encryption and privacy measures in my pipeline well in advance, ensuring that all data is securely handled and meet regulatory standards.</p><p>Building awareness around the importance of proactive collaboration with upstream stakeholders is crucial for avoiding these kinds of issues. This shared awareness can mean the difference between smooth data pipelines and disruptive downtime, allowing us to focus on delivering valuable insights rather than firefighting preventable issues.</p><p>I encourage you all to examine your own data pipeline practices. Proactive collaboration with upstream stakeholders can make all the difference in avoiding preventable issues and keeping the data flowing smoothly.</p><p>I really hope you find this article helpful! 😊</p><p><strong>Connect with me on LinkedIn:</strong></p><p><a href="https://www.linkedin.com/in/samhitha-poreddy/">LinkedIn</a></p><p><strong>Further Reading:</strong></p><ul><li>Fundamentals of Data Engineering by <a href="https://www.oreilly.com/search?q=author:%22Joe%20Reis%22">Joe Reis</a>, <a href="https://www.oreilly.com/search?q=author:%22Matt%20Housley%22">Matt Housley</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35dc28ebc7d8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/why-engaging-with-upstream-stakeholders-matters-in-data-engineering-35dc28ebc7d8">Why Engaging with Upstream Stakeholders Matters in Data Engineering</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Find me a Job Social Network Schema using SQL Graph Databases]]></title>
            <link>https://medium.com/learning-sql/find-me-a-job-social-network-schema-using-sql-graph-databases-dd8ddc67ce6f?source=rss-a8a22b5bf23c------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd8ddc67ce6f</guid>
            <category><![CDATA[graph-database]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Samhitha Poreddy]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 01:22:20 GMT</pubDate>
            <atom:updated>2024-09-25T16:57:36.006Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will discuss how to use a graph database as a powerful recommendation engine for job seekers. We will start by defining a problem statement, creating a graph schema, and using the MATCH function to build queries that offer valuable job recommendations based on factors such as user skills, connections, and locations.</p><h4><strong>What is a Graph Database?</strong></h4><p>A graph database allows for the storage of relationships between data points, enabling users to connect various pieces of related data. This provides valuable insights and enhances operational flexibility. Graph databases are ideal for applications where relationships are crucial, such as fraud detection, risk management, social networks, recommendation systems, predictive analytics, dependency analysis, and IoT applications.</p><p>Theoretically, a graph database consists of nodes (also known as vertices) and edges (or relationships). Each node signifies an entity, such as a person or a product, while each edge represents the connection between two nodes, like friendships or preferences. Both nodes and edges can have attributes or properties linked to them. 🔄</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vYwJcB2Nb2_phqE-" /></figure><h4><strong>Graph Database vs Relational Database:</strong></h4><ul><li><strong>Evolving Relationships</strong>: Unlike relational databases, graph databases handle changing relationships more easily without altering schemas. For example, a relational database allows you to store entities and relationships in a one-to-many relationship, while a graph database allows for many-to-many relationships.</li><li><strong>Recursive Queries</strong>: Graph databases excel in recursive queries, such as finding multi-level connections, which are slower in relational databases. They allow you to materialize new information from existing facts and identify non-obvious connections.</li><li><strong>Pathfinding</strong>: Graph databases are more efficient than relational databases for shortest path or connectivity analysis.”</li></ul><h4><strong>Problem Statement:</strong></h4><p>The goal is to design a graph-based recommendation system that can assist users in finding suitable job opportunities based on their skills, endorsements, connections, and geographical location. By leveraging the relationships stored in the graph database, we aim to provide personalized job recommendations that enhance the user experience on platforms like LinkedIn.</p><p><strong>Create graph objects:</strong></p><p><strong>Entities (Nodes):</strong></p><ol><li>User: Represents an individual LinkedIn user.</li><li>Job: Represents a job listing.</li><li>Company: Represents an employer.</li><li>Skill: Represents the skills users can list or be endorsed for.</li><li>Location: Represents the location of the user and the job.</li><li>Connection: Represents the relationship between two users.</li><li>Application: Represents an application submitted by a user for a job.</li></ol><p><strong>Relationships (Edges):</strong></p><ol><li>User-APPLIED_TO-&gt;Job: This relationship captures when a user applies for a job.</li><li>User-CONNECTED_TO-&gt;User: This relationship captures connections between users (1st-degree, 2nd-degree, etc.).</li><li>User-ENDORSES-&gt;Skill: This represents when a user endorses another user for a skill.</li><li>User-HAS_SKILL-&gt;Skill: This relationship captures the skills a user has.</li><li>Job-REQUIRES_SKILL-&gt;Skill: This represents the skills required for a job.</li><li>Job-POSTED_BY-&gt;Company: This represents the company posting the job.</li><li>Company-LOCATED_IN-&gt;Location: This represents where the company is located.</li><li>User-LIVES_IN-&gt;Location: This represents where the user is located.</li></ol><p>Building all the nodes and edges tables below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*_or8VviCKsRViy9YbiRIow.jpeg" /></figure><pre>CREATE TABLE Users (<br>    UserID INT PRIMARY KEY,<br>    UserName VARCHAR(100),<br>    UserTitle VARCHAR(100)<br>) AS NODE;<br><br>CREATE TABLE Jobs (<br>    JobID INT PRIMARY KEY,<br>    JobTitle VARCHAR(100),<br>    CompanyID INT,<br>    LocationID INT<br>) AS NODE;<br><br>CREATE TABLE Companies (<br>    CompanyID INT PRIMARY KEY,<br>    CompanyName VARCHAR(100)<br>) AS NODE;<br><br>CREATE TABLE Skills (<br>    SkillID INT PRIMARY KEY,<br>    SkillName VARCHAR(100)<br>) AS NODE;<br><br>CREATE TABLE Locations (<br>    LocationID INT PRIMARY KEY,<br>    City VARCHAR(100),<br>    State VARCHAR(100)<br>) AS NODE;</pre><pre><br>CREATE TABLE AppliedTo (<br>    ApplicationID INT PRIMARY KEY,<br>    ApplicationDate DATE<br>) AS EDGE;<br><br><br>CREATE TABLE ConnectedTo (<br>    ConnectionID INT PRIMARY KEY,<br>    ConnectionType VARCHAR(50) -- e.g., &#39;1st-degree&#39;, &#39;2nd-degree&#39;<br>) AS EDGE;<br><br><br>CREATE TABLE Endorses (<br>    EndorsementID INT PRIMARY KEY<br>) AS EDGE;<br><br><br>CREATE TABLE HasSkill (<br>    HasSkillID INT PRIMARY KEY<br>) AS EDGE;<br><br><br>CREATE TABLE RequiresSkill (<br>    RequiresSkillID INT PRIMARY KEY<br>) AS EDGE;<br><br><br>CREATE TABLE PostedBy (<br>    PostedByID INT PRIMARY KEY<br>) AS EDGE;<br><br><br>CREATE TABLE LocatedIn (<br>    LocatedInID INT PRIMARY KEY<br>) AS EDGE;<br><br><br>CREATE TABLE LivesIn (<br>    LivesInID INT PRIMARY KEY<br>) AS EDGE;</pre><p>When you insert data into the graph tables, some implicit columns are automatically created to manage the relationships between the nodes.</p><p><strong>Node table:</strong></p><ul><li>For each node table, an implicit column called node_id is created.</li><li>The node_id column uniquely identifies each node in the system.</li></ul><p><strong>Edge Tables:</strong></p><ul><li>For each edge table, three implicit columns are automatically created:</li></ul><ol><li>edge_id: Uniquely identifies the edge.</li><li>from_id: Represents the starting node that this edge connects from.</li><li>to_id: Represents the ending node that this edge connects to.</li></ol><p><em>Note: edge may or may not have any attributes associated</em></p><pre><br>INSERT INTO Users (UserID, UserName, UserTitle)<br>VALUES (1, &#39;John Doe&#39;, &#39;Software Engineer&#39;),<br>       (2, &#39;Jane Smith&#39;, &#39;Data Analyst&#39;),<br>    (3, &#39;Alice Johnson&#39;, &#39;Product Manager&#39;),<br>(4, &#39;Bob Brown&#39;, &#39;Data Scientist&#39;),<br>(5, &#39;Charlie Green&#39;, &#39;UX Designer&#39;),<br>(6, &#39;David White&#39;, &#39;DevOps Engineer&#39;),<br>(7, &#39;Eve Black&#39;, &#39;Marketing Specialist&#39;),<br>(8, &#39;Frank Grey&#39;, &#39;Cloud Engineer&#39;);<br><br><br>    INSERT INTO Jobs (JobID, JobTitle, CompanyID, LocationID)<br>VALUES (1, &#39;Senior Software Engineer&#39;, 1, 1),<br>       (2, &#39;Data Scientist&#39;, 2, 2),<br>    (3, &#39;Front-End Developer&#39;, 3, 3),<br>(4, &#39;DevOps Engineer&#39;, 1, 1),<br>(5, &#39;Marketing Manager&#39;, 4, 4),<br>(6, &#39;Cloud Architect&#39;, 5, 5),<br>(7, &#39;Data Engineer&#39;, 2, 2);<br><br><br>    INSERT INTO Companies (CompanyID, CompanyName)<br>VALUES (1, &#39;Meta&#39;),<br>       (2, &#39;Amazon&#39;),<br>    (3, &#39;Apple&#39;),<br>(4, &#39;Google&#39;),<br>(5, &#39;CloudNine&#39;),<br>(6, &#39;DataAnalytics Ltd&#39;);<br><br>    INSERT INTO Skills (SkillID, SkillName)<br>VALUES (1, &#39;Python&#39;),<br>       (2, &#39;Machine Learning&#39;),<br>       (3, &#39;SQL&#39;),<br>    (4, &#39;JavaScript&#39;),<br>(5, &#39;Kubernetes&#39;),<br>(6, &#39;AWS&#39;),<br>(7, &#39;UI/UX Design&#39;),<br>(8, &#39;Project Management&#39;),<br>(9, &#39;Data Warehousing&#39;);<br><br>    INSERT INTO Locations (LocationID, City, State)<br>VALUES (1, &#39;San Francisco&#39;, &#39;CA&#39;),<br>       (2, &#39;New York&#39;, &#39;NY&#39;),<br>    (3, &#39;Austin&#39;, &#39;TX&#39;),<br>(4, &#39;Chicago&#39;, &#39;IL&#39;),<br>(5, &#39;Seattle&#39;, &#39;WA&#39;),<br>(6, &#39;Boston&#39;, &#39;MA&#39;);<br><br><br><br>    INSERT INTO AppliedTo (ApplicationID, $from_id, $to_id, ApplicationDate)<br>VALUES (1, (SELECT $node_id FROM Users WHERE UserID = 1), <br>           (SELECT $node_id FROM Jobs WHERE JobID = 1), &#39;2024-09-20&#39;),<br>     (2, (SELECT $node_id FROM Users WHERE UserID = 2), (SELECT $node_id FROM Jobs WHERE JobID = 2), &#39;2024-09-22&#39;),<br>(3, (SELECT $node_id FROM Users WHERE UserID = 3), (SELECT $node_id FROM Jobs WHERE JobID = 3), &#39;2024-09-21&#39;),<br>(4, (SELECT $node_id FROM Users WHERE UserID = 4), (SELECT $node_id FROM Jobs WHERE JobID = 5), &#39;2024-09-21&#39;),<br>(5, (SELECT $node_id FROM Users WHERE UserID = 5), (SELECT $node_id FROM Jobs WHERE JobID = 1), &#39;2024-09-20&#39;);<br><br><br>     INSERT INTO ConnectedTo (ConnectionID, $from_id, $to_id, ConnectionType)<br>VALUES (1, (SELECT $node_id FROM Users WHERE UserID = 1), <br>           (SELECT $node_id FROM Users WHERE UserID = 2), &#39;1st-degree&#39;),<br>     (2, (SELECT $node_id FROM Users WHERE UserID = 2), (SELECT $node_id FROM Users WHERE UserID = 3), &#39;1st-degree&#39;),<br>(3, (SELECT $node_id FROM Users WHERE UserID = 3), (SELECT $node_id FROM Users WHERE UserID = 4), &#39;1st-degree&#39;),<br>(4, (SELECT $node_id FROM Users WHERE UserID = 4), (SELECT $node_id FROM Users WHERE UserID = 5), &#39;1st-degree&#39;),<br>(5, (SELECT $node_id FROM Users WHERE UserID = 1), (SELECT $node_id FROM Users WHERE UserID = 5), &#39;2nd-degree&#39;);<br><br>     INSERT INTO Endorses (EndorsementID, $from_id, $to_id)<br>VALUES (1, (SELECT $node_id FROM Users WHERE UserID = 1), <br>           (SELECT $node_id FROM Skills WHERE SkillID = 1)),<br>     (2, (SELECT $node_id FROM Users WHERE UserID = 2), (SELECT $node_id FROM Skills WHERE SkillID = 2)),<br>(3, (SELECT $node_id FROM Users WHERE UserID = 3), (SELECT $node_id FROM Skills WHERE SkillID = 4)),<br>(4, (SELECT $node_id FROM Users WHERE UserID = 4), (SELECT $node_id FROM Skills WHERE SkillID = 5)),<br>(5, (SELECT $node_id FROM Users WHERE UserID = 5), (SELECT $node_id FROM Skills WHERE SkillID = 7));<br><br>     INSERT INTO HasSkill (HasSkillID, $from_id, $to_id)<br>VALUES (1, (SELECT $node_id FROM Users WHERE UserID = 1), <br>           (SELECT $node_id FROM Skills WHERE SkillID = 1)),<br>     (2, (SELECT $node_id FROM Users WHERE UserID = 2), (SELECT $node_id FROM Skills WHERE SkillID = 2)),<br>(3, (SELECT $node_id FROM Users WHERE UserID = 3), (SELECT $node_id FROM Skills WHERE SkillID = 4)),<br>(4, (SELECT $node_id FROM Users WHERE UserID = 4), (SELECT $node_id FROM Skills WHERE SkillID = 5)),<br>(5, (SELECT $node_id FROM Users WHERE UserID = 5), (SELECT $node_id FROM Skills WHERE SkillID = 7)),<br>(6, (SELECT $node_id FROM Users WHERE UserID = 6), (SELECT $node_id FROM Skills WHERE SkillID = 6)),<br>(7, (SELECT $node_id FROM Users WHERE UserID = 7), (SELECT $node_id FROM Skills WHERE SkillID = 8));<br><br><br>     INSERT INTO RequiresSkill (RequiresSkillID, $from_id, $to_id)<br>VALUES (1, (SELECT $node_id FROM Jobs WHERE JobID = 1), <br>           (SELECT $node_id FROM Skills WHERE SkillID = 1)),<br>     (2, (SELECT $node_id FROM Jobs WHERE JobID = 2), (SELECT $node_id FROM Skills WHERE SkillID = 2)),<br>(3, (SELECT $node_id FROM Jobs WHERE JobID = 3), (SELECT $node_id FROM Skills WHERE SkillID = 4)),<br>(4, (SELECT $node_id FROM Jobs WHERE JobID = 4), (SELECT $node_id FROM Skills WHERE SkillID = 5)),<br>(5, (SELECT $node_id FROM Jobs WHERE JobID = 5), (SELECT $node_id FROM Skills WHERE SkillID = 8));<br><br><br>     INSERT INTO PostedBy (PostedByID, $from_id, $to_id)<br>VALUES (1, (SELECT $node_id FROM Jobs WHERE JobID = 1), <br>           (SELECT $node_id FROM Companies WHERE CompanyID = 1)),<br>     (2, (SELECT $node_id FROM Jobs WHERE JobID = 2), (SELECT $node_id FROM Companies WHERE CompanyID = 2)),<br>(3, (SELECT $node_id FROM Jobs WHERE JobID = 3), (SELECT $node_id FROM Companies WHERE CompanyID = 3)),<br>(4, (SELECT $node_id FROM Jobs WHERE JobID = 4), (SELECT $node_id FROM Companies WHERE CompanyID = 1)),<br>(5, (SELECT $node_id FROM Jobs WHERE JobID = 5), (SELECT $node_id FROM Companies WHERE CompanyID = 4)),<br>(6, (SELECT $node_id FROM Jobs WHERE JobID = 6), (SELECT $node_id FROM Companies WHERE CompanyID = 5));<br><br><br>     INSERT INTO LocatedIn (LocatedInID, $from_id, $to_id)<br>VALUES (1, (SELECT $node_id FROM Companies WHERE CompanyID = 1), <br>           (SELECT $node_id FROM Locations WHERE LocationID = 1)),<br>     (2, (SELECT $node_id FROM Companies WHERE CompanyID = 2), (SELECT $node_id FROM Locations WHERE LocationID = 2)),<br>(3, (SELECT $node_id FROM Companies WHERE CompanyID = 3), (SELECT $node_id FROM Locations WHERE LocationID = 3)),<br>(4, (SELECT $node_id FROM Companies WHERE CompanyID = 4), (SELECT $node_id FROM Locations WHERE LocationID = 4)),<br>(5, (SELECT $node_id FROM Companies WHERE CompanyID = 5), (SELECT $node_id FROM Locations WHERE LocationID = 5));<br><br>     INSERT INTO LivesIn (LivesInID, $from_id, $to_id)<br>VALUES (1, (SELECT $node_id FROM Users WHERE UserID = 1), <br>           (SELECT $node_id FROM Locations WHERE LocationID = 1)),<br>     (2, (SELECT $node_id FROM Users WHERE UserID = 2), (SELECT $node_id FROM Locations WHERE LocationID = 2)),<br>(3, (SELECT $node_id FROM Users WHERE UserID = 3), (SELECT $node_id FROM Locations WHERE LocationID = 3)),<br>(4, (SELECT $node_id FROM Users WHERE UserID = 4), (SELECT $node_id FROM Locations WHERE LocationID = 4)),<br>(5, (SELECT $node_id FROM Users WHERE UserID = 5), (SELECT $node_id FROM Locations WHERE LocationID = 5)),<br>(6, (SELECT $node_id FROM Users WHERE UserID = 6), (SELECT $node_id FROM Locations WHERE LocationID = 1)),<br>(7, (SELECT $node_id FROM Users WHERE UserID = 7), (SELECT $node_id FROM Locations WHERE LocationID = 4));<br><br></pre><p>lets build a simple application that anyone using this graph database can use the queries to get the jobs easily</p><ol><li>Recommend Job roles Based on user’s Skills:</li></ol><pre>-- Recommend Jobs Based on Skills<br>SELECT  distinct u.username,j.jobtitle as Recommend_Jobs_Roles<br>FROM Users u, Jobs j, Skills s, HasSkill hs, RequiresSkill rs<br>WHERE MATCH(u-(hs)-&gt;s&lt;-(rs)-j)</pre><p>2. Recommend Jobs Based on Connections</p><pre>SELECT   u.username,u2.username as connected_user,j.jobtitle as Recommend_Jobs_Roles_For_user1<br>FROM Users u,Users u2, Jobs j,AppliedTo a,ConnectedTo c<br>WHERE MATCH(u-(c)-&gt;u2-(a)-&gt;j)</pre><p>3. Recommend Jobs Based on Company Followed</p><pre>SELECT u.UserName, j.JobTitle AS Recommend_Jobs_Roles_For_User<br>FROM Users u, Jobs j, PostedBy p, ConnectedTo c, Companies co, HasSkill hs, RequiresSkill rs<br>WHERE MATCH(u-(c)-&gt;co&lt;-(p)-j);</pre><p>4. Recommend jobs based on location proximity</p><pre>-- Recommend jobs based on location proximity<br>SELECT  u.UserName,loc.City as Home_location,c.CompanyName,loc.City as Office_Location<br>FROM Companies c, Users u, Locations loc,LivesIn li, LocatedIn lin<br>WHERE MATCH (u-(li)-&gt;loc&lt;-(lin)-c)</pre><p>I’ve learned that it’s essential to master any skill or new learning by practicing with real-world examples. As we all have used LinkedIn while searching for a job, understanding how LinkedIn recommends job listings through the SQL graph database is both fun and exciting. 😊</p><p>Hope this article has provided you with a better understanding of how Graphs work in SQL. 👍</p><p><strong>Resources used to write this blog:</strong></p><ul><li>Learn from <strong>YouTube </strong>Channels</li><li>Drew from personal experience</li><li><a href="https://learn.microsoft.com/en-us/sql/relational-databases/graphs/sql-graph-overview?view=sql-server-ver16">https://learn.microsoft.com/en-us/sql/relational-databases/graphs/sql-graph-overview?view=sql-server-ver16</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd8ddc67ce6f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learning-sql/find-me-a-job-social-network-schema-using-sql-graph-databases-dd8ddc67ce6f">Find me a Job Social Network Schema using SQL Graph Databases</a> was originally published in <a href="https://medium.com/learning-sql">Learning SQL</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing API Data Ingestion with PySpark]]></title>
            <link>https://medium.com/towards-data-engineering/optimizing-api-data-ingestion-with-pyspark-f324f26e5949?source=rss-a8a22b5bf23c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f324f26e5949</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pagination]]></category>
            <dc:creator><![CDATA[Samhitha Poreddy]]></dc:creator>
            <pubDate>Sun, 08 Sep 2024 23:13:56 GMT</pubDate>
            <atom:updated>2024-10-10T14:58:57.432Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, you will learn how to efficiently read API data and build a DataFrame from the API. <em>Pagination</em>, a technique that breaks large datasets into smaller chunks (or pages), is often used to avoid overwhelming the server and improve performance when working with large data sources. Let’s explore how to leverage pagination with PySpark to efficiently handle large datasets from a REST API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dc_w9nG-1oniRRsl289YZw.jpeg" /></figure><p>In PySpark, there are various methods to extract data from a REST API and convert it into a data frame. Some common approaches include:</p><p>1. Utilizing Python libraries for making HTTP requests.</p><p>2. Using the standard library, such as urllib, for HTTP requests without extra dependencies.</p><p>3. custom functions or UDF’s.</p><p>4. Employing pagination for API that supports it, especially for handling large datasets efficiently.</p><h3>Drawbacks of using the above-mentioned libraries or functions for HTTP requests in PySpark</h3><p>One major drawback of using Python libraries like requests for making API calls within a PySpark environment is that the driver is solely responsible for executing the HTTP requests. This leaves the Spark executors idle, which undermines Spark&#39;s core advantage—parallel processing and distributed computing.</p><p>This approach can be acceptable for small datasets, but it becomes inefficient as the data size increases. For instance, when I created a Python function that triggered 100 API requests, the entire process took about 4 minutes. This clearly illustrates the performance bottleneck when using Python to handle tasks that Spark is designed to parallelize. Therefore, while feasible for limited use cases, this method fails to scale and deviates from Spark’s optimized architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Vz4tXMADYhV9o9kGpv27HQ.png" /></figure><p>A standard library like urllib in Python, which sends HTTP requests, is also inefficient as it fetches all the data at once.</p><p>UDFs process data row-by-row, meaning each row triggers an individual API request, which is slow and inefficient. This approach underutilizes Spark’s distributed computing capabilities because the driver handles the HTTP requests, leaving the executors underutilized. This results in performance bottlenecks when dealing with large datasets.</p><p>Now, let’s explore the advantages of using pagination to fetch data from APIs.</p><h4>Pagination in PySpark:</h4><p>Pagination is more efficient than all the other processes mentioned above for API requests because it batches multiple API requests at once, reducing the number of calls and allowing larger chunks of data to be retrieved in fewer steps.</p><pre>import requests<br><br>base_url = &#39;https://dummyjson.com/users&#39;<br><br># Function to fetch paginated data<br>def customer_data_fetch():<br>    customer_data_list = []<br>    page = 1  # Start with page 1<br>    page_size = 20  # Number of records per page, can be customized<br><br>    while True:<br>        # Fetch a page of users<br>        response = requests.get(base_url, params={&#39;limit&#39;: page_size, &#39;skip&#39;: (page - 1) * page_size})<br>        <br>        if response.status_code == 200:<br>            page_data = response.json()<br>            <br>            # If there&#39;s no data left to fetch, break the loop<br>            if not page_data.get(&#39;users&#39;):<br>                break<br>            <br>            # Add the users from this page to the customer_data_list<br>            customer_data_list.extend(page_data[&#39;users&#39;])<br>            <br>            # Move to the next page<br>            page += 1<br>        else:<br>            print(f&#39;Error: {response.status_code} on page {page}&#39;)<br>            break<br><br>    return customer_data_list<br><br># Fetch customer data using pagination<br>customer_data_lists = customer_data_fetch()<br><br># Print a few records to verify<br>for user in customer_data_lists[:5]:  # Print the first 5 users<br>    print(user)</pre><p>By contrast, pagination fetches multiple records in one API call, reducing the total number of requests. When I implemented pagination, it reduced the processing time to under 3 seconds, as fewer API requests were needed, and each request retrieved more data at once.</p><p>This clearly shows how the pagination approach is scalable, leveraging fewer API calls and minimizing network overhead. In a distributed environment like Spark, where efficiency and scalability are key, pagination allows for optimal resource utilization, ensuring that both the driver and executors can handle large datasets without bottlenecks.</p><p><strong><em>Final Step:</em></strong><br>You can directly create a dataframe from the customer_data_fetch() function, which returns a list of dictionaries.</p><pre># Convert to PySpark DataFrame<br>df_customer = spark.createDataFrame(customer_data_lists)<br><br># Show the DataFrame (print a few rows)<br>df_customer.show()</pre><p>You can also create an RDD and build a dataframe out of the RDD.</p><pre>from pyspark.sql.types import StructType,StructField,StringType,DoubleType,IntegerType<br>from pyspark.sql import functions as f<br><br>json_rdd = spark.sparkContext.parallelize(customer_data_lists)<br><br>customer_df = spark.read.json(json_rdd,StructType([<br>    StructField(&quot;id&quot;,IntegerType(),True),<br>    StructField(&quot;firstName&quot;,StringType(),True),<br>    StructField(&quot;lastName&quot;,StringType(),True),<br>    StructField(&quot;email&quot;,StringType(),True),<br>    StructField(&quot;phone&quot;,StringType(),True),<br>    StructField(&quot;address&quot;,StringType(),True)<br>   <br>]))</pre><h3>A note on performance.</h3><p>If performance issues persist with large datasets, consider extending this logic using Python’s concurrent.futures to make parallel API requests, further speeding up the process. However, this simple loop approach works well for handling paginated data without overloading the driver.</p><p>Thanks for reading! I really hope you’ve enjoyed the journey of pagination!</p><p>Samhitha</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f324f26e5949" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/optimizing-api-data-ingestion-with-pyspark-f324f26e5949">Optimizing API Data Ingestion with PySpark</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Robust ETL Pipeline with Databricks and Apache Spark]]></title>
            <link>https://medium.com/@samhitha.lfa54/building-robust-etl-pipeline-with-databricks-and-apache-spark-511826f02e9a?source=rss-a8a22b5bf23c------2</link>
            <guid isPermaLink="false">https://medium.com/p/511826f02e9a</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[etl-pipeline]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Samhitha Poreddy]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 02:50:31 GMT</pubDate>
            <atom:updated>2024-08-25T02:50:31.404Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will learn how to build a scalable ETL pipeline using PySpark in Databricks, handling data ingestion, cleansing, transformation, and storing the transformed data in a target destination like a data lake or data warehouse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*iRX8ggO7ck7wgOfzak6avg.png" /><figcaption>ETL Pipeline</figcaption></figure><p><strong><em>Why Use Databricks and Apache Spark for ETL?</em></strong></p><ul><li><strong>Scalability</strong>: Spark’s ability to handle large-scale data across distributed clusters.</li><li><strong>Performance</strong>: In-memory computing and optimized query execution.</li><li><strong>Flexibility</strong>: Support for multiple languages (Python, Scala, SQL, R) and data sources.</li><li><strong>Integration with Delta Lake</strong>: Ensuring ACID transactions, scalable metadata handling, and data versioning.</li></ul><p>Now that we understand Spark’s benefits let’s design a Robust ETL Pipeline. The sample financial dataset I use for this project represents a platform like Robinhood, where users trade stocks, ETFs, and cryptocurrencies.</p><p>Below is the sample data I will use to build the ETL process. You can refer to the file using this link:<a href="https://github.com/SamhithaPoreddy/RobinhoodData/blob/main/financial_data.csv">FinancialData.csv</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1JbD8DV9_NBB25oI3W2IqA.png" /></figure><p><strong>Step 1: Load Data into Databricks</strong></p><p>When you start working on a pyspark application, the first step is to assign it a name, as defined below. I have uploaded my CSV file to the DBFS file storage location. I extract the file and create a new data frame in this step.</p><pre>from pyspark.sql import SparkSession<br><br># Create Spark session<br>spark = SparkSession.builder.appName(&quot;FinancialDataAnalysis&quot;).getOrCreate()<br><br>#Load the CSV file into a DataFrame<br>financial_df = spark.read.csv(&quot;dbfs:/FileStore/financial_data.csv&quot;,header=True,inferSchema=True)<br><br># Show a sample of the data<br>financial_df.show(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T2jGQzml1GHb7OF5gxTL8g.png" /><figcaption>DBFS File Storage</figcaption></figure><p><strong>Step 2: Data Cleansing</strong></p><p>Below are the data cleansing operations I have performed to ensure data integrity. Depending on your dataset, you can add various other operations.</p><ul><li><strong><em>Handle Missing Values</em></strong><em>: Check for and handle missing data.</em></li><li><strong><em>Data Type Corrections</em></strong><em>: Ensure data types are correct (e.g., numeric values for PricePerUnit, Quantity).</em></li><li><strong><em>Remove Duplicates</em></strong><em>: Ensure there are no duplicate records.</em></li></ul><pre>from pyspark.sql.functions import col, isnan, when, count<br><br># Check for missing values<br>financial_df.select([count(when(col(c).isNull(), c)).alias(c) for c in financial_df.columns]).show()<br><br># Drop rows with any missing values<br>financial_df = financial_df.na.drop()<br><br># Drop duplicates<br>financial_df = financial_df.dropDuplicates()</pre><p><strong>Step 3: Perform Complex Transformations</strong></p><p><strong><em>Adding column</em></strong><em>: Create new features such as </em><em>NetAmount (TotalAmount minus BrokerageFee).</em></p><pre># Create a new feature: Net Amount (TotalAmount - BrokerageFee)<br>financial_df = financial_df.withColumn(&quot;NetAmount&quot;, col(&quot;TotalAmount&quot;) - col(&quot;BrokerageFee&quot;))<br><br># Show the updated DataFrame<br>financial_df.show(5)</pre><p><strong><em>Calculate Daily Returns for Assets</em></strong><em>: Calculate the daily returns for each asset based on its closing prices. This can be useful for understanding the asset’s performance over time.</em></p><pre>from pyspark.sql.functions import lag, col, expr<br>from pyspark.sql.window import Window<br><br># Window specification for previous value calculation<br>window_spec = Window.partitionBy(&quot;AssetSymbol&quot;).orderBy(&quot;TransactionDate&quot;)<br><br># Calculate previous closing price<br>financial_df = financial_df.withColumn(&quot;PrevPrice&quot;, lag(col(&quot;PricePerUnit&quot;)).over(window_spec))<br><br># Calculate daily return<br>financial_df = financial_df.withColumn(&quot;DailyReturn&quot;, (col(&quot;PricePerUnit&quot;) - col(&quot;PrevPrice&quot;)) / col(&quot;PrevPrice&quot;))<br><br>financial_df.select(&quot;AssetSymbol&quot;, &quot;TransactionDate&quot;, &quot;PricePerUnit&quot;, &quot;PrevPrice&quot;, &quot;DailyReturn&quot;).show()</pre><p><strong>Step 4: Data Analysis and Insights</strong></p><p>Data analysis and insights help guide the design and optimization of ETL pipelines to ensure they are efficient, accurate, and aligned with business objectives.</p><ul><li><strong><em>Total Volume Traded per Asset</em></strong><em>: Group data by </em><em>AssetSymbol and calculate the total quantity traded.</em></li><li><strong><em>Average Transaction Size by Asset Type</em></strong><em>: Calculate the average </em><em>TotalAmount for each </em><em>AssetType</em></li><li><strong><em>Top Users by Transaction Volume</em></strong><em>: Find the users with the highest total transaction volume.</em></li></ul><pre>from pyspark.sql.functions import sum, avg, col <br># Total volume traded per asset<br>total_volume_by_asset = financial_df.groupBy(&quot;AssetSymbol&quot;).agg(sum(&quot;Quantity&quot;).alias(&quot;TotalAmount&quot;)).orderBy(&quot;TotalAmount&quot;, ascending=False)<br>total_volume_by_asset.show()<br><br># Average transaction size by asset type<br>avg_transaction_by_type = financial_df.groupBy(&quot;AssetType&quot;).agg(avg(&quot;TotalAmount&quot;).alias(&quot;AverageAmount&quot;)).orderBy(&quot;AverageAmount&quot;, ascending=False)<br>avg_transaction_by_type.show()<br><br># Top users by transaction volume<br>top_users = financial_df.groupBy(&quot;UserID&quot;).agg(sum(&quot;TotalAmount&quot;).alias(&quot;TopUsers&quot;)).orderBy(&quot;TopUsers&quot;,ascending=False)<br>top_users.show()</pre><p><strong>Step 5: loading data into Delta Lake</strong></p><p>You can use the respective storage solution to write the data depending on your use case.</p><pre># Save DataFrame to a Delta table<br>total_volume_by_asset.write.format(&quot;delta&quot;).mode(&quot;overwrite&quot;).save(&quot;/Financial_Delta_Load/delta/total_volume_by_asset&quot;)<br><br>avg_transaction_by_type.write.format(&quot;delta&quot;).mode(&quot;overwrite&quot;).save(&quot;/Financial_Delta_Load/delta/avg_transaction_by_type&quot;)<br><br>top_users.write.format(&quot;delta&quot;).mode(&quot;overwrite&quot;).save(&quot;/Financial_Delta_Load/delta/top_users&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DRfBKTGo_jcbKsnAENIT7A.png" /><figcaption>Delta Load</figcaption></figure><p><strong><em>Best Practices while working on a real-time project:</em></strong></p><p><strong>Immutability of DataFrames:</strong> It is essential to know that DataFrames in Spark are immutable. This means that once a DataFrame is created, it cannot be changed. Any transformation or data cleansing operation on a DataFrame creates a new DataFrame and does not modify the original one.</p><p><strong>Note</strong>: You lose the initial dataset if you perform any transformation or data cleansing on the same DataFrame reference. To avoid such discrepancies and preserve the original data, always create a new DataFrame after performing an action.</p><p>Thanks for reading! I hope this article gives you a clear understanding of building an end-to-end pipeline in Databricks.</p><p>Samhitha</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=511826f02e9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging EventBridge to trigger an aws step function using Terraform.]]></title>
            <link>https://medium.com/@samhitha.lfa54/leveraging-eventbridge-to-trigger-an-aws-step-function-using-terraform-adf212d0a0e4?source=rss-a8a22b5bf23c------2</link>
            <guid isPermaLink="false">https://medium.com/p/adf212d0a0e4</guid>
            <category><![CDATA[cdktf]]></category>
            <category><![CDATA[eventbridge]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws-step-functions]]></category>
            <dc:creator><![CDATA[Samhitha Poreddy]]></dc:creator>
            <pubDate>Sun, 11 Aug 2024 20:21:50 GMT</pubDate>
            <atom:updated>2024-08-11T20:34:03.601Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What is a step function?</strong></h3><p>An <strong>AWS Step Function</strong> is a serverless orchestration service provided by Amazon Web Services (AWS) that enables you to coordinate and manage the execution of distributed services and microservices into scalable, event-driven workflows. These workflows are composed of a series of steps, each representing a task or a set of tasks, that can be executed in sequence, parallel, or based on conditional logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*O189Yr5hPTntc22n8Figdw.png" /></figure><p><strong>What are the different ways we can trigger a step function?</strong></p><p>AWS Step Functions can be triggered in various ways, depending on your architecture and use case. Whether it’s manually triggering through the console, using AWS SDKs, or integrating with other AWS services like Lambda, S3, API Gateway, or IoT, there’s a method that fits almost every scenario. In this blog, I will explain how to trigger the step function through an event bridge using cdktf.</p><p><strong>Steps to build an event bridge:</strong></p><ol><li>Define an IAM role with assume role policy:</li></ol><p>We are all familiar with the first step for any AWS service that wants to interact with another AWS service in AWS: creating an IAM policy and attaching the policy to an IAM role.</p><p>sts:AssumeRole : action allows the specified service (EventBridge) to assume this IAM role.</p><p>states:StartExecution: This action allows the role to start an execution of a Step Function.</p><pre><br>import { Construct } from &quot;constructs&quot;;<br>import { App, TerraformStack } from &quot;cdktf&quot;;<br>import { IamRole, IamRolePolicy } from &quot;@cdktf/provider-aws/lib/iam-role&quot;;<br>import { AwsProvider } from &quot;@cdktf/provider-aws/lib/provider&quot;;<br>import { DataAwsIamPolicyDocument } from &quot;@cdktf/provider-aws/lib/data-aws-iam-policy-document&quot;;<br><br>class MyStack extends TerraformStack {<br>  constructor(scope: Construct, id: string) {<br>    super(scope, id);<br><br>    new AwsProvider(this, &quot;AWS&quot;, {<br>      region: &quot;us-east-1&quot;,<br>    });<br><br>    // IAM Role to be assumed by EventBridge<br>    const assumeRolePolicy = new DataAwsIamPolicyDocument(this, &quot;AssumeRolePolicy&quot;, {<br>      statement: [<br>        {<br>          actions: [&quot;sts:AssumeRole&quot;],<br>          principals: [<br>            {<br>              type: &quot;Service&quot;,<br>              identifiers: [&quot;events.amazonaws.com&quot;], // EventBridge service principal<br>            },<br>          ],<br>        },<br>      ],<br>    });<br><br>    const iamRole = new IamRole(this, &quot;EventBridgeStepFunctionRole&quot;, {<br>      name: &quot;eventbridge-step-function-role&quot;,<br>      assumeRolePolicy: assumeRolePolicy.json,<br>    });<br><br>    // IAM Policy to allow the IAM Role to start the Step Function execution<br>    new IamRolePolicy(this, &quot;InvokeStepFunctionPolicy&quot;, {<br>      role: iamRole.name,<br>      policy: JSON.stringify({<br>        Version: &quot;2012-10-17&quot;,<br>        Statement: [<br>          {<br>            Effect: &quot;Allow&quot;,<br>            Action: &quot;states:StartExecution&quot;,<br>            Resource: &quot;arn:aws:states:us-east-1:123456789012:stateMachine:your-state-machine-name&quot;,//give * if you have not defined your step function<br>          },<br>        ],<br>      }),<br>    });<br>  }<br>}<br><br>const app = new App();<br>new MyStack(app, &quot;MyStack&quot;);<br>app.synth();</pre><p>2. Define the EventBridge Rule to Trigger the Step Function</p><p>CloudWatchEventRule: This class allows you to create a CloudWatch Event Rule to trigger the step function at 4:00 PM EST daily</p><p>CloudWatchEventTarget: This class allows you to specify a target(step function) for a given CloudWatch Event (EventBridge) rule.</p><pre>import { Construct } from &quot;constructs&quot;;<br>import { TerraformStack } from &quot;cdktf&quot;;<br>import { AwsProvider, CloudwatchEventRule, CloudwatchEventTarget, IamRole } from &quot;@cdktf/provider-aws&quot;;<br>import { StepFunction } from &quot;@cdktf/provider-aws/lib/step-function&quot;;<br><br>class MyStepFunctionStack extends TerraformStack {<br>  constructor(scope: Construct, id: string) {<br>    super(scope, id);<br><br>    // AWS Provider<br>    new AwsProvider(this, &quot;Aws&quot;, {<br>      region: &quot;us-east-1&quot;, // specify your region<br>    });<br><br>    // Create Step Function (assuming you have a defined state machine JSON)<br>    const stepFunction = new StepFunction(this, &quot;MyStepFunction&quot;, {<br>      name: &quot;MyStepFunction&quot;,<br>      definition: JSON.stringify({<br>        Comment: &quot;A simple Step Function&quot;,<br>        StartAt: &quot;HelloWorld&quot;,<br>        States: {<br>          HelloWorld: {<br>            Type: &quot;Pass&quot;,<br>            Result: &quot;Hello, World!&quot;,<br>            End: true,<br>          },<br>        },<br>      }),<br>      roleArn:// specify your role ARN for the step function<br>    });<br><br>    // Create an IAM role for EventBridge to invoke Step Functions<br>   // Use the IAM role defined above<br><br><br>    // Create the CloudWatch Event Rule for daily trigger<br>    const rule = new CloudwatchEventRule(this, &quot;DailyTriggerRule&quot;, {<br>      name: &quot;DailyTriggerRuleStepFn&quot;,<br>      scheduleExpression: &quot;cron(0 21 * * ? *)&quot;, // 4:00 PM EST (21:00 UTC) daily<br>    });<br><br>    // Set the Step Function as the target for the event rule<br>    new CloudwatchEventTarget(this, &quot;StepFunctionTarget&quot;, {<br>      rule: rule.name,<br>      arn: stepFunction.arn,<br>      roleArn: eventRole.arn,<br>    });<br>  }<br>}<br><br>export default MyStepFunctionStack;</pre><p>3. Deploy</p><p>To use this stack, instantiate the MyStepFunctionStack class in your main.ts or equivalent entry file:</p><pre>import { App } from &quot;cdktf&quot;;<br>import MyStepFunctionStack from &quot;./MyStepFunctionStack&quot;;<br><br>const app = new App();<br>new MyStepFunctionStack(app, &quot;MyStepFunctionStack&quot;);<br>app.synth();t</pre><p>References:</p><p><a href="https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html">What is Step Functions?</a></p><p><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/sfn_state_machine">https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/sfn_state_machine</a></p><p>If you have any questions or feedback, feel free to ask.</p><p>Thanks,</p><p>Samhitha</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adf212d0a0e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark Architecture and Lifecycle]]></title>
            <link>https://medium.com/@samhitha.lfa54/spark-architecture-and-lifecycle-b4c8e7b77363?source=rss-a8a22b5bf23c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4c8e7b77363</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[spark-architecture]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Samhitha Poreddy]]></dc:creator>
            <pubDate>Sat, 27 Jul 2024 23:07:04 GMT</pubDate>
            <atom:updated>2024-07-27T23:08:06.180Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, we will learn the internal workings of Spark architecture and its lifecycle. I will also explain this with an analogy to help you understand it in simpler terms.</p><h3><em>“What is Spark?”</em></h3><p>Spark is an open-source distributed computing engine. It is used for processing and analyzing large volumes of data. Like Hadoop, spark also works in a distributed nature but differs in in-memory processing. Because of this in-memory and parallel processing feature, the spark application programs are at lightning speed.</p><p><strong>Spark architecture:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rsIPAQLtVWnyg9cuaVn5QQ.png" /><figcaption>Key components of the Spark architecture</figcaption></figure><p><strong>Driver: </strong>The “boss” of the Spark job, the driver determines the tasks, delegates them to workers, monitors progress, and collects the results.</p><p><strong>Cluster Manager: </strong>The “secretary” finds workers and manages resources for the driver. It ensures the driver gets enough workers (computers) to complete the tasks. Once the resources are assigned to the driver, the cluster manager silently ensures that all the resources are running and spins up new worker nodes in case of failure. Examples of cluster managers are YARN, Mesos, and Spark’s own standalone cluster manager.</p><p><strong>Workers: </strong>These<strong> </strong>are the “employees” who actually do the work. Each worker has its own memory and CPU (the computer’s brain) to perform the tasks assigned by the driver.</p><ul><li><strong>Executors</strong>: These are the “workstations” within the workers. Each worker has one or more executors, which are the environments where tasks run. Executors execute the tasks and store the data needed for and generated by these tasks.</li><li><strong>Tasks</strong>: The “individual jobs” that need to be done. The driver breaks down the main job into smaller tasks and assigns them to the executors to run in parallel.</li></ul><p><strong>Spark Lifecycle:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*K-kHTsmLjIzt3uIxO8P6Sw.png" /></figure><ol><li>The lifecycle starts when the user submits an application. Application can be a single command or combination of multiple notebooks with complex logic.</li><li>Spark comes to life when user submits an application. This triggers the driver to initiate the spark session. When application is submitted, the driver converts the code into Job.</li><li>DAG(Directed acyclic graph) builds the logical plan for all the transformations that are submitted within the application. A lineage graph is maintained by DAG.</li><li>DAG splits the code into multiple task and these tasks are given to the task executor.</li><li>Executor requests the resources from the cluster manager to execute the tasks.</li><li>The cluster manager allocates the resources to the worker and communicate the driver with the active worker nodes.</li><li>The driver now establishes a connection with the workers in the form of a JAR file.</li><li>Worker nodes execute tasks with the help of executors and then return the results to the driver.</li><li>The driver returns the results to the user.</li></ol><h4><strong>Analogy of movie Production:</strong></h4><ol><li><strong>Script Writing(Application) </strong>: The writer creates a detailed script for the movie.</li><li><strong>Scene Breakdown (Job Division)</strong>: The director (driver) breaks down the script into smaller scenes (tasks) through the help of assistant directors(DAG) and assigns these to different film crew members (workers).</li><li><strong>Organize Resources (Resource Allocation)</strong>: The producer (cluster manager) ensures that each crew member(worker) has the necessary equipment, locations, and schedules to complete their scenes.</li><li><strong>Filming (Task Execution)</strong>: The film crew members (workers) start working on their assigned scenes. Each specialized team (executor) within the crew focuses on specific tasks, such as filming, lighting, or sound recording.</li><li><strong>Pre-production and Post-production (Data Processing)</strong>: As the crews work, they may need to prepare props, set up scenes, or edit footage. These tasks are done in parallel to speed up the production process.</li><li><strong>Editing and Compilation (Result Collection)</strong>: Once the scenes are filmed(tasks), the director reviews and compiles the footage, ensuring everything fits together according to the script.</li><li><strong>Final Cut and Release (Completion)</strong>: The movie is completed, final edits are made, and it’s ready for release. The production is wrapped up, and resources are reset for the next project.</li></ol><p>Isn&#39;t it fascinating to see how Spark efficiently manages and processes large jobs by breaking them into smaller tasks, running them in parallel, and managing resources smartly. Each component of the movie production represents a part of Spark’s architecture, working together to complete a complex job efficiently</p><p><strong>Reference:</strong> <a href="https://www.youtube.com/watch?v=4JP0XqsjwCI&amp;list=PLgPb8HXOGtsQeiFz1y9dcLuXjRh8teQtw&amp;index=1">https://www.youtube.com/watch?v=4JP0XqsjwCI&amp;list=PLgPb8HXOGtsQeiFz1y9dcLuXjRh8teQtw&amp;index=1</a></p><p>Thanks for reading! Hope this articles gives you a clear understanding of the spark architecture.</p><p>Samhitha</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4c8e7b77363" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamically invoke selected tables in DMS Task.]]></title>
            <link>https://medium.com/@samhitha.lfa54/dynamically-invoke-selected-tables-in-dms-task-9ad9c3aa1e6d?source=rss-a8a22b5bf23c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ad9c3aa1e6d</guid>
            <category><![CDATA[aws-dms]]></category>
            <category><![CDATA[s3-bucket]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[database-migration]]></category>
            <dc:creator><![CDATA[Samhitha Poreddy]]></dc:creator>
            <pubDate>Sun, 14 Jul 2024 18:58:49 GMT</pubDate>
            <atom:updated>2024-07-14T18:58:49.298Z</atom:updated>
            <content:encoded><![CDATA[<p>AWS DMS task loads tables and views using table-mapping rules to perform the migration. These rules can be created in two ways: through the console and using CDK. In this article, I will explain how to build using CDK Terraform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*qo_6pUT911qXfkrLCBb4sw.png" /><figcaption>AWS DMS Migration Flow</figcaption></figure><p><strong>Why do we need to specify a particular list of tables?</strong></p><p>Currently, I have a source database residing in an AWS MySQL server. I want to extract tables into the target endpoint, which is an S3 bucket. As shown below, I can use the ‘%’ wildcard to copy all tables within a schema from the source database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*d5FkfSZd_xJ9Z1fPjnRyqQ.png" /></figure><p>There are more efficient ways to perform the task migration. As Data engineers, we always need to understand the business requirements. One of the fundamental rules while extracting data is reading and understanding the source data and copying the needed data into the Data Warehouse. By interacting with the business process experts, you can get the list of schemas and tables that will be used to build the underlying dimensional model.</p><p>Let’s split this task into three sections:</p><ol><li>Generate the tables list for migration.</li></ol><p>I have built a simple SQL server script that queries the list of tables in JSON format.</p><pre>SELECT right(TABLE_SCHEMA,3) as &#39;schema-name&#39;,JSON_QUERY(&#39;[&quot;&#39; + table_name + &#39;&quot;]&#39;) as &#39;table-names&#39; <br>FROM INFORMATION_SCHEMA.TABLESwhere TABLE_SCHEMA=&#39;test&#39; FOR JSON AUTOs</pre><p>2. Construct a function to read the JSON file.</p><p>Store the script as an array in a JSON file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*hj0OyUxrpGZSDZMcKZIc6Q.png" /></figure><p>Call the JSON file in main.ts file to configure the tables</p><p>This function reads a JSON file from a specified path and returns the parsed content as a JavaScript object.</p><pre>import * as fs from &#39;fs&#39;;<br>import * as path from &#39;path&#39;;<br><br>// Function to read JSON file<br>function readSchemaTablesFile(filePath: string) {<br>const fullPath = path.resolve(__dirname, filePath);<br>const fileContent = fs.readFileSync(fullPath, &#39;utf-8&#39;);<br>return JSON.parse(fileContent);<br>}<br>const schemaTables = readSchemaTablesFile(&#39;./src/schema_tables.json&#39;);</pre><p>3. Build table mapping rules</p><pre>const tableMappings = {<br>  rules: schemaTables.schemas.map((schema: any, index: number) =&gt; ({<br>    &quot;rule-type&quot;: &quot;selection&quot;,<br>    &quot;rule-id&quot;: (index + 1).toString(),<br>    &quot;rule-name&quot;: (index + 1).toString(),<br>    &quot;object-locator&quot;: {<br>      &quot;schema-name&quot;: schema[&#39;schema-name&#39;],<br>      &quot;table-name&quot;: schema[&#39;table-names&#39;].join(&#39;,&#39;)<br>    },<br>    &quot;rule-action&quot;: &quot;include&quot;<br>  }))<br>};<br>// Print the tableMappings variable<br>   console.log(JSON.stringify(tableMappings, null, 2));</pre><p>Using the map function on the schemas array to iterate over each element in the array and build the JSON object with the list of tables that need to be called in the DMS task.</p><p>The output of the table mappings looks like the one below.</p><pre>{<br>  &quot;rules&quot;: [<br>    {<br>      &quot;rule-type&quot;: &quot;selection&quot;,<br>      &quot;rule-id&quot;: &quot;1&quot;,<br>      &quot;rule-name&quot;: &quot;1&quot;,<br>      &quot;object-locator&quot;: {<br>        &quot;schema-name&quot;: &quot;test&quot;,<br>        &quot;table-name&quot;: &quot;orders&quot;<br>      },<br>      &quot;rule-action&quot;: &quot;include&quot;<br>    },<br>    {<br>      &quot;rule-type&quot;: &quot;selection&quot;,<br>      &quot;rule-id&quot;: &quot;2&quot;,<br>      &quot;rule-name&quot;: &quot;2&quot;,<br>      &quot;object-locator&quot;: {<br>        &quot;schema-name&quot;: &quot;test&quot;,<br>        &quot;table-name&quot;: &quot;customers&quot;<br>      },<br>      &quot;rule-action&quot;: &quot;include&quot;<br>    }<br>  ]<br>}</pre><p>4. configuring the DMS replication task</p><pre># Create a new replication task<br>resource &quot;aws_dms_replication_task&quot; &quot;test&quot; {<br>  cdc_start_time            = &quot;1993-05-21T05:50:00Z&quot;<br>  migration_type            = &quot;full-load&quot;<br>  replication_instance_arn  = aws_dms_replication_instance.test-dms-replication-instance-tf.replication_instance_arn<br>  replication_task_id       = &quot;test-dms-replication-task-tf&quot;<br>  replication_task_settings = &quot;...&quot;<br>  source_endpoint_arn       = aws_dms_endpoint.test-dms-source-endpoint-tf.endpoint_arn<br>  table_mappings            = JSON.stringify(tableMappings),<br><br>  tags = {<br>    Name = &quot;test&quot;<br>  }<br><br>  target_endpoint_arn = aws_dms_endpoint.test-dms-target-endpoint-tf.endpoint_arn<br>}</pre><p>Here, we use the tableMappings object as the value of the table_mappings property.</p><p>Thank you for taking the time to read.</p><p>Best regards,</p><p>Samhitha</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ad9c3aa1e6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>