<?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 Eduardo Senior on Medium]]></title>
        <description><![CDATA[Stories by Eduardo Senior on Medium]]></description>
        <link>https://medium.com/@senior.eduardo92?source=rss-5c11251b5f3c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ld9_jKAiqUOzhRUVQK6F7w.jpeg</url>
            <title>Stories by Eduardo Senior on Medium</title>
            <link>https://medium.com/@senior.eduardo92?source=rss-5c11251b5f3c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:51:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@senior.eduardo92/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[Active Counts in SQL Using a Date Dimension]]></title>
            <link>https://medium.com/learning-sql/active-counts-in-sql-using-a-date-dimension-92e288466f9b?source=rss-5c11251b5f3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/92e288466f9b</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[football]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Eduardo Senior]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 16:08:47 GMT</pubDate>
            <atom:updated>2024-04-07T16:08:47.841Z</atom:updated>
            <content:encoded><![CDATA[<h4>What NFL Hall of Fame data can teach us about business.</h4><figure><a href="https://learning-sql.ck.page/6214028d2f"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZD3VqPlLSVm-io1SwNaKw.jpeg" /></a></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/0*gMgHqyU-cZoaDI5c.jpg" /><figcaption>Source: Neil Leifer/SI</figcaption></figure><h4>Welcome in.</h4><p>I want to show you a little trick. It’s a join in SQL that will help you solve a key business question that comes up again and again across an array of functional areas:</p><blockquote>How can we measure the <strong>active status</strong> of an entity over time?</blockquote><p>While it might seem trivial, having the ability to work through these types of problems can dramatically expand your analytical toolkit. Think about the following use cases:</p><ul><li>HR is trying to gauge the number of <em>active employees</em> at the company. They want to do a year-over-year analysis.</li><li>IT leadership is asking for a report showing how many open cases the company’s help desk has. They’re interested in seasonality.</li><li>Sales directors are trying to count <em>active opportunities</em> in their sales pipeline. They’re looking to compare trends before and after a product launch.</li></ul><p>These are classic business intelligence questions that virtually every company is asking. Many times, leadership will have a grasp on <em>today’s</em> numbers, but things tend to go awry when we talk about those very same metrics <em>over time</em>. And if you’re reading this article right now, I’m going to wager and say that you’re the guy or gal at your company responsible for making this happen. A good approach to tackling these problems can go a long way for you and your stakeholders. And I have you covered.</p><h4>Here’s the plan.</h4><p>We’ll begin this post by exploring the root of the problem: why exactly is it so difficult to answer these questions? Next, we’ll introduce our proposed solution by explaining the concept of a date dimension and its role in overcoming these obstacles. To wrap up, we’ll tie everything together with a comprehensive demonstration. We’ll interpret and visualize our findings and showcase our approach&#39;s practical application and benefits.</p><p>Let’s begin.</p><h4>The issue.</h4><p>Data availability is usually not the challenge. Most of the entities we mentioned earlier can typically be found in a dimension table or directory: a list of <strong><em>employees</em></strong> from Workday, a dump of <strong><em>cases</em></strong> from ServiceNow, or the <strong><em>opportunity</em></strong> object in Salesforce.</p><p>Upon inspection, however, you will quickly notice that many of these tables are structured so that each employee or opportunity is represented by exactly one record.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3a5S5TfyxRn9etKnQ2cjqQ.png" /><figcaption>Sample employee directory. Image by author.</figcaption></figure><p>And therein lies the problem. Sure, these records have start and end dates associated with them, which allow us to determine whether a given employee is active or not. But in their current form, these datasets only allow us to gauge what is active <em>as of today</em>.</p><pre>select <br>  count(distinct(employee_id)) as active_total<br>from <br>  employees<br>where <br>  termination_date is null</pre><p>What we really want to know is what this number looks like <em>over time</em>: by year, quarter, month, or even day.</p><h4>Enter the date dimension.</h4><p>A date dimension is simply a table designed to have a record for each date in the calendar. These records contain a series of attributes that expand on the date in question: things like year, month, day, week, and quarter. Some even include flags to indicate special occasions, like that day being a holiday or the end of a fiscal year.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*V30Ky2DnN2iSIvQ0gxsYxA.png" /><figcaption>Sample date dimension. Image by author.</figcaption></figure><p>So let’s go back and think about our problem. We said earlier that the crux of the issue lies in the nature of most datasets. Typically, records are static, capturing only snapshots in time — such as the start and end dates of an employee’s tenure.</p><p>But what if we can change how the dataset is organized?</p><p>By leveraging a date dimension, we can join static date fields from any dataset to a <em>continuous</em> calendar. This method allows us to populate a record for each day an entity was active, providing a granular, day-by-day view of activity over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*dm6y0j1ZFz9atskO9Y5Ykw.png" /><figcaption>Concept of joining to date dimension. Image by author.</figcaption></figure><h4>Show &amp; tell.</h4><p>Alright, let’s drive this idea home with a topic that <em>really</em> matters: football.</p><p>Now, I know what you’re thinking: “What does football have to do with our business questions?” Well, quite a bit, it turns out.</p><p>In this demo, we’re going to explore how we can use SQL and our date dimension technique to track and analyze the careers of NFL legends. The idea here is simple: if we can understand the dynamics of football careers over time, we can apply the same concepts to employees, cases, sales opportunities — you name it.</p><p>Here’s the question we’re looking to answer:</p><blockquote>Which NFL season featured the most future Hall of Fame players?</blockquote><p>Lucky for us, we have a great dataset available as part of the Kaggle community — shout out to Matt OP 🤙</p><p>To start, <a href="https://www.kaggle.com/datasets/mattop/nfl-pro-football-hall-of-fame-19632022?resource=download">download the data</a> and load it into your preferred data platform or RDMS. I will be using Apache Spark via the PySpark APIs as well as Spark SQL throughout the demo, but the same concepts should apply regardless of the technology.</p><p>After loading up the table (I named mine nflhofplayers), we can preview the data and make our initial observations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vQv_YNhuC7YNqKgkf7LgHw.gif" /><figcaption>Data preview. Image by author.</figcaption></figure><p>We can see the table has 306 records (one for each player inductee, 1963–2022) and is composed of 33 fields. It has things like position, all_pro_selections, and total_games_played. These are great data points that can help sharpen our analysis later on, but to answer our initial question, we will focus on two important date fields: from and to. These fields represent the <em>first</em> and <em>last</em> year of a player’s career in the NFL.</p><p>Let’s zoom in on a specific player to get a better understanding:</p><p>Calvin Johnson.</p><p>Yeah, this guy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*Yn9ijuE2l7WHi-ei.gif" /><figcaption>Source: Tenor</figcaption></figure><p>Calvin Johnson played 9 years in the NFL (2007-2015) for the Detroit Lions and was an unstoppable force at the wide receiver position. The clip you see above: he’s hauling in a clutch, game-tying catch in a showdown with the Bengals, where he put up 155 receiving yards and 2 touchdowns.</p><p>Here’s what his record looks like in our table:</p><pre>select<br>  id,<br>  player,<br>  position,<br>  from as played_from,<br>  to as played_to<br>from <br>  nflhofplayers <br>where <br>  id=8</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*RPWK8iAqRrGCarGBeEzSTQ.png" /><figcaption>Calvin Johnson’s record. Image by author.</figcaption></figure><p>Now that we understand what we are looking at, let’s reframe the question we posed earlier:</p><blockquote>How can we produce a record of Calvin Johnson for <strong><em>each year</em></strong> that he played in the league?</blockquote><p>If we can achieve this, we can group on that particular date column, and Johnson will be counted in each of the years he was active in the NFL. Do this across all of the players, and we have our answer.</p><p>At least in theory... Let’s take our date dimension out for a spin.</p><pre>with <br> <br>  calendar as (<br>    select year(date_day) as dateyear<br>    from all_dates<br>    group by 1<br>  )<br><br>  , players as (<br>    select<br>      id,<br>      player,<br>      position,<br>      from as played_from,<br>      to as played_to<br>    from nflhofplayers <br>    where id=8<br>  )<br><br>  , joined as (<br>    select * <br>    from players<br>    left join calendar<br>    on dateyear between played_from and played_to<br>  )<br><br>select * from joined;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*8wLJM2PyVDCatoP0ngZ_aw.png" /><figcaption>Post-join record set for Calvin Johnson. Image by author.</figcaption></figure><p>Let’s break down what’s happening in this query.</p><ol><li>The first thing we’ll need to do is roll up our dates to the year level, so you’ll notice the calendar CTE does just that. We do this because it’s the level of granularity that we’re interested in. If your analysis is at the week or day level, just make sure to roll up your date dimension accordingly.</li><li>Next, our players CTE is just a copy and paste from the previous code block. We’re still focused on Calvin here (notice the id=8 in the where clause). At this point, you’re welcome to grab as many columns as needed for your specific analysis. For now, we’ll just select position along with our two essential date fields.</li><li>When we take stock of what’s happening in the joined CTE, the real game-changer is the between operator — it’s what lets us throw a range into the mix when we&#39;re joining data. And that&#39;s incredibly powerful. It means we can easily scoop up any dates that sit within our specified start and end points straight from the date dimension (i.e., calendar).</li></ol><p>And that’s it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*u1-MAfp9qNhXOYXI.gif" /><figcaption>Source: Tenor</figcaption></figure><p>Well, almost. Remove your id filter to apply this logic to all players in the dataset—group by dateyear and count(distinct id).</p><pre>with <br><br>  calendar as (<br>    select year(date_day) as dateyear<br>    from all_dates<br>    group by 1<br>  )<br><br>  , players as (<br>    select<br>      id,<br>      player,<br>      position,<br>      from as played_from,<br>      to as played_to<br>    from nflhofplayers<br>  )<br><br>  , joined as (<br>    select * <br>    from players<br>    left join calendar<br>    on dateyear between played_from and played_to<br>  )<br><br>  , grouped as (<br>    select<br>      dateyear,<br>      count(distinct id) as players<br>    from joined<br>    group by 1<br>  )<br><br>select * <br>from grouped<br>order by dateyear desc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*guqLGbw1Vjgw9X1etn47aA.png" /><figcaption>Active player count by year. Image by author.</figcaption></figure><p>Now, our problem seems easier than ever to solve. You can take a max, sort on the players column, or even graph it out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NyrLQ2k_PMayC5I5BCT8Bg.png" /><figcaption>Players grouped by year active. Image by author.</figcaption></figure><h4>Here’s to 1971.</h4><p>That season must have been like watching a live audition for Canton, with each game unfolding as a chapter in future Hall of Famers’ highlight reels.</p><p>The 1971 season featured a total of <strong>81 players</strong> who would eventually become recipients of a gold jacket.</p><p>That year, the Dallas Cowboys clinched their first Super Bowl victory, a testament to the high-caliber play that defined the season. Players like <a href="https://www.profootballhof.com/players/roger-staubach/">Roger Staubach</a> began cementing their legacies, contributing to a campaign filled with epic comebacks and heart-stopping plays.</p><p>For those of us who weren’t around to see these legends live, it’s hard to deny that this <em>feels</em> right. We’ve all heard the anecdotes: all of those crazy stories from dad, uncle, or grandpa, telling us how ‘<em>we used to watch the REAL football players back then!</em>’ The data backs them up! And as much as we hoped we never had to, we may just have to admit that our obnoxious uncle was right: the 70s rocked 🤘</p><h4>As promised.</h4><p>I’m sure you can now see how, as advertised, this translates seamlessly into the world of business 😏… Just swap the player_from and player_to date fields in the join for whatever constitutes a “tenure” for a given entity’s state. Employees have ‘hire’ and ‘termination’ dates; cases have ‘open’ and ‘closed’ dates; opportunities have ‘created’ and ‘converted’ dates. Whatever the industry, it’s the start and end dates that define an entity’s ‘active’ season, and that’s what you feed the between operator.</p><p>Thanks for reading 🤙</p><h4>References:</h4><ol><li>Campos, G. (2023, October 30). Date dimension: How to create a practical and useful date dimension in dbt. <em>Indicium Engineering</em>. Retrieved from <a href="https://medium.com/indiciumtech/date-dimension-how-to-create-a-practical-and-useful-date-dimension-in-dbt-5ee70a18f3bb">https://medium.com/indiciumtech/date-dimension-how-to-create-a-practical-and-useful-date-dimension-in-dbt-5ee70a18f3bb</a></li><li>McEwen, J. (2022, June 5). How to easily create a SQL date dimension table. <em>Learning SQL</em>. Retrieved from <a href="https://medium.com/learning-sql/how-to-easily-create-a-sql-date-dimension-table-a3f46537c500">https://medium.com/learning-sql/how-to-easily-create-a-sql-date-dimension-table-a3f46537c500</a></li><li>OP, M. (n.d.). NFL Pro Football Hall of Fame 1963–2022. Kaggle: Your machine learning and data science community. Retrieved March 29, 2024, from <a href="https://www.kaggle.com/datasets/mattop/nfl-pro-football-hall-of-fame-19632022?resource=download">https://www.kaggle.com/datasets/mattop/nfl-pro-football-hall-of-fame-19632022?resource=download</a></li><li>Pro Football Hall of Fame. (n.d.). Roger Staubach. Retrieved March 29, 2024, from <a href="https://www.profootballhof.com/players/roger-staubach/">https://www.profootballhof.com/players/roger-staubach/</a></li></ol><h4>Appendix A: Create your own date dimension.</h4><p><strong><em>Excel</em></strong>. The easiest way to get started. Here are the steps:</p><ol><li>Determine the Date Range: identify your start date and end date. For example, 2023-01-01 to 2023-12-31.</li><li>Create a New Excel Spreadsheet: open Excel and start a new worksheet.</li><li>Enter the Start Date: in cell A1, enter your start date.</li><li>Generate Sequential Dates: in cell A2, enter the formula =A1+1. Copy this formula down column A until the date displayed is your end date.</li><li>Add Time Attributes: label additional columns for Year, Month, Day, etc., starting from column B. Use Excel functions like YEAR(), MONTH(), DAY() to populate these columns based on the date in column A.</li></ol><p>You can set up a range that works for you and then bring it into your database of choice.</p><p><strong><em>PostgreSQL</em></strong>. If you’re using Postgres, no worries: you have the generate_series function at your disposal.</p><ol><li>Create the date dimension table.</li></ol><pre>create table date_dimension (<br>    date_key date primary key,<br>    year int,<br>    month int,<br>    day int,<br>    -- Add more attributes as needed<br>);</pre><p>2. Generate the date range and populate the table.</p><pre>insert into date_dimension (date_key, year, month, day)<br>select<br>    date_series::date, <br>    extract(year from date_series), <br>    extract(month from date_series), <br>    extract(day from date_series)<br>from generate_series(<br>    &#39;start_date&#39;::timestamp, <br>    &#39;end_date&#39;::timestamp, <br>    &#39;1 day&#39;::interval<br>) as date_series;</pre><p>This method of creating the date dimension also applies to MS SQL Server. For a more detailed explanation, please check out this <a href="https://medium.com/learning-sql/how-to-easily-create-a-sql-date-dimension-table-a3f46537c500">article</a> by <a href="https://jonmce.medium.com/">Jon McEwen</a> in the <a href="https://medium.com/learning-sql">Learning SQL</a> publication here on Medium.</p><p><strong><em>Databricks/Spark</em></strong>. Python and DataFrames can be helpful here.</p><pre># Set start and end dates<br>startDate = &quot;start_date&quot;<br>endDate = &quot;end_date&quot;<br><br># Generate date range<br>dateDF = spark.sql(s&quot;&quot;&quot;<br>  select<br>    sequence(<br>      to_date(&#39;$startDate&#39;), <br>      to_date(&#39;$endDate&#39;), <br>      interval 1 day<br>    ) as date_array<br>  &quot;&quot;&quot;).withColumn(&quot;date&quot;, explode($&quot;date_array&quot;))<br><br># Use Spark SQL functions to extract year, month, day, etc., <br># from the date column<br>dateDimensionDF = dateDF.select(<br>    col(&quot;date&quot;),<br>    year(col(&quot;date&quot;)).alias(&quot;year&quot;),<br>    month(col(&quot;date&quot;)).alias(&quot;month&quot;),<br>    dayofmonth(col(&quot;date&quot;)).alias(&quot;day&quot;)<br>    #Add more attributes as needed<br>)<br><br># save as table<br># ...</pre><p><strong><em>dbt</em></strong>. Use Jinja templating and dbutils for dynamic date ranges.</p><pre>with<br>  date_series AS (<br>    select <br>      dateadd(day, row_number() over (order by null) - 1, &#39;{{ var(&quot;start_date&quot;) }}&#39;) as date<br>    from<br>      {{ dbt_utils.generate_series(start=0, stop=(datediff(&#39;{{ var(&quot;end_date&quot;) }}&#39;, &#39;{{ var(&quot;start_date&quot;) }}&#39;))) }}<br>  )<br><br>select<br>  date,<br>  extract(year from date) AS year,<br>  extract(month from date) AS month,<br>  extract(day from date) AS day<br>  -- Add more attributes as needed<br>from date_series</pre><p>In dbt, you can pass variables in your dbt run command or set them in your dbt_project.yml.</p><p>If you’re interested in this approach and you’d like to go a little deeper, check out this <a href="https://medium.com/indiciumtech/date-dimension-how-to-create-a-practical-and-useful-date-dimension-in-dbt-5ee70a18f3bb">post</a> by Gabriel Campos.</p><h4>Appendix B: Alternatives.</h4><p><strong><em>Conditional aggregation</em></strong>. You do have the option of forgoing the date dimension altogether. This means no need to create or maintain a separate table, which is always nice. If your period is well-defined, this approach can be more straightforward.</p><pre>select<br>  year(check_date) AS year,<br>  month(check_date) AS month,<br>  count(employee_id) AS active_employees<br>from<br>    (<br>      select &#39;2023-01-01&#39; + interval a + 10*b month AS check_date<br>      from<br>        (select 0 a union all select 1 union all select 2 union all select 3<br>        union all select 4 union all select 5 union all select 6<br>        union all select 7 union all select 8 union all select 9) as a<br>      join<br>        (select 0 b union all select 1 union all select 2 union all select 3<br>        union all select 4 union all select 5 union all select 6<br>        union all select 7 union all select 8 union all select 9) as b<br>    ) as months<br>join poc.employees<br>  on <br>    hire_date &lt;= check_date <br>    and (termination_date is null or termination_date &gt;= check_date)<br>group by year, month<br>order by year, month</pre><p>However, you’re taking a hit on scalability and flexibility. As your analytical needs grow more complex, this method can become cumbersome. Maintainability can suffer, too: if your period of interest changes, you’ll need to constantly update your logic. The code above only works for 2023, for example.</p><p><strong><em>Snapshot facts</em></strong>. You could also build out a data pipeline to capture snapshots of these entities in a fact table. For example, you could create a table fct__active_employees that incrementally loads the current count of active employees.</p><pre>merge into fct__active_employees as target<br>using (<br>  select <br>    current_date() as snapshot_date,<br>    count(*) as active_employees<br>  from employees<br>  where termination_date is null<br>) as source<br>on source.snapshot_date = target.snapshot_date<br>when matched then update set *<br>when not matched then insert *</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92e288466f9b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learning-sql/active-counts-in-sql-using-a-date-dimension-92e288466f9b">Active Counts in SQL Using a Date Dimension</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[REST API Data Ingestion with PySpark]]></title>
            <link>https://medium.com/@senior.eduardo92/rest-api-data-ingestion-with-pyspark-5c9c9ce89c9f?source=rss-5c11251b5f3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c9c9ce89c9f</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Eduardo Senior]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 16:45:47 GMT</pubDate>
            <atom:updated>2023-10-05T16:47:59.236Z</atom:updated>
            <content:encoded><![CDATA[<h4>Putting executors to work.</h4><h4>We’ve all done it.</h4><p>If you’re writing a PySpark application and you are trying to consume data from a REST API like this:</p><pre>import requests<br>from pyspark.sql import SparkSession<br><br>spark = SparkSession.builder.appName(&quot;REST_API_with_PySpark&quot;).getOrCreate()<br><br>base_url = &quot;https://api.example.com/data&quot;<br>query_limit = 500<br>total_records = 2000<br><br>data = []<br>for offset in range(0, total_records, query_limit):<br>    url = f&quot;{base_url}?limit={query_limit}&amp;offset={offset}&quot;<br>    response = requests.get(url)<br>    if response.status_code == 200:<br>        data.extend(response.json())<br><br># Load DataFrame<br><br># Transformations<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*D8ONBgHDfIQid3ru" /><figcaption>🐐</figcaption></figure><h4>There’s a better way.</h4><p>This approach may be okay for initial testing, but it lacks scalability. The problem with this code is that it’s pure Python, and as a result will run solely on the driver. Spark is all about parallel execution 🚀, it’s got no time for that kind of single-threaded nonsense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*jIxe3RpKbIOmFaBxmYrIvA.png" /><figcaption>Single-threaded nonsense</figcaption></figure><p>To leverage Spark’s distributed processing power, you need to operate on distributed data structures like RDDs or DataFrames. By applying transformations and actions on these data structures, we enable Spark to distribute tasks across multiple executors and process data in parallel. Only then are we taking advantage of the computing resources of the entire cluster, allowing for significant improvements in performance.</p><p>Give this a try instead:</p><pre>import requests<br>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import udf, explode, lit<br>from pyspark.sql.types import ArrayType, StructType, StructField, StringType, IntegerType<br><br>spark = SparkSession.builder.appName(&quot;REST_API_with_PySpark_DF&quot;).getOrCreate()<br><br>schema = StructType([<br>    StructField(&quot;field1&quot;, StringType(), True),<br>    StructField(&quot;field2&quot;, IntegerType(), True),<br>    # ... Define other fields based on the API&#39;s response<br>])<br><br>@udf(returnType=ArrayType(schema))<br>def fetch_data(offset: int, limit: int):<br>    endpoint = &quot;https://api.example.com/data&quot;<br>    params = {<br>        &quot;offset&quot;: offset,<br>        &quot;limit&quot;: limit<br>    }<br>    response = requests.get(endpoint, params=params)<br>    return response.json()  # assuming API returns a list of records<br><br>total_records = requests.get(&quot;https://api.example.com/data&quot;, params={&quot;offset&quot;: 0, &quot;limit&quot;: 1}).json().get(&#39;total&#39;, 0)<br>records_per_page = 500<br><br>offsets_df = spark.range(0, total_records, records_per_page).select(col(&quot;id&quot;).alias(&quot;offset&quot;), lit(records_per_page).alias(&quot;limit&quot;))<br>response_df = offsets_df.withColumn(&quot;response&quot;, fetch_data(&quot;offset&quot;, &quot;limit&quot;))<br>results_df = response_df.select(explode(&quot;response&quot;))</pre><p>Our latest code has two notable additions: 1) a <strong>user-defined function (UDF) </strong>named fetch_data, and 2) a <strong>schema</strong>, creatively named schema.</p><h4>UDFs</h4><p>In Spark, UDFs are custom functions authored by users to address specific needs not covered by Spark’s built-in functions (like sending HTTP requests). Put simply, they are functions that operate on the data, row by row, and can take one or more columns as input.¹</p><p>For our purposes, you can think of each record in the DataFrame as representing the configuration for a single API call. The UDF takes the different combinations of offset and limit values available in each row and “configures” a request. Using the withColumn transformation in conjunction with our fetch_data function, we create a new results_df DataFrame and store the response of each API call within a new field called “response”.</p><p>So, how does this improve upon our original code? At first glance, it might seem like we are still making an API call for each offset. And, indeed, we are. The difference, of course, is that we are no longer doing so <em>sequentially</em>. By turning our offset list into a DataFrame and encapsulating our logic within a UDF, we create an object that can be partitioned<strong><em> </em></strong>across an army of executors, making concurrent operations across the cluster possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ka9nRWUCfNcoCxj1dxKcJw.jpeg" /><figcaption>No nonsense here.</figcaption></figure><h4>Have expectations.</h4><p>When working with UDFs that interact with structured data sources, it’s important to define a schema for the expected response. A predefined schema ensures that the data retrieved matches our expectations in terms of structure and data types. This not only safeguards data integrity and quality but also optimizes performance, as Spark can process data more efficiently when the structure is known in advance.²</p><p>When setting up the response schema for your specific use case, look for clues in the API provider’s documentation. Here’s an example of what the response for a GET /users API call might look like:</p><pre>[<br>  {<br>    &quot;name&quot;: &quot;Jack&quot;,<br>    &quot;age&quot;: 30,<br>    &quot;isActive&quot;: true<br>  },<br>  {<br>    &quot;name&quot;: &quot;Fred&quot;,<br>    &quot;age&quot;: 20,<br>    &quot;isActive&quot;: true<br>  }<br>  ...<br>]</pre><p>Based on this we would expect and array of objects, each object having three attributes: name, age, and isActive. Our schema would map these to Spark types as such:</p><pre>schema = StructType([<br>    StructField(&quot;name&quot;, StringType(), True),<br>    StructField(&quot;age&quot;, IntegerType(), True),<br>    StructField(&quot;isActive&quot;, BooleanType(), True),<br>    # ... Define other fields based on the API&#39;s response<br>])</pre><h4>A note on performance.</h4><p>It’s important to point out that when you use a Python UDF with DataFrames, we incur the overhead cost of transferring data back and forth between the JVM and the Python process (Py4J). This serialization and deserialization can impact performance.³</p><p>That being said, even with this overhead, the higher-level optimizations provided by Catalyst and Tungsten (Spark’s internal optimization engines) can still make DataFrame operations faster than equivalent RDD operations in many cases (assuming you continue to work with the data after bringing it into memory).</p><p>If performance is absolutely paramount, consider writing your functions in Scala or Java. These functions will run within the JVM, eliminating the serialization/deserialization overhead and boosting overall execution efficiency.⁴</p><h4>Pagination problems.</h4><p>We’ve made really good progress, but the truth is that offset / limit strategies for pagination are on their way out: they’re just not the (optimal) tool of choice for API designers anymore. While they lend themselves nicely for parallelization, they come with a multitude of drawbacks, and have thus declined in popularity in favor of other, more robust methods.⁵ Modern APIs will instead favor the use of keyset pagination, and more specifically, <strong><em>cursors</em></strong>, for managing the retrieval of large datasets.⁶</p><p>In short, cursor-based pagination uses tokens that represent a unique record and its position in a sorted list of records. When a client makes a request, the server responds with a subset of records and a token pointing to the next record in the set. The client can then use this token as the cursor in <em>subsequent</em> requests, continuing this process until all desired data has been retrieved.</p><p>And therein lies the rub. By providing us with pagination values only <em>after</em> our initial request is complete, providers have effectively stripped us of concurrency, forcing us again into a sequential back-and-forth exchange. We will explore this topic in more detail in a follow-up post and provide a set of guidelines for dealing with these new constraints. While admittedly more involved, it is absolutely possible.</p><p>Thanks for reading.</p><h4>P.S. Be a good neighbor.</h4><p>A quick note on rate limits, proper etiquette… Make sure to enable the right level of parallelization, and let those processes paginate in the traditional sense (for loop within their own executor processes). Consider using bulk API when possible for initial seeding (REST API for incremental). Always remember that when dealing with external systems, the principle of being a “good citizen” applies: don’t overwhelm the system, handle errors gracefully, and respect the rules of the game laid out by the API provider.</p><h4>References</h4><ol><li>Bill Chambers and Matei Zahari. <em>Spark: The Definitive Guide</em>, O’Reilly, Sebastopol, CA, 2018, p. 111–113.</li><li>Chambers and Zahari, p. 60.</li><li>Cristofol Torrens. “Avoiding UDFs in Python.” <em>Damavis Blog</em>, 26 May 2021, <a href="https://blog.damavis.com/en/avoiding-udfs-in-apache-spark/">https://blog.damavis.com/en/avoiding-udfs-in-apache-spark/.</a></li><li>Chambers and Zahari, p. 113.</li><li>Michael Hahn. “Evolving API Pagination at Slack.” <em>Slack Engineering</em>, 2017, <a href="https://slack.engineering/evolving-api-pagination-at-slack/">slack.engineering/evolving-api-pagination-at-slack/.</a></li><li>Drew Martin. “Pagination with Relative Cursors.” <em>Shopify Engineering</em>, 12 August 2019, <a href="https://shopify.engineering/pagination-relative-cursors">https://shopify.engineering/pagination-relative-cursors</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c9c9ce89c9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>