What’s New in PySpark: TVFs, Subqueries, Plots, and Profilers
Summary
- TVFs and subquery API: PySpark now supports table-valued functions and the new subquery API, enabling more expressive, modular workflows—including custom TVFs via Python UDTFs on the Databricks Data and AI platform.
- Developer experience improvements: Plotting, profiling, and lateral joins make PySpark development more intuitive, with UDF logging and Python-native data sources coming soon on the Databricks Data and AI platform.
- Production pipeline capabilities: Build sophisticated data transformations and analysis workflows using the new PySpark features while maintaining code clarity and maintainability.
What’s New in PySpark: TVFs, Subqueries, Plots, and Profilers

Talk by Takuya Ueshin, Sr. Software Engineer, Databricks ; Xinrong Meng, Senior Software Engineer, Databricks
PySpark’s DataFrame API is evolving to support more expressive and modular workflows. In this video, we’ll introduce two powerful additions: table-valued functions (TVFs) and the new subquery API. You’ll learn how to define custom TVFs using Python User-Defined Table Functions (UDTFs), including support for polymorphism, and how subqueries can simplify complex logic. We’ll also explore how lateral joins connect these features, followed by practical tools for the PySpark developer experience—such as plotting, profiling, and a preview of upcoming capabilities like UDF logging and a Python-native data source API. Whether you're building production pipelines or extending PySpark itself, this talk will help you take full advantage of the latest features in the PySpark ecosystem.
Here’s more to explore:
Production ready data pipelines for analytics and AI: https://www.databricks.com/solutions/data-engineering
The Big Book of Data Engineering: https://www.databricks.com/resources/ebook/big-book-data-engineering-2nd-edition
See all the product announcements from Data + AI Summit: https://www.databricks.com/events/dataaisummit-2025-announcements
FAQs
What are table-valued functions (TVFs)?
TVFs are functions that return multiple rows (a table) rather than a single value—available in SQL and now in PySpark DataFrame APIs through custom UDTFs.
How do subqueries simplify code?
The new subquery API in PySpark allows you to write more modular, readable code by defining complex logic once and reusing it across transformations.
What are lateral joins?
Lateral joins connect TVFs with DataFrames, enabling patterns like exploding nested data while maintaining correlation with parent rows—useful for complex transformations.
When will UDF logging ship?
UDF logging and the Python-native data source API are upcoming features in the Databricks Data and AI platform roadmap—check release notes for availability.
Full transcript
Hi everyone. Uh thanks for uh coming to our talk. Um the this talk is uh what's new in pi spark. Uh we will introduce the new features in uh introduced in uh mainly uh spark 4. 0. Yeah. Um we are um uh int uh introducing this talk. Uh both both of us are uh datab bricks uh sen uh senior software engineers and also apach spark contributor commit and PMC members. uh we will uh go through these topics today and yeah let's uh uh go uh from the first topic um the first topic is table valued functions um yeah uh this is um uh as you may know uh this is um available in the SQL but uh the these are missing in the data frame APIs.
So, and these uh functions are returning the multiple roads uh possibly with um multiple commas rather than a single value. Uh in Spark uh this idea already exists uh functions like explode, inline and more. uh recently uh variant explode or something like that. Uh which take a column and uh return a table. Um but now in pispark you can also write your own custom TVs using userdefined table function or UDTF API. Uh that's what we'll dive into next.
Uh here's a quick example of uh one of the built-in table uh valid functions uh variants uh explode. Uh it takes a variant column in this case created by parsing a JSON string and returns a table of key value pairs. Uh this is a uh TVF used as a top level table. uh no joints yet, no correlation, uh just a function that outputs a table directly and just to note uh TVS are exposed through uh spark. tvf name space. So you call things like spark. tvf. variant explode something like that to use them uh from Python.
Uh later we'll see how to use TVFS within data frame pipelines using lateral joints. Uh before we talk about UDTFS uh let's take a look at the built-in TVFS that currently Spark provides. Uh these have been available in uh SQL but now uh available in data frame API. All of these TVFs are accessible uh through the TVF uh spark. tvf name space as I mentioned. Uh so you need to like spark. tvf explode blah blah blah spark TVf uh dot uh stack blah blah blah and so on.
And you can use them as a standalone tables or uh join them with other data frames. And uh we'll explore both patterns soon. Okay. And uh next topic is an uh Python UDF um or Python user defined table function. This is the way to define your own TVF using Python. Unlike scalar udfs uh which returns a single value uh udfs can uh return multiple rows for a single input row. You implement a UDF by writing a class with a e method that is rows using python's generator semantics or return an iterator uh of values. uh spunk will call this method uh for each input row and collect all the yielded results as a table.
UDFs are decorated with a at UD udf decorator uh which tells Spark how to uh register and use them similar to how the UD at UDF or at pandas UDF decorators work for UD udfs. Yeah, this is the simple UDF uh range with square. Uh it takes two arguments start and end. Yeah. And here is uh each integer in that range along with its square. The UDTF decorator registers the function and declares the output schema. Uh in this case two columns num and squared.
Internally the evil method is just a generator. Uh it loops through the range and use rows uh one at a time. Uh this is the uh clean way to express logic that needs to expand one input draw into many. And this shows a simple example of uh using the UDTF by passing two lits uh one and four. The result is the data frame with three rows, the numbers one through three and their squares. The output structure matches what we declared with the at UDTF decorator. two columns named num and square.
If the UDTF is registered, uh you can use you can also use it directly in SQL. For example, select star from range with square one and four. Uh this kind of interface makes uh UTFS convenient and uh consistent across both pi uh pispark and secure workloads. And um uh additional uh in addition to that um uh there's a polymorphic UDTF. Uh by default the normal UDT UDF have um um fixed return schema as we saw uh in the previous example.
But sometimes uh we want that schema to depend on the input. That's where polymorphic uh UDKF come in. Uh they allow you to define dynamic output schemas which are determined at runtime. For example, the number of output columns might depend on a parameter value or the type of the output might depend on the input type. To enable this, you define a static method called analyze inside your UDF class. This method receives argument metadata and returns the output uh sorry returns output schema as an analyze result object.
Note that if you define analyze method the return type passed to previously passed to at UDTF uh decorator should be omitted because it will be determined later. We'll look at the example uh of that next. Here's a polymorphic UDTF um example. Uh this is called repeat. It takes a value and a count and emits that value multiple times. This function isn't just generic in behavior. It's also generic in output type. The key is the analyze method.
Yeah. Uh, it inspects the argument types and dynamically returns a schema. In this case, a single column that inherits the type of the first argument. Uh, this makes the function type flexible uh while still enabling schema inference and validation. Um because reboot is a polymorphic UDTF, it adapts to different input types, string, integer and so on and carries the input uh carries that type uh into the output. uh in each case of these examples, the UDF UDTF uh provides uh produce the repeated values in a single CRM named X uh with the correct type automatically used.
Uh if you use integer as the value, the return type will be also integer. If it's string, uh the return type will be string. Uh this is one of the most powerful use cases uh for polymorphic UDTF. Uh defining a generic table behavior once and having it work uh many types with uh correct schema uh handling. Okay. Um next topic is a subquery dataf frame APIs. uh subquery is now supported in the dataf frame API uh not just in SQL.
Uh this enables nested logic and composible pipelines uh while keeping your code fully in Python. You can write both correlated and uncorrelated subqueries. The supported patterns include DF. exists and uh not DF. exist. exist for exist or not exist subqueries and also similarly if you call df. scala scalar uh it will uh be uh behave as the same as the sub uh scalar subquery that returns a single value and also uh call this is a column object call is in and pass to uh pass uh passing the df object uh this is for in sub queries uh this is actually supported from spark 4.
- Yeah. And uh these tools are key for uh writing modular and expressive uh python pispark pipelines and especially when joining with lat logic or udtfs. Here's an example of a correlated subquery in the dead frame API. Uh we are filtering customers to only um those who have at least one sales record with amount uh greater than 100. The some query uh on sales reference a column from the outer out outer customers query um specifically here a customer ID.
To do that uh we need to call dot outer against the column uh on the outer column uh making the correlation explicit. Uh this is just like writing exist blah blah blah in SQL uh but not fully in pispark code. Uh beyond exists um the data frame API supports a few more subqueries styles as I mentioned before. First scalar subqueries using dotscaler. Uh this exacts uh this extracts a single value from a subquery just like the SQL above.
Second um you can um express not exist using this um tilda not operator uh with um don't exists uh exactly how you'd invert any boolean expressions and third and final finally um spark 4. 1 as I mentioned before introduces in subqueries with all is in and take it should take a DF uh data frame object. Uh this lets you test membership of a value against the subquery's output. Again um very similar to SQL, these patterns let you stay fully within the data frame API uh while still writing powerful nested logic.
Yeah. Then um lateral join. Um next um the lateral join is one of the important uh feature of the subqueries related features. Um this is uh yeah lateral join allows you to uh join each row uh with the result of a function or subquery and that can depend on that row's values. And this is what makes row wise expansion possible such as calling udtf that takes uh input crs and returns uh multiple output rows in pi u pispark uh you use the lateral join to express this.
This replaces secret lateral join clause and works uh cleanly in code. Let's look at the some examples starting with a built-in TVF. Uh this is an example of a lateral join with a built-in TVF variant export again here. Uh we start by passing JSON strings into a variant columns using pass station JSON like what we did previously. But this time uh we select it as a column. uh previously it was uh like from the lat uh literal value but this time we can use the calm object com then we call the lateral join with the sparktf variant explode uh passing uh in the par using outer uh since it comes from the left table not in the explode variant explode uh this joins uh each input row with the exploded key value pairs of the JSON object uh producing multiple rows per input.
A clean row wise expansion. Now let's see the same pattern with the Python UDF. This is the same uh range with square UDTF uh as uh we saw earlier but now applied uh row wise with lateral join. For each row in the dead frame we invoke the UDTF with start and end as input and expand it into multiple output rows. Again dot outer is needed uh to reference columns from the left hand side. As you can see uh the input row uh one and four it generates three rows and for the uh for the in uh the other input one and 12 it generates two rows and put them all together.
Uh this is how Lateral joins generates to uh custom table logic uh giving you a powerful uh Python native way to express expansion and nested results. Alternatively um TVFS can take table argument entire data frames passed into the function for row wise processing. Although uh currently none of the uh built-in TVFS allow this, Python UDTF can take advantage of uh table arguments. To do this, you use the as table method uh to be more precise.
Oh, okay. Slide is right. dft as table method when passing the data frame as an argument. Uh this signals that it should be uh treated as a table argument inside the UDTF. Each row from the input table is passed individually to eval object just like a structured input record. Um this opens up powerful use cases where your UDTF can scan, filter, reshape rows coming from another dead frame uh one at a time. Yeah, this UDF repeat rows takes a table argument where uh where each row contains uh value x and a repeat count n inside eval.
We simply emit the value x repeated any times. Um this is a simple but powerful example of row wise expansion uh where a single input row results in multiple output rows. Uh UDTFs uh give you the flexibility to define these behaviors in pure Python uh while preserving schema and row structure. Okay, here's how we apply the repeat rows UDF. The input data frame has columns X and N and we call uh DF as table to pass it into the UDTF.
For the input one and three, we get three rows of 10 and for 20 and one, we get one row of 20. This makes it easy to implement calm fan out logic across structured rows and something not easily done with standard dead frame transforms alone. Um summary so far uh we've seen how these features work independently and now uh how they work together. T TVFs return structural row set uh either builtin or custom UDTFS. Sub queries allows um nested logic that makes your pipeline modular and expressive and lateral joints and table arguments are uh what tie these together enabling row wise application of table returning logic while supporting correlation and expansion patterns. together they uh let you build complex composible data pipelines uh without leaving the dataf frame API.
Okay, I'm going to switch here with Shinom. Please welcome her. Yeah, thanks for the great introduction. And now we are going to dive into the pass native plotting and EDF unified profiling. So let's talk about native plotting first. So in passbark data frames are are built for like big data processing. They are very good at it. But we didn't have builtin plotting. So it didn't pro provide the visualizations. users had to convert the data frame the passbach data frame to pandas frame or pandas on spark frame in order to do the plotting that's not very convenient and also like for pandas or pandas on spark frame they have the index column but the index concept does not exist in paspark so that adds friction also you have the performance and code complexity cost and that's why we introduced used passbark native plotting.
There's no convergent, no mismatch. You just like plot directly from your pass data frame and you can just call plot on your pass data frame and you can get the visualization and it work the same between the spark classic and spark connect and it's backed by the plotly library. The API matches the like what users already know from pandas or pandas on spark. You can use method chaining style like df. plot line for line plots or you can pass in the line to the can parameter of the plot API.
They both work. We support all common plot tabs. And here we categorize them by how much data they need. So first it's called like top n rows for plots like bar horizontal bar pi scatter plots. We just use the first n rows here. N equals to like 1,000 by default but it's configurable. It's fast and readable is very good for quick incess. And the second we call it sample data. So like for line and error plots for example they use sampling.
This work well for showing the trend in big data like in large data sets without scanning everything. And the third one is called global matrix. So plots like histograms, box plots or KD plots. They need the full data set to be accurate. So we compute full statistics to show the distribut distributions and outliers and this design balance both performance and data insights across different plot types. Here we will see a very simple example.
We have a very simple data frame. It shows the massly active users for products over several months and each row gives us the number of users for one product in that month. To visualize this, we use a grouped bar chart. So the xaxis shows the mass here and the yaxis indicates the users user cons. And each product will get a different color. And thanks to this like bar mode parameter. Bars are grouped side by side for comparison.
This is the output plot. It help us compare monthly usage across products. So for example we can quickly see like whether one product consistently consistently leaves in user count. Here is the product A. We can also use the line plot to show product growth trend. And this line chart shows like how each product sales changed over time. is useful for spotting trends and patterns mass to nas. So that's all for native plotting.
Now let's switch gears and talk about the profiling especially for UDF profiling. UDFs are powerful feature in passbar but it's also a performance blind spot because it runs on executtors like distributed computation. So it's hard to know like what's taking time or using memory. That's why we introduced like passbark U udf profiling and it consists of performance and memory profiling. It works for all types of UDFs and derived functions for example map in pandas.
It works consistently across spark classic and spark connect. It has a very simple set of API we will see later as well. and it support registered UDF. So even if you wrapped your UDF in a SQL statement, you can still get inside. So here's the API very simple. We have three API. So for show like spark. profile profile show. You can view the profiling results and to save the results you use the dump. And to reset everything and start fresh, we can call spark. p profofile. clear.
Now let's focus on the performance profiling. So it's great for identifying the like costly logic inside your userdefined functions. It uses the Python builtin C profile and it checks how many times each function is called in your UDF and how much time is spent. And like what's what's powerful is it runs across all exeutors. So we can see the distributed behavior in your summary and this helps identify the slow or inefficient logic in your UDF.
So this example shows how easy it is to profile a UDF. Here we define a very simple pandas UDF called add and like very intuitive just like add to a number. And here we register the performance profiler using the spark conf. And then we execute the UDF at one using like by the clite and then we call the show API we just mentioned. Here's the output of our performance profiler. So it shows that we have like 100 like like 1,800 function calls and the timing details.
So each line includes the function name, the number of calls and how much time was spent per call. And here the UDF ID in the profiling output it matches the one in the spark plan which can achieved by the explain API in passark. So you can easily trace which UDF you are profiling. So that's about performance profiling. Now let's look at memory profiling. So memory profiling, we can track how much memory each line of your UDF consumes and this can help us see like where memory usage specs which can help detect leaks or inefficiencies.
It works in a distributed context just as the performance profiler. So we can get the like the overview across exeutors. To enable it, we need to install the memory profiler library in your cluster. And here's a example. It uses the same pandas UDF as before like the ad one, but this time we register the memory profiler with this var and we execute the UDF. Finally, we call the show API to show the memory profile. Here is the output profile.
So it shows the line by line memory usage and memory increments and the occurrences like now let's see a few like real life scenarios where pass EDF profiling helps. So first you can find hot loops in your UDF by the performance profiler. It shows which function runs the most or take the most time. And second, the memory profiler can helps you catch lines of code in your UDF that consumes a lot of memory. For example, if you are preparing data for like for your ML model and there will be a lot of like temporary data created with this memory profiling tool, you can just like avoid the memory specs.
And third, we can compare like different EDF implementations and find the best tool. This is like like we will dive into the comparing UDF implementations like how the profiling tool can help us achieve that. There's a very simple but common step in data pipelines that is like we need to clean up the text. Let's say we have u a review data free and it just consists of like customer reviews in the string format. We often need to make that like the text consistent before using it.
So we turn we want to turn the text to lowerase and remove all the punctuations keep only words and in this way it's just like easy to count compare and analyze later. So the code defines a Python UDF which called normalized text and it token tokenize the like each row and lowercase the reveal string and again we register the parf profiler using the spark conf and we apply to the reveal column and execute the UDF. We want to show the profile result and we can clearly see that the function normalized text is actually called a million times because like the original data frame has like a million rows and Python UDF is executed like row by row.
So it's intuit that intuitive that like it's spam million calls of this function and it took three and a half seconds as cumulative time which include the called functions and then we want to try like how pandas udf works will it achieve a better performance. So we define a pandas udf here which is like vector rest and more efficient in general. We call it improved normalized text. It basically does the same thing lowerase your reveal text string and then tokenize it.
Again we register the parf performance like profiler and then apply to reveal column executed and finally show the profile result and in the vectorzed pandas udf case data is processed in batches like 5,000 rows per patch here and it results in only like 200 UDF calls total for the improved normalized text and for the cumulative time it takes around like 2. 1 seconds even though it has the same logic. So by switching from a scalar Python UDF to a vector pandas UDF, we reduced the cumulative runtime for the EDF from 3.
5 seconds to 2. 1 seconds. And this example runs only on a million rows. But as data scales, the performance gap widens. And in this case, appendas UDF is strongly preferred. So to summarize with native plotting, Passbark becomes more intuitive and accessible by providing your a set of plotting API that can apply directly to data frame. And with the unified UDF profiling, you can gain deep visibility into performance memory and helping you write more efficient and linear pass code.
That's all I wanted to share today and now let's welcome back Takuya to take us through like what's new in Pasbark. Thank you. Uh thank you. Uh yeah uh let's wrap up uh with a few uh highlights of what's available uh and what's in progress. Uh first uh Spark 4. 0 Z introduced the Python data source API as well uh which allows you to define Spark data source entirely in Python. Uh no JVM code uh required to uh uh to run this um data source.
Uh this opens the door to simpler connectors and uh testing tools and lightweight adapters. Uh actually I saw there are some sessions uh during this dice and about the Python data source uh so you may want to also join them. The second uh one is um arrow UD udfs. Uh this is um uh under actively um development. Uh this will be a fast modern replacement for pants UDFs. Uh operating directly on um arrow uh object arrow um batches without conversion uh to pandas.
Uh they are fully vectorized and uh promise both speed and uh simplicity. uh but they are still uh uh work in progress uh but I guess it will be available uh in spark 4. 1 uh thank you uh that's all uh from our uh Folks,
Learn more about the Databricks Data and AI platform.
The information provided herein is for general informational purposes only and may not reflect the most current product capabilities or configurations.