<?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 Marty Jackson on Medium]]></title>
        <description><![CDATA[Stories by Marty Jackson on Medium]]></description>
        <link>https://medium.com/@mfjackson?source=rss-1d5549ed0282------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*r47AsA9idzWdgU3UoTQrTw.jpeg</url>
            <title>Stories by Marty Jackson on Medium</title>
            <link>https://medium.com/@mfjackson?source=rss-1d5549ed0282------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:32:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mfjackson/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[Using the Spark Aggregator class in Scala]]></title>
            <link>https://medium.com/data-science/using-the-spark-aggregator-class-in-scala-341ee8bb46e5?source=rss-1d5549ed0282------2</link>
            <guid isPermaLink="false">https://medium.com/p/341ee8bb46e5</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[aggregator]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Marty Jackson]]></dc:creator>
            <pubDate>Thu, 16 Apr 2020 23:08:07 GMT</pubDate>
            <atom:updated>2020-04-19T02:49:15.822Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Note: </strong>If you already understand the Aggregator class and simply want to view an example of how it’s implemented in Scala, feel free to skip to the “<em>Using our Aggregators</em>” section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JS1jttKlhdNYHV0P" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Type-safe Aggregations</strong></h3><p><strong><em>What are they?</em></strong></p><p>You’re in an airport waiting for your luggage at the baggage claim. The internal turmoil is rising inside of you, as most other passengers have received their luggage by now and you sure don’t want to lose your clothes, your toiletries, or that bottle of deluxe craft beer you checked. Just as you start to despair, you see it: a large, bright orange suitcase that is clearly yours. Gleefully, you pick it up and a smile just begins to cross your face — until you notice a drip from the zipper. And then another. And another. While the bag itself is in the same condition as it was when you checked it, its contents are soaked. You can’t help but wonder, <em>When did this happen? Was it the low pressure in the plane? Did it fall off of a cart? Should I have used bubble wrap?</em> Unfortunately, you don’t really have any way of knowing. Although you should have used bubble wrap.</p><p>A similar feeling of distress occurs when a Data Scientist performs an aggregation on a Dataset in Spark, only for the contents of the output Dataset to be revealed as invalid in some way; maybe the input and output were both intact Datasets, but something about the output’s content type is incorrect. The internal mechanisms of the aggregation and what went wrong can typically only be diagnosed after a significant amount of detective work. Even then, there’s no guarantee that future instances of input data won’t cause another issue for the aggregation.</p><p>However, just like adding more bubble wrap to prevent a bottle breaking in your suitcase, we can create custom aggregations that are strongly typed throughout using Spark’s Aggregator class. This class allows a Data Scientist to specify exactly what transformations worker nodes perform, how data is combined across nodes, and what each step should entail in terms of expected input and output type. The result is an intimate knowledge of how an aggregation transformation is being performed and an automated way to diagnose any typing issues that might arise. In other words, it’s a foolproof way to save your bottle of beer next time you fly.</p><p><strong><em>When to use type-safe aggregations</em></strong></p><p>Deciding whether to perform type-safe aggregations on Spark Datasets can be a difficult decision. On the one hand, it’s tempting to throw caution to the wind, declare the input and output types as Dataset, and call it a day. From my experience, this works for many of the exploratory and analytic instances a Data Scientist might encounter, as data and type validations can be performed on-the-fly in a notebook or scripting environment.</p><p>On the other hand, there are instances (e.g. automated ML pipelines in production, creating an API for other Data Scientists) when you need to ensure a transformation won’t be yielding unexpected and potentially errant results without warning. These are the cases when you’ll want to use the <a href="https://spark.apache.org/docs/2.0.2/api/java/org/apache/spark/sql/expressions/Aggregator.html">Aggregator</a> class in Spark. This class allows a Data Scientist to identify the input, intermediate, and output types when performing some type of custom aggregation.</p><p>I found Spark’s Aggregator class to be somewhat confusing when I first encountered it. There are several steps, seemingly unused parameters, and limited examples online. Most of the examples I’ve seen tend to outline simple use-cases like summing a collection of integers or calculating an average. While these are certainly useful for tautological purposes, they don’t offer much insight into other common aggregations that one might need to perform. Thus, my aim here is to demonstrate <em>two</em> uses of the Aggregator class that one might actually use in writing a data preprocessing application and break them down line-by-line.</p><h3><strong>An `</strong><strong>Aggregator` example</strong></h3><p>Let’s suppose you have the following retail data for a home improvement store</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7a6b21a13f160c45cc56f4447d2bc2b/href">https://medium.com/media/c7a6b21a13f160c45cc56f4447d2bc2b/href</a></iframe><p>and want to do the following in a type-safe manner:</p><ul><li>provide a count of how many unique customers appear in each retailCategory</li><li>collect an array of unique productIDs, grouped by retailCategory</li><li>transform the above data into a Dataset that contains the previous two steps</li></ul><p>Let’s also suppose we want to use the following general structure for implementing our aggregators:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4acdddaacc548e12ca128a5e54692ddd/href">https://medium.com/media/4acdddaacc548e12ca128a5e54692ddd/href</a></iframe><p>Which will result in a Data Scientist calling the following API when using our library:</p><pre>val myValue = DoSomething.transformData(…)</pre><p>Note that we are creating an object that contains the method we want to use to perform our aggregation, as well as both of our aggregators that we want to use within that method. This differs from many other examples I’ve seen online for two reasons. Firstly, we are attempting to create an API for a Data Scientist to use during a data preprocessing stage rather than creating a workflow to call with some mainApp object. Secondly, we are building more than two aggregators used by the same transformation.</p><p>The first items on our to do list are to import the Aggregator class, the ExpressionEncoder class, create a case class for the input data schema shown above, and create another case class for our output schema:</p><pre>import org.apache.spark.sql.expressions.Aggregator<br>import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder</pre><pre>// input schema<br>case class RetailByCustomer(customerID: String,<br>  productID: String,<br>  retailCategory: String)</pre><pre>// output schema<br>case class AggRetailByCategory(retailCategory: String, <br>  customerCount:Int,<br>  productSet: Set[String])</pre><p><strong>Note</strong>: We need to import the ExpressionEncoder class in order to define our own encoder for a Set[String] type, as this is not a default encoder in Scala.</p><p>Now we get to write our aggregators. I’ll show both of them in full now and then break them down line-by-line.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e31e24ab7790e408c3b999f7f8403d3/href">https://medium.com/media/3e31e24ab7790e408c3b999f7f8403d3/href</a></iframe><p>As you might infer from the value name, our first aggregator provides a count of distinct customers. This is done by adding each customer to a Set, as sets only include one instance of any given value. It’s also important to use a distinct count in this scenario in order to avoid overcounting in situations where incoming data may include duplicates or productID values that don’t map to any retailCategory. Now, let’s take a look at the first line:</p><pre>val distinctCustomerCountAggregator: <br>  TypedColumn[RetailByCustomer, Int] = new<br>    Aggregator[RetailByCustomer, Set[String], Int]</pre><p>Here we are declaring a value that will return a <a href="https://spark.apache.org/docs/2.2.1/api/java/org/apache/spark/sql/TypedColumn.html">TypedColumn</a> with the expected input (RetailByCustomer — an <a href="https://jaceklaskowski.gitbooks.io/mastering-spark-sql/spark-sql-Expression.html">Expression</a>) and the expected output (Int — an <a href="https://jaceklaskowski.gitbooks.io/mastering-spark-sql/spark-sql-ExpressionEncoder.html">ExpressionEncoder</a>). We’re setting this value equal to a new Aggregator and defining the input type (RetailByCustomer), the intermediate type (Set[String]), and the output type (Int). That is, this Aggregator will expect to take in some type defined in our RetailByCustomer case class, perform some type of transformation that will result in a Set[String] type, and return some value of type Int after aggregation.</p><p>Now onto the meat of the function. But first, here’s a puppy to break up the monotony and refresh your soul a bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JHMDoW_aJJ7aQNp2" /><figcaption>Photo by <a href="https://unsplash.com/@freestocks?utm_source=medium&amp;utm_medium=referral">freestocks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you’re reading this article, you probably know that Spark is a framework for performing data transformations in a distributed fashion, so you probably know that there is a master node that sends out tasks to worker node executors to perform data transformations. But what tasks do you send to the worker nodes to work together when performing an aggregation across the entire dataset?</p><p>The way I like to think about it at a <em>high level</em> starts with individual worker nodes. The Aggregator class sends tasks to an executor on an individual worker node (and all other worker nodes active for the job) on how to begin an aggregation:</p><pre>override def zero: Set[String] = Set[String]()</pre><p>That is, in our case, each worker node should start the aggregation with an empty set of type String.</p><p>Next, the Aggregator class tells each worker node what to do with the data it has in memory:</p><pre>override def reduce(es: Set[String], rbc: RetailByCustomer):<br>  Set[String] = es + rbc.customerID</pre><p>The instructions in our reduce definition are telling each worker node to expect inputs of es, our “empty set” from the previous step, and rbc, our RetailByCustomer case class defined above. Additionally, the output of this transformation on each worker node is going to result in an expected type Set[String]. Lastly, the actual transformation to take place on each worker node is defined. Each in-memory value stored as a type RetailByCustomer.customerID (which we defined as a String) is added to the existing empty set, resulting in a Set[String] containing distinct customer IDs.</p><p>To see this in practice, suppose our data has been partitioned by retailCategory, such that information about “Lighting” and “Gardening” is stored on one worker node, “A.C.” and “Cleaning” are stored on a second node, and “Paint” is stored on a third node. The resulting sets on each node should look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SdY-uwql5crcBeE8_PZVww.png" /></figure><p>Now that the transformation of finding unique customerIDs has been performed on each worker node, the Aggregator class has to instruct the worker nodes how to interact with each other in order to find unique customerIDs <em>across</em> nodes. This brings us to the merge definition:</p><pre>override def merge(wx: Set[String], wy: Set[String]): <br>  Set[String] = wx.union(wy)</pre><p>Here, we are defining the two expected inputs as type Set[String]; one from “Worker X” (wx) and one from “Worker Y” (wy). Again, we define the expected output type as Set[String]. Lastly, the Aggregator class has to give instructions on what each worker node should do when interacting with the others. In this case, we tell each worker to union the output from the reduce step with the other worker’s reduce output (i.e. return all elements between the two sets).</p><p>While there’s much more nuance to how information is passed across worker nodes, for the purposes of understanding the Aggregator class we can visualize the output of the merge step as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5xdOKT1dnqgNG8VQOORMLg.png" /><figcaption>Hypothetical visualization of what our workers nodes would return if they didn’t union results.</figcaption></figure><p>which will result in the output “Set(“001”, “005”, “003”, “004”, “002”)” of type Set[String].</p><p>The next step, finish, provides instructions for the driver to perform an action:</p><pre>override def finish(reduction: Set[String]): Int = reduction.size</pre><p>Here, we define the expected input type as our unioned Set[String] and expected output type as Int. We also define the action to be taken on the Set[String] input by calling the size method, which returns an integer representing the number of items in the set. In the case of our example, this returns 5.</p><p>The last step is to define the Encoder for both our buffer (or intermediate) step and output step:</p><pre>override def bufferEncoder: Encoder[Set[String]] =<br>  implicitly(ExpressionEncoder[Set[String]])</pre><pre>override def outputEncoder: Encoder[Int] =<br>  implicitly(Encoders.scalaInt)</pre><p>The output for distinctCustomerCountAggregator is an Int, which has a predefined encoder in Scala. Thus, we can simply call Encoders.scalaInt when defining our outputEncoder and pass it implicitly to the other definitions. However, although both Set and String have predefined encoders in Scala, Set[String] does not. Therefore, we have to define our own Set[String] encoder using the ExpressionEncoder class that was imported in the first step.</p><p>productIDAggregator is actually quite similar to the distinctCustomerCountAggregator except for one key difference: we are expecting an output of type Set[String] rather than Int. This will change a couple of the steps.</p><p><strong>Exercise</strong>:<em> If you’re reading this article in full, I encourage you to think which steps will need to be changed in order to facilitate this before moving on (hint: there are 3).</em></p><p>The first difference involves changing both the TypedColumn and expected Aggregator output types to Set[String]:</p><pre>val productIDAggregator: <br>  TypedColumn[RetailByCustomer, Set[String]] =<br>    new Aggregator[RetailByCustomer, Set[String], Set[String]]</pre><p>The next three steps are actually the same for both aggregators: we instruct the worker nodes to create empty sets, add productIDs to those sets, and union the resulting sets across themselves.</p><p>The second difference, however, appears in the finish definition. We want to change the expected output type from Int to Set[String] and eliminate the size method, as we just want to return the actual set of productIDs:</p><pre>override def finish(reduction: Set[String]): Set[String] = reduction</pre><p>Lastly, we need to change the outputEncoder. Since we’re not really transforming between types in this case, our bufferEncoder and outputEncoder will be the same:</p><pre>override def bufferEncoder: Encoder[Set[String]] =<br>  implicitly(ExpressionEncoder[Set[String]])</pre><pre>override def outputEncoder: Encoder[Set[String]] =<br>  implicitly(ExpressionEncoder[Set[String]])</pre><p>And that’s it! We’ve created two aggregators that perform two distinct functions!</p><h3><strong>Using our Aggregators</strong></h3><p>To use these in practice, let’s take a look at the full code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24308d12e4a91bf168b36f88fdfb0ac6/href">https://medium.com/media/24308d12e4a91bf168b36f88fdfb0ac6/href</a></iframe><p>After compiling and publishing the code above, a Data Scientist can call the following when building a data transformation pipeline (or you can just call it at the bottom of the file):</p><pre>import com.wherever.code.is.PreprocessData</pre><pre>val retailData = Seq(<br>(&quot;001&quot;, &quot;zk67&quot;, &quot;Lighting&quot;),<br>(&quot;001&quot;, &quot;gg89&quot;, &quot;Paint&quot;),<br>(&quot;002&quot;, &quot;gg97&quot;, &quot;Paint&quot;),<br>(&quot;003&quot;, &quot;gd01&quot;, &quot;Gardening&quot;),<br>(&quot;003&quot;, &quot;af83&quot;, &quot;A.C.&quot;),<br>(&quot;003&quot;, &quot;af84&quot;, &quot;A.C.&quot;),<br>(&quot;004&quot;, &quot;gd77&quot;, &quot;Gardening&quot;),<br>(&quot;004&quot;, &quot;gd73&quot;, &quot;Gardening&quot;),<br>(&quot;005&quot;, &quot;cl55&quot;, &quot;Cleaning&quot;),<br>(&quot;005&quot;, &quot;zk67&quot;, &quot;Lighting&quot;),<br>).toDF(&quot;customerID&quot;, &quot;productID&quot;, &quot;retailCategory&quot;)</pre><pre>val transformedRetailData = PreprocessData.createArrayAndCount(retailData)</pre><p>where the shown output of val transformedRetailData should look something like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wbgbXnaWNeXawFvTmuInog.png" /></figure><h3><strong>Conclusions</strong></h3><ul><li>Type-safe aggregations allow Data Scientists to specify how transformations are being undertaken, how data is combined within and across nodes, and what each step should entail in terms of expected input and output type.</li><li>Use Spark’s Aggregator class to perform type-safe transformations. The typical use-case is in a production-level environment, writing an API, or when you plan on repeated use of an aggregation.</li><li>Understanding what is happening under the hood in Spark at a high level is important in understanding how the Aggregator class works.</li></ul><h4><strong><em>Reaching out</em></strong></h4><p>Thanks for reading this article! Please feel free to reach out with any comments/questions below or via <a href="https://twitter.com/martainyo">Twitter</a>. You can also visit my personal site: <a href="http://mfjackson.github.com/">mfjackson.github.com</a>. I’m constantly learning and looking to improve my knowledge of all things Data Science, so if I’ve made any erroneous statements or you know of a better methodology than the one in this article, please let me know!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=341ee8bb46e5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/using-the-spark-aggregator-class-in-scala-341ee8bb46e5">Using the Spark Aggregator class in Scala</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>