Are you looking to find out how to perform the inner join in PySpark on the Azure Databricks cloud or maybe you are looking for a solution, to find a method to do inner join in PySpark? If you are looking for any of these problem solutions, you have landed on the correct page. I will also show you how to use both PySpark and Spark SQL ways of doing an inner join in Azure Databricks. I will explain it with a practical example. So please don’t waste time let’s start with a step-by-step guide to understand perform inner join in PySpark Azure Databricks.
In this blog, I will teach you the following with practical examples:
- Syntax of join()
- Inner Join using PySpark join() function
- Inner Join using SQL expression
join() method is used to join two Dataframes together based on condition specified in PySpark Azure Databricks.
Syntax: dataframe_name.join()
Contents
- 1 What is the syntax of the join() function in PySpark Azure Databricks?
- 2 Create a simple DataFrame
- 3 How to perform Inner Join in PySpark Azure Databricks using the join() function?
- 4 How to perform inner join in PySpark Azure Databricks using SQL expression?
- 5 When should you use inner join in PySpark using Azure Databricks?
- 6 Real World Use Case Scenarios for using inner join in PySpark Azure Databricks?
- 7 What are the alternatives for performing inner join in PySpark using Azure Databricks?
- 8 Final Thoughts
What is the syntax of the join() function in PySpark Azure Databricks?
The syntax is as follows:
dataframe_name.join(other, on, how)
Parameter Name | Required | Description |
other (Dataframe) | Yes | It represents the second column to be joined. |
on (str, list, or Column) | Yes | A string for the join column name, a list of column names, a join expression (Column), or a list of Columns. If on is a string or a list of strings indicating the name of the join column(s), the column(s) must exist on both sides. |
how (str) | Optional | It represents join type, by default how=”inner”. |
Apache Spark Official Documentation Link: join()
Create a simple DataFrame
Gentle reminder:
In Databricks,
- sparkSession made available as spark
- sparkContext made available as sc
In case, you want to create it manually, use the below code.
from pyspark.sql.session import SparkSession
spark = SparkSession.builder
.master("local[*]")
.appName("azurelib.com")
.getOrCreate()
sc = spark.sparkContext
a) Create manual PySpark DataFrame
# 1. Student Dataset
student_data = [
(1,"Clara",2),
(2,"Conny",3),
(3,"Sallie",1),
(4,"Magdalene",3),
(5,"Palm",3)
]
std_df = spark.createDataFrame(student_data, schema=["id","name","dept_id"])
std_df.printSchema()
std_df.show(truncate=False)
"""
root
|-- id: long (nullable = true)
|-- name: string (nullable = true)
|-- dept_id: long (nullable = true)
+---+---------+-------+
|id |name |dept_id|
+---+---------+-------+
|1 |Clara |2 |
|2 |Conny |3 |
|3 |Sallie |1 |
|4 |Magdalene|3 |
|5 |Palm |3 |
+---+---------+-------+
"""
# 2. Department Dataset
dept_data = [
(1,"civil"),
(2,"mechanical"),
(3,"cse"),
(4,"it"),
(5,"ece")
]
dept_df = spark.createDataFrame(dept_data, schema=["id","name"])
dept_df.printSchema()
dept_df.show(truncate=False)
"""
root
|-- id: long (nullable = true)
|-- name: string (nullable = true)
+---+----------+
|id |name |
+---+----------+
|1 |civil |
|2 |mechanical|
|3 |cse |
|4 |it |
|5 |ece |
+---+----------+
"""
b) Creating a DataFrame by reading files
Download and use the below source file.
# replace the file_path with the source file location which you have downloaded.
std_df_2 = spark.read.format("csv").option("header", True).load(student_file_path)
std_df_2.printSchema()
dept_df_2 = spark.read.format("csv").option("header", True).load(department_file_path)
dept_df_2.printSchema()
"""
root
|-- id: long (nullable = true)
|-- name: string (nullable = true)
|-- dept_id: long (nullable = true)
root
|-- id: long (nullable = true)
|-- name: string (nullable = true)
"""
Note: Here, I will be using the manually created DataFrame.
How to perform Inner Join in PySpark Azure Databricks using the join() function?
Before diving in, let’s have a brief discussion about what is meant by Inner Join. This join returns rows that have matching values in both DataFrame. Let’s understand this with a simple example.
Example:
std_df.join(dept_df, std_df.dept_id == dept_df.id, "inner").show()
"""
Output:
+---+---------+-------+---+----------+
| id| name|dept_id| id| name|
+---+---------+-------+---+----------+
| 3| Sallie| 1| 1| civil|
| 1| Clara| 2| 2|mechanical|
| 2| Conny| 3| 3| cse|
| 4|Magdalene| 3| 3| cse|
| 5| Palm| 3| 3| cse|
+---+---------+-------+---+----------+
"""
In the above example, we can see that the output has only records which has match on both DataFrames. Also, by default join() function combine DataFrame using inner join method. Hence, it’s not mandatory to specify it.
If you don’t want duplicate columns while joining, try passing the joining column name in str or list[str] format. But this works only when you have same column name on both DataFrames. Therefore rename one of the joining column. No problem, if you don’t understand let’s do this with an example.
std_df.join(dept_df.withColumnRenamed("id", "dept_id"), "dept_id", "inner").show()
"""
Output:
+-------+---+---------+----------+
|dept_id| id| name| name|
+-------+---+---------+----------+
| 1| 3| Sallie| civil|
| 2| 1| Clara|mechanical|
| 3| 2| Conny| cse|
| 3| 4|Magdalene| cse|
| 3| 5| Palm| cse|
+-------+---+---------+----------+
"""
How to perform inner join in PySpark Azure Databricks using SQL expression?
In this section, let’s perform the inner join using SQL expressions. In order to use a raw SQL expression, we have to convert our DataFrame into a SQL view.
std_df.createOrReplaceTempView("student")
dept_df.createOrReplaceTempView("department")
Example:
spark.sql('''
SELECT *
FROM student AS std
JOIN department AS dept
ON std.dept_id = dept.id
''').show()
"""
Output:
+---+---------+-------+---+----------+
| id| name|dept_id| id| name|
+---+---------+-------+---+----------+
| 3| Sallie| 1| 1| civil|
| 1| Clara| 2| 2|mechanical|
| 2| Conny| 3| 3| cse|
| 4|Magdalene| 3| 3| cse|
| 5| Palm| 3| 3| cse|
+---+---------+-------+---+----------+
"""
I have attached the complete code used in this blog in notebook format to this GitHub link. You can download and import this notebook in databricks, jupyter notebook, etc.
When should you use inner join in PySpark using Azure Databricks?
This could be the possible reason:
To extract all the Left DataFrame and Right DataFrame records that satisfy the joining column condition.
Real World Use Case Scenarios for using inner join in PySpark Azure Databricks?
Assume that you have a student and department data set. The student dataset has the student id, name, and department id. And the department dataset has the department id and name of that department. You want to fetch all the students and their corresponding department records. The inner join extracts all the left and right DataFrame which satisfy the joining column conditions.
What are the alternatives for performing inner join in PySpark using Azure Databricks?
There are multiple alternatives for inner join in PySpark DataFrame, which are as follows:
- DataFrame.join(): used for combining DataFrames
- Using PySpark SQL expressions
Final Thoughts
In this article, we have learned about how to perform inner join in PySpark Azure Databricks along with the examples explained clearly. I have also covered different scenarios with practical examples that could be possible. I hope the information that was provided helped in gaining knowledge.
Please share your comments and suggestions in the comment section below and I will try to answer all your queries as time permits.
- For Azure Study material Join Telegram group : Telegram group link:
- Azure Jobs and other updates Follow me on LinkedIn: Azure Updates on LinkedIn
- Azure Tutorial Videos: Videos Link
- Azure Databricks Lesson 1
- Azure Databricks Lesson 2
- Azure Databricks Lesson 3
- Azure Databricks Lesson 4
- Azure Databricks Lesson 5
- Azure Databricks Lesson 6
- Azure Databricks Lesson 7
As a big data engineer, I design and build scalable data processing systems and integrate them with various data sources and databases. I have a strong background in Python and am proficient in big data technologies such as Hadoop, Hive, Spark, Databricks, and Azure. My interest lies in working with large datasets and deriving actionable insights to support informed business decisions.