Are you looking to find out how to perform left semi-join in PySpark on the Azure Databricks cloud or maybe you are looking for a solution, to find a method to do left semi-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 a left semi-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 left semi-join in PySpark Azure Databricks.
In this blog, I will teach you the following with practical examples:
- Syntax of join()
- Left Semi Join using PySpark join() function
- Left Semi Join using SQL expression
The PySpark join() function is used to joinleft DataFrame with the right DataFrame based on column index position or key column.
data_frame.join()
Contents
- 1 What is the syntax of the join() function in PySpark Azure Databricks?
- 2 Create a simple DataFrame
- 3 How to perform Left Semi Join in PySpark Azure Databricks using the join() function?
- 4 How to perform left semi-join in PySpark Azure Databricks using SQL expression?
- 5 When should you use the left semi-join in PySpark using Azure Databricks?
- 6 Real World Use Case Scenarios for using left semi-join in PySpark Azure Databricks?
- 7 What are the alternatives for performing left semi-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)
]
"""
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 Left Semi Join in PySpark Azure Databricks using the join() function?
Before diving in, Let’s have a brief discussion about what is meant by Left Semi-Join. This join returns only rows in the left DataFrame that have matching rows in the right DataFrame. Let’s understand this with a simple example.
Example:
# Method 1:
std_df.join(dept_df, std_df.dept_id == dept_df.id, "semi").show()
# Method 2:
std_df.join(dept_df, std_df.dept_id == dept_df.id, "leftsemi").show()
# Method 3:
std_df.join(dept_df, std_df.dept_id == dept_df.id, "left_semi").show()
# The above codes generated the same output
"""
Output:
+---+---------+-------+
| id| name|dept_id|
+---+---------+-------+
| 3| Sallie| 1|
| 1| Clara| 2|
| 2| Conny| 3|
| 4|Magdalene| 3|
| 5| Palm| 3|
+---+---------+-------+
"""
In the above example, we can see that the output has only left dataframe records which are present in the department DataFrame. We can use “semi”, “leftsemi” and “left_semi” inside the join() function to perform left semi-join.
How to perform left semi-join in PySpark Azure Databricks using SQL expression?
In this section, let’s perform the left semi-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
LEFT SEMI JOIN department AS dept
ON std.dept_id = dept.id
''').show()
"""
Output:
+---+---------+-------+
| id| name|dept_id|
+---+---------+-------+
| 3| Sallie| 1|
| 1| Clara| 2|
| 2| Conny| 3|
| 4|Magdalene| 3|
| 5| Palm| 3|
+---+---------+-------+
"""
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 the left semi-join in PySpark using Azure Databricks?
This could be the possible reason:
To extract all the left DataFrame records which have a matching key column value in the right DataFrame.
Real World Use Case Scenarios for using left semi-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 left semi-join extracts only the student DataFrame who has a matching department id in the department DataFrame.
What are the alternatives for performing left semi-join in PySpark using Azure Databricks?
There are multiple alternatives for left semi-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 left semi-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.