How to perform Left Anti Join in PySpark Azure Databricks?

Are you looking to find out how to perform left anti-join in PySpark on the Azure Databricks cloud or maybe you are looking for a solution, to find a method to do left anti-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 anti-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 anti-join in PySpark Azure Databricks.

In this blog, I will teach you the following with practical examples:

  • Syntax of join()
  • Left Anti Join using PySpark join() function
  • Left Anti 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()

What is the syntax of the join() function in PySpark Azure Databricks?

The syntax is as follows:

dataframe_name.join(other, on, how)
Parameter NameRequiredDescription
other (Dataframe)YesIt represents the second column to be joined.
on (str, list, or Column)YesA 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)OptionalIt represents join type, by default how=”inner”.
Table 1: join() Method in PySpark Databricks Parameter list with Details

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,"Rhianna",5),
    (2,"Avie",2),
    (3,"Keene",1),
    (4,"Guthry",1),
    (5,"Annamarie",2)
]

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  |Rhianna  |5      |
|2  |Avie     |2      |
|3  |Keene    |1      |
|4  |Guthry   |1      |
|5  |Annamarie|2      |
+---+---------+-------+
"""
# 2. Department Dataset
dept_df = spark.createDataFrame([(1,"civil")], schema=["id","name"])
dept_df.printSchema()
dept_df.show(truncate=False)

"""
root
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)

+---+-----+
|id |name |
+---+-----+
|1  |civil|
+---+-----+
"""

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 Anti Join in PySpark Azure Databricks using the join() function?

Before diving in, Let’s have a brief discussion about what is meant by Left Anti-Join. This join returns rows in the left DataFrame that have no 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, "left_anti").show()

# Method 2:
std_df.join(dept_df, std_df.dept_id == dept_df.id, "leftanti").show()

# The above codes generated the same output

"""
Output:

+---+---------+-------+
| id|     name|dept_id|
+---+---------+-------+
|  2|     Avie|      2|
|  5|Annamarie|      2|
|  1|  Rhianna|      5|
+---+---------+-------+
"""

In the above example, we can see that the output has only records which are not present in the department DataFrame. We have used “antijoin” and “anti_join” inside the join() function to perform left anti-join.

How to perform left anti-join in PySpark Azure Databricks using SQL expression?

In this section, let’s perform the left anti-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 ANTI JOIN department AS dept
    ON std.dept_id = dept.id
''').show()

"""
Output:

+---+---------+-------+
| id|     name|dept_id|
+---+---------+-------+
|  2|     Avie|      2|
|  5|Annamarie|      2|
|  1|  Rhianna|      5|
+---+---------+-------+
"""

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 left anti-join in PySpark using Azure Databricks?

This could be the possible reason:

To extract all the left DataFrame records which have no matching key column value in the right DataFrame.

Real World Use Case Scenarios for using left anti-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 anti-join extracts only the student DataFrame who has no matching department id in the department DataFrame.

What are the alternatives for performing left anti-join in PySpark using Azure Databricks?

There are multiple alternatives for left anti-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 anti-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.

PySpark in Azure Databricks, as explained by Arud Seka Berne S on azurelib.com.

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.