cancel
Showing results for 
Search instead for 
Did you mean: 
Data Engineering
Join discussions on data engineering best practices, architectures, and optimization strategies within the Databricks Community. Exchange insights and solutions with fellow data engineers.
cancel
Showing results for 
Search instead for 
Did you mean: 

Apply expectations only if column exists

Hoviedo
New Contributor III

Hi, is there any way to apply a expectations only if that column exists? I am creating multiple dlt tables with the same python function so i would like to create diferent expectations based in the table name, currently i only can create expectations for those column that exists in all the tables created for the python function

thanks

3 REPLIES 3

Walter_C
Databricks Employee
Databricks Employee

To apply expectations only if a column exists in Delta Live Tables (DLT), you can use the @Dlt.expect decorator conditionally within your Python function. Here is a step-by-step approach to achieve this:

  1. Check if the Column Exists: Before applying the expectation, check if the column exists in the DataFrame.
  2. Apply Expectations Conditionally: Use the @Dlt.expect decorator only if the column is present.

Hoviedo
New Contributor III

Hi Walter, sorry what would it look like in the code?

i can do this in the python function (it does nothing)

if "Distance" in df.columns:
            dlt.expect("Distance is positive", "Distance >= 0")
 
but i am now sure how can i apply the same with the decorator

Hoviedo
New Contributor III
def get_changes_from_raw(table_name):
    @Dlt.table(
        name=f"{table_name}_changes",
        comment=f"New {table_name} data incrementally ingested from cloud object storage landing zone",
    )
    @Dlt.expect("valid_rescued_data", "_rescued_data is null")
    def read_changes_from_adl2():
          df = spark.read...
 
          if "distance" in df.columns:
              dlt.expect("distance is positive", "distance >= 0")

Connect with Databricks Users in Your Area

Join a Regional User Group to connect with local Databricks users. Events will be happening in your city, and you won’t want to miss the chance to attend and share knowledge.

If there isn’t a group near you, start one and help create a community that brings people together.

Request a New Group