-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathdqx_demo_library.py
306 lines (231 loc) · 7.55 KB
/
dqx_demo_library.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# Databricks notebook source
# MAGIC %md
# MAGIC # Using DQX as a Library
# COMMAND ----------
# MAGIC %md
# MAGIC ### Installation of DQX in the cluster
# COMMAND ----------
# MAGIC %pip install databricks-labs-dqx
# COMMAND ----------
dbutils.library.restartPython()
# COMMAND ----------
# MAGIC %md
# MAGIC ### Generate quality rule candidates using Profiler
# COMMAND ----------
from databricks.labs.dqx.profiler.profiler import DQProfiler
from databricks.labs.dqx.profiler.generator import DQGenerator
from databricks.labs.dqx.profiler.dlt_generator import DQDltGenerator
from databricks.sdk import WorkspaceClient
import yaml
schema = "col1: int, col2: int, col3: int, col4 int"
input_df = spark.createDataFrame([[1, 3, 3, 1], [2, None, 4, 1]], schema)
ws = WorkspaceClient()
profiler = DQProfiler(ws)
summary_stats, profiles = profiler.profile(input_df)
print(summary_stats)
print(profiles)
# generate DQX quality rules/checks
generator = DQGenerator(ws)
checks = generator.generate_dq_rules(profiles) # with default level "error"
print(yaml.safe_dump(checks))
# generate DLT expectations
dlt_generator = DQDltGenerator(ws)
dlt_expectations = dlt_generator.generate_dlt_rules(profiles)
print(dlt_expectations)
# COMMAND ----------
# MAGIC %md
# MAGIC ## Validate quality checks
# COMMAND ----------
import yaml
from databricks.labs.dqx.engine import DQEngine
from databricks.sdk import WorkspaceClient
checks = yaml.safe_load("""
- criticality: "invalid_criticality"
check:
function: "is_not_null"
arguments:
col_names:
- "col1"
- "col2"
""")
dq_engine = DQEngine(WorkspaceClient())
status = dq_engine.validate_checks(checks)
print(status.has_errors)
print(status.errors)
# COMMAND ----------
# MAGIC %md
# MAGIC ## Apply quality rules using yaml-like dictionary
# COMMAND ----------
import yaml
from databricks.labs.dqx.engine import DQEngine
from databricks.sdk import WorkspaceClient
checks = yaml.safe_load("""
- criticality: "error"
check:
function: "is_not_null"
arguments:
col_names:
- "col1"
- "col2"
- criticality: "error"
check:
function: "is_not_null_and_not_empty"
arguments:
col_name: "col3"
- criticality: "warn"
check:
function: "value_is_in_list"
arguments:
col_name: "col4"
allowed:
- 1
- 2
""")
schema = "col1: int, col2: int, col3: int, col4 int"
input_df = spark.createDataFrame([[1, 3, 3, 1], [2, None, 4, 1]], schema)
# Option 1: apply quality rules on the dataframe and provide valid and invalid (quarantined) dataframes, checks are validated automatically
#valid_df, quarantined_df = apply_checks_by_metadata_and_split(input_df, checks)
# Option 2: apply quality rules on the dataframe and report issues as additional columns (`_warning` and `_error`), checks are validated automatically
dq_engine = DQEngine(WorkspaceClient())
valid_and_quarantined_df = dq_engine.apply_checks_by_metadata(input_df, checks)
display(valid_and_quarantined_df)
# COMMAND ----------
# MAGIC %md
# MAGIC ## Apply quality rules using DQX classes
# COMMAND ----------
from databricks.labs.dqx.col_functions import is_not_null, is_not_null_and_not_empty, value_is_in_list
from databricks.labs.dqx.engine import DQEngine, DQRule, DQRuleColSet
from databricks.sdk import WorkspaceClient
checks = DQRuleColSet( # define rule for multiple columns at once
columns=["col1", "col2"],
criticality="error",
check_func=is_not_null).get_rules() + [
DQRule( # define rule for a single column
name='col3_is_null_or_empty',
criticality='error',
check=is_not_null_and_not_empty('col3')),
DQRule( # name auto-generated if not provided
criticality='warn',
check=value_is_in_list('col4', ['1', '2']))
]
schema = "col1: int, col2: int, col3: int, col4 int"
input_df = spark.createDataFrame([[1, 3, 3, 1], [2, None, 4, 1]], schema)
# Option 1: apply quality rules on the dataframe and provide valid and invalid (quarantined) dataframes
#valid_df, quarantined_df = apply_checks_and_split(input_df, checks)
# Option 2: apply quality rules on the dataframe and report issues as additional columns (`_warning` and `_error`)
dq_engine = DQEngine(WorkspaceClient())
valid_and_quarantined_df = dq_engine.apply_checks(input_df, checks)
display(valid_and_quarantined_df)
# COMMAND ----------
# MAGIC %md
# MAGIC ## Apply checks in the medalion architecture
# COMMAND ----------
# Prepare bronze layer
bronze_path = "/tmp/dqx_demo/bronze"
df = spark.read.format("delta").load("/databricks-datasets/delta-sharing/samples/nyctaxi_2019")
df.write.format("delta").mode("overwrite").save(bronze_path)
# COMMAND ----------
# Define our Data Quality cheks
import yaml
checks = yaml.safe_load("""
- check:
function: "is_not_null"
arguments:
col_names:
- "vendor_id"
- "pickup_datetime"
- "dropoff_datetime"
- "passenger_count"
criticality: "error"
- check:
function: "is_not_null_and_not_empty"
arguments:
col_name: "vendor_id"
trim_strings: true
name: "vendor_id_is_null_or_empty"
criticality: "error"
- check:
function: "not_in_future"
arguments:
col_name: "pickup_datetime"
name: "pickup_datetime_not_in_future"
criticality: "warn"
- check:
function: "not_in_future"
arguments:
col_name: "dropoff_datetime"
name: "dropoff_datetime_not_in_future"
criticality: "warn"
- check:
function: "is_in_range"
arguments:
col_name: "passenger_count"
min_limit: 0
max_limit: 6
name: "passenger_incorrect_count"
criticality: "warn"
- check:
function: "is_not_null"
arguments:
col_name: "trip_distance"
name: "trip_distance_is_null"
criticality: "error"
""")
# COMMAND ----------
from databricks.labs.dqx.engine import DQEngine
from databricks.sdk import WorkspaceClient
dq_engine = DQEngine(WorkspaceClient())
# Apply checks when processing to silver layer
bronze = spark.read.format("delta").load(bronze_path)
silver, quarantine = dq_engine.apply_checks_by_metadata_and_split(bronze, checks)
# COMMAND ----------
display(silver)
# COMMAND ----------
display(quarantine)
# COMMAND ----------
# MAGIC %md
# MAGIC ## Create own custom checks
# COMMAND ----------
# MAGIC %md
# MAGIC ### Create custom check function
# COMMAND ----------
import pyspark.sql.functions as F
from pyspark.sql import Column
from databricks.labs.dqx.col_functions import make_condition
def ends_with_foo(col_name: str) -> Column:
column = F.col(col_name)
return make_condition(column.endswith("foo"), f"Column {col_name} ends with foo", f"{col_name}_ends_with_foo")
# COMMAND ----------
# MAGIC %md
# MAGIC ### Apply custom check function
# COMMAND ----------
import yaml
from databricks.labs.dqx.engine import DQEngine
from databricks.sdk import WorkspaceClient
from databricks.labs.dqx.col_functions import *
# use built-in, custom and sql expression checks
checks = yaml.safe_load(
"""
- criticality: "error"
check:
function: "is_not_null_and_not_empty"
arguments:
col_name: "col1"
- criticality: "error"
check:
function: "ends_with_foo"
arguments:
col_name: "col1"
- criticality: "error"
check:
function: "sql_expression"
arguments:
expression: "col1 LIKE 'str%'"
msg: "col1 starts with 'str'"
"""
)
schema = "col1: string"
input_df = spark.createDataFrame([["str1"], ["foo"], ["str3"]], schema)
dq_engine = DQEngine(WorkspaceClient())
valid_and_quarantined_df = dq_engine.apply_checks_by_metadata(input_df, checks, globals())
display(valid_and_quarantined_df)