Scala
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Scala
-
Section 4: Functional Scala
-
Section 5: Collections in Depth
-
Section 6: Type System
-
Section 7: Concurrency and Ecosystem
-
Section 8: Practical Projects
-
Section 9: Interview Practice
-
Section 10: Data Structures and Algorithms in Scala
-
Section 11: More Practice Exercises
-
Section 12: Advanced Functional Patterns
-
Section 13: More Ecosystem
-
Section 14: Scala Collections Library Deep Dive
-
Section 15: Scala Standard Library Deep Dive
-
Section 16: Akka Ecosystem Deep Dive
-
Section 17: Cats and Cats Effect Deep Dive
-
Section 18: Play Framework Deep Dive
-
Section 19: Apache Spark with Scala Deep Dive
-
Section 20: Scala Build Tools Deep Dive
-
Section 21: Scala 3 Specific Features
-
90: Union and Intersection Types
-
Section 22: Scala Testing Deep Dive
-
Section 23: Functional Domain Modeling
-
Section 24: More Data Structures and Algorithms in Scala
-
Section 25: Scala for Data Engineering
-
Section 26: More Practical Projects
-
Section 27: More Interview and Review
-
Section 28: ZIO Ecosystem Deep Dive
-
Section 29: Scala for Machine Learning
-
Section 30: Scala Microservices Architecture
-
Section 31: Scala Type System Deep Dive
-
Section 32: More Practice and Drills
-
Section 33: Scala Performance Deep Dive
-
Section 34: Scala Ecosystem Tooling
-
Section 35: Scala for Reactive Systems
-
Section 36: More Real-World Case Studies
-
Section 37: Scala for Financial Systems
-
Section 38: Scala GraphQL and gRPC
-
Section 39: More Final Projects
-
Section 40: More Interview and Final Review
-
Section 41: Scala for Streaming Data
-
Section 42: Scala Security Practices
-
Section 43: More Language Deep Dive
-
Section 44: Scala Command-Line Tools
-
Section 45: Scala Documentation and Style
-
Section 46: Scala Dependency Management
-
Section 47: More Practical Backend Patterns
-
Section 48: Scala for Event-Driven Architecture
-
Section 49: More Practice Drills Round 2
-
Section 50: Scala Compiler Deep Dive
-
Section 51: Scala for Web Frontends
-
Section 52: More Data Engineering Practice
-
Section 53: Scala Observability
-
Section 54: More Advanced Practice Projects
-
Section 55: Scala for Legacy Java Integration
-
Section 56: More Testing Practice
-
Section 57: Final Mastery Review
-
Section 58: Scala History and Ecosystem Context
-
Section 59: More Concurrency Patterns
-
Section 60: Scala for Configuration Management
-
Section 61: More Domain Modeling Practice
82: Spark SQL from Scala
Up until now, we've spent a lot of time in the Scala-native side of Spark, using the Dataset and DataFrame APIs. But let's be honest: sometimes, writing a complex join or a nested aggregation in the DSL feels like you're fighting the language. That's where Spark SQL comes in. It allows us to write raw SQL queries against our data while still staying inside our Scala application.
Setting up the SparkSession
To use Spark SQL, everything revolves around the SparkSession. You've seen this before, but remember that the session is your gateway to the SQL engine. For this example, let's imagine we have a CSV file called web_logs.csv containing website traffic data: IP addresses, page paths, timestamps, and HTTP status codes.
val spark = SparkSession.builder()
.appName("LogAnalyzer")
.master("local[*]")
.getOrCreate()
Loading the logs into a DataFrame
Before we can run SQL, we need data in the system. I'll load the CSV into a DataFrame. I'm using inferSchema here because it's faster for small prototypes, though in a production pipeline, I'd strongly recommend defining a proper case class or schema to avoid the overhead of a second pass over the data.
val logsDF = spark.read
.option("header", "true")
.option("inferSchema", "true")
.csv("web_logs.csv")
The "missing view" mistake
Here is where I usually trip up when I'm switching back and forth between the DataFrame API and SQL. I'll try to run a query to find all the 404 errors on our site.
// This will fail!
val errors = spark.sql("SELECT * FROM logsDF WHERE status = 404")
errors.show()
If you run this, Spark will throw an AnalysisException telling you that the table logsDF doesn't exist. It's a common point of confusion: Spark SQL doesn't automatically know about the Scala variables in your code. The SQL engine operates on a catalog of tables and views, not your JVM variable names.
To fix this, I have to register the DataFrame as a temporary view. This creates a pointer in the Spark catalog that the SQL engine can actually see.
logsDF.createOrReplaceTempView("web_logs")
// Now this works perfectly
val errors = spark.sql("SELECT * FROM web_logs WHERE status = 404")
errors.show()
Aggregating the "broken" pages
Now that we have a view, let's do something useful. I want to find the top 5 pages that are returning 404s so the dev team knows what to fix first. I could do this with groupBy and count in the Scala API, but a SQL string is much more readable for this specific logic.
val brokenPages = spark.sql("""
SELECT page_path, COUNT(*) as error_count
FROM web_logs
WHERE status = 404
GROUP BY page_path
ORDER BY error_count DESC
LIMIT 5
""")
brokenPages.show()
I used a triple-quoted string (""") here. It's a Scala trick that lets me write the SQL over multiple lines without needing concatenation, which keeps the query legible. You'll notice that spark.sql() returns a DataFrame. This is the beauty of the system: you can start with a DataFrame, switch to SQL for a complex transformation, and then go back to using Scala functions for the final output.
📋 Practical Task
Analyzing Product Sales with Spark SQL
You have a dataset called sales_data.csv with the following columns: product_id (Integer), category (String), amount (Double), and sale_date (String).
Write a Scala program that:
- Initializes a
SparkSession. - Reads the
sales_data.csvfile into a DataFrame. - Registers that DataFrame as a temporary view named
sales. - Uses
spark.sql()to calculate the total revenue (sum ofamount) for eachcategory, but only for categories that have generated more than $1,000 in total sales. - Orders the result by total revenue in descending order.
- Prints the resulting DataFrame to the console.
There are no comments for now.