-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathdqx_demo_library.py
More file actions
1481 lines (1195 loc) · 45.4 KB
/
Copy pathdqx_demo_library.py
File metadata and controls
1481 lines (1195 loc) · 45.4 KB
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Databricks notebook source
# MAGIC %md
# MAGIC # Demonstrate DQX usage as a Library
# COMMAND ----------
# MAGIC %md
# MAGIC ## Installation of DQX in Databricks cluster
# COMMAND ----------
dbutils.widgets.text("test_library_ref", "", "Test Library Ref")
if dbutils.widgets.get("test_library_ref") != "":
%pip install '{dbutils.widgets.get("test_library_ref")}'
else:
%pip install databricks-labs-dqx
%restart_python
# COMMAND ----------
# MAGIC %md
# MAGIC ## Generation of quality rule/check candidates using Profiler
# MAGIC Data profiling is typically performed as a one-time action for the input dataset to discover the initial set of quality rule candidates.
# MAGIC This is not intended to be a continuously repeated or scheduled process, thereby also minimizing concerns regarding compute intensity and associated costs.
# 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.labs.dqx.config import WorkspaceFileChecksStorageConfig, TableChecksStorageConfig
from databricks.labs.dqx.engine import DQEngine
from databricks.sdk import WorkspaceClient
import os
import yaml
default_file_directory = os.getcwd()
default_catalog = "main"
default_schema = "default"
dbutils.widgets.text("demo_file_directory", default_file_directory, "File Directory")
dbutils.widgets.text("demo_catalog", default_catalog, "Catalog Name")
dbutils.widgets.text("demo_schema", default_schema, "Schema Name")
demo_file_directory = dbutils.widgets.get("demo_file_directory")
demo_catalog_name = dbutils.widgets.get("demo_catalog")
demo_schema_name = dbutils.widgets.get("demo_schema")
schema = "col1: int, col2: int, col3: int, col4 int"
input_df = spark.createDataFrame([[1, 3, 3, 1], [2, None, 4, 1]], schema)
ws = WorkspaceClient()
# profile the input data
profiler = DQProfiler(ws)
# change the default sample fraction from 30% to 100% for demo purpose
summary_stats, profiles = profiler.profile(input_df, options={"sample_fraction": 1.0})
print(yaml.safe_dump(summary_stats))
print(profiles)
# generate DQX quality rules/checks candidates
# they should be manually reviewed before being applied to the data
generator = DQGenerator(ws)
checks = generator.generate_dq_rules(profiles) # with default level "error"
print(yaml.safe_dump(checks))
# generate Lakeflow Pipeline (formerly Delta Live Table (DLT)) expectations
dlt_generator = DQDltGenerator(ws)
dlt_expectations = dlt_generator.generate_dlt_rules(profiles, language="SQL")
print(dlt_expectations)
dlt_expectations = dlt_generator.generate_dlt_rules(profiles, language="Python")
print(dlt_expectations)
dlt_expectations = dlt_generator.generate_dlt_rules(profiles, language="Python_Dict")
print(dlt_expectations)
# save generated checks in a workspace file
user_name = spark.sql("select current_user() as user").collect()[0]["user"]
checks_file = f"{demo_file_directory}/dqx_demo_checks.yml"
dq_engine = DQEngine(ws)
dq_engine.save_checks(checks=checks, config=WorkspaceFileChecksStorageConfig(location=checks_file))
# save generated checks in a Delta table
dq_engine.save_checks(
checks=checks,
config=TableChecksStorageConfig(location=f"{demo_catalog_name}.{demo_schema_name}.dqx_checks_table", mode="overwrite")
)
# COMMAND ----------
# MAGIC %md
# MAGIC ## Loading and applying quality checks from a file
# COMMAND ----------
from databricks.labs.dqx.engine import DQEngine
from databricks.sdk import WorkspaceClient
from databricks.labs.dqx.config import WorkspaceFileChecksStorageConfig
input_df = spark.createDataFrame([[1, 3, 3, 2], [3, 3, None, 1]], schema)
# load checks from a file
dq_engine = DQEngine(WorkspaceClient())
checks = dq_engine.load_checks(config=WorkspaceFileChecksStorageConfig(location=checks_file))
# Option 1: apply quality rules and quarantine invalid records
valid_df, quarantine_df = dq_engine.apply_checks_by_metadata_and_split(input_df, checks)
display(valid_df)
display(quarantine_df)
# Option 2: apply quality rules and annotate invalid records as additional columns (`_warning` and `_error`)
valid_and_quarantine_df = dq_engine.apply_checks_by_metadata(input_df, checks)
display(valid_and_quarantine_df)
# COMMAND ----------
# MAGIC %md
# MAGIC ## Loading and applying quality checks from a Delta table
# COMMAND ----------
from databricks.labs.dqx.engine import DQEngine
from databricks.sdk import WorkspaceClient
from databricks.labs.dqx.config import TableChecksStorageConfig
input_df = spark.createDataFrame([[1, 3, 3, 2], [3, 3, None, 1]], schema)
# load checks from a Delta table
dq_engine = DQEngine(WorkspaceClient())
checks = dq_engine.load_checks(config=TableChecksStorageConfig(location=f"{demo_catalog_name}.{demo_schema_name}.dqx_checks_table"))
# Option 1: apply quality rules and quarantine invalid records
valid_df, quarantine_df = dq_engine.apply_checks_by_metadata_and_split(input_df, checks)
display(valid_df)
display(quarantine_df)
# Option 2: apply quality rules and annotate invalid records as additional columns (`_warning` and `_error`)
valid_and_quarantine_df = dq_engine.apply_checks_by_metadata(input_df, checks)
display(valid_and_quarantine_df)
# COMMAND ----------
# MAGIC %md
# MAGIC ## Validating syntax of quality checks defined declaratively in yaml
# 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
for_each_column:
- col1
- col2
""")
dq_engine = DQEngine(WorkspaceClient())
status = dq_engine.validate_checks(checks)
print(status.has_errors)
print(status.errors)
# COMMAND ----------
# MAGIC %md
# MAGIC ## Applying quality checks defined in yaml
# COMMAND ----------
import yaml
from databricks.labs.dqx.engine import DQEngine
from databricks.sdk import WorkspaceClient
checks = yaml.safe_load("""
# check for a single column
- criticality: warn
check:
function: is_not_null_and_not_empty
arguments:
column: col3
# check for multiple column
- criticality: error
check:
function: is_not_null
for_each_column:
- col1
- col2
# check with a filter
- criticality: warn
filter: col1 < 3
check:
function: is_not_null_and_not_empty
arguments:
column: col4
# check with user metadata
- criticality: warn
check:
function: is_not_null_and_not_empty
arguments:
column: col5
user_metadata:
check_category: completeness
responsible_data_steward: someone@email.com
# check with auto-generated name
- criticality: warn
check:
function: is_in_list
arguments:
column: col1
allowed:
- 1
- 2
# check for a struct field
- check:
function: is_not_null
arguments:
column: col7.field1
# "error" criticality used if not provided
# check for a map element
- criticality: error
check:
function: is_not_null
arguments:
column: try_element_at(col5, 'key1')
# check for an array element
- criticality: error
check:
function: is_not_null
arguments:
column: try_element_at(col6, 1)
# check uniqueness of composite key, multi-column rule
- criticality: error
check:
function: is_unique
arguments:
columns:
- col1
- col2
- criticality: error
check:
function: is_aggr_not_greater_than
arguments:
column: col1
aggr_type: count
limit: 10
- criticality: error
check:
function: is_aggr_not_less_than
arguments:
column: col1
aggr_type: count
limit: 1.2
""")
# validate the checks
status = DQEngine.validate_checks(checks)
assert not status.has_errors
schema = "col1: int, col2: int, col3: int, col4 int, col5: map<string, string>, col6: array<string>, col7: struct<field1: int>"
input_df = spark.createDataFrame([
[1, 3, 3, None, {"key1": ""}, [""], {"field1": 1}],
[3, None, 4, 1, {"key1": None}, [None], {"field1": None}],
[None, None, None, None, None, None, None],
], schema)
dq_engine = DQEngine(WorkspaceClient())
# Option 1: apply quality rules and quarantine invalid records
valid_df, quarantine_df = dq_engine.apply_checks_by_metadata_and_split(input_df, checks)
display(valid_df)
display(quarantine_df)
# Option 2: apply quality rules and annotate invalid records as additional columns (`_warning` and `_error`)
valid_and_quarantine_df = dq_engine.apply_checks_by_metadata(input_df, checks)
display(valid_and_quarantine_df)
# COMMAND ----------
# MAGIC %md
# MAGIC ## Applying quality checks programmatically using DQX classes
# COMMAND ----------
from databricks.labs.dqx import check_funcs
from databricks.labs.dqx.engine import DQEngine
from databricks.labs.dqx.rule import DQRowRule, DQDatasetRule, DQForEachColRule
from databricks.sdk import WorkspaceClient
import pyspark.sql.functions as F
checks = [
DQRowRule( # check for a single column
name="col3_is_null_or_empty",
criticality="warn",
check_func=check_funcs.is_not_null_and_not_empty,
column="col3"
),
*DQForEachColRule( # check for multiple columns
columns=["col1", "col2"],
criticality="error",
check_func=check_funcs.is_not_null).get_rules(),
DQRowRule( # check with a filter
name="col_4_is_null_or_empty",
criticality="warn",
filter="col1 < 3",
check_func=check_funcs.is_not_null_and_not_empty,
column="col4"
),
DQRowRule(
criticality="warn",
check_func=check_funcs.is_not_null_and_not_empty,
column='col3',
user_metadata={
"check_type": "completeness",
"responsible_data_steward": "someone@email.com"
}
),
DQRowRule( # provide check func arguments using positional arguments
criticality="warn",
check_func=check_funcs.is_in_list,
column="col1",
check_func_args=[[1, 2]]
),
DQRowRule( # provide check func arguments using keyword arguments
criticality="warn",
check_func=check_funcs.is_in_list,
column="col2",
check_func_kwargs={"allowed": [1, 2]}
),
DQRowRule( # check for a struct field
# "error" criticality used if not provided
check_func=check_funcs.is_not_null,
column="col7.field1"
),
DQRowRule( # check for a map element
criticality="error",
check_func=check_funcs.is_not_null,
column=F.try_element_at("col5", F.lit("key1"))
),
DQRowRule( # check for an array element
criticality="error",
check_func=check_funcs.is_not_null,
column=F.try_element_at("col6", F.lit(1))
),
DQDatasetRule( # check uniqueness of composite key, multi-column rule
criticality="error",
check_func=check_funcs.is_unique,
columns=["col1", "col2"]
),
DQDatasetRule(
criticality="error",
check_func=check_funcs.is_aggr_not_greater_than,
column="col1",
check_func_kwargs={"aggr_type": "count", "limit": 10},
),
DQDatasetRule(
criticality="error",
check_func=check_funcs.is_aggr_not_less_than,
column="col1",
check_func_kwargs={"aggr_type": "avg", "limit": 1.2},
),
]
schema = "col1: int, col2: int, col3: int, col4 int, col5: map<string, string>, col6: array<string>, col7: struct<field1: int>"
input_df = spark.createDataFrame([
[1, 3, 3, None, {"key1": ""}, [""], {"field1": 1}],
[3, None, 4, 1, {"key1": None}, [None], {"field1": None}],
[None, None, None, None, None, None, None],
], schema)
dq_engine = DQEngine(WorkspaceClient())
# Option 1: apply quality rules and quarantine invalid records
valid_df, quarantine_df = dq_engine.apply_checks_and_split(input_df, checks)
display(valid_df)
display(quarantine_df)
# Option 2: apply quality rules and annotate invalid records as additional columns (`_warning` and `_error`)
valid_and_quarantine_df = dq_engine.apply_checks(input_df, checks)
display(valid_and_quarantine_df)
# COMMAND ----------
# MAGIC %md
# MAGIC ## Applying quality checks in the Lakehouse medallion architecture
# COMMAND ----------
import yaml
from databricks.labs.dqx.config import InputConfig, OutputConfig
from databricks.labs.dqx.engine import DQEngine
from databricks.sdk import WorkspaceClient
checks = yaml.safe_load("""
- check:
function: is_not_null
for_each_column:
- vendor_id
- pickup_datetime
- dropoff_datetime
- passenger_count
- trip_distance
- pickup_longitude
- pickup_latitude
- dropoff_longitude
- dropoff_latitude
criticality: warn
filter: total_amount > 0
- check:
function: is_not_less_than
arguments:
column: trip_distance
limit: 1
criticality: error
filter: tip_amount > 0
- check:
function: sql_expression
arguments:
expression: pickup_datetime <= dropoff_datetime
msg: pickup time must not be greater than dropff time
name: pickup_datetime_greater_than_dropoff_datetime
criticality: error
- check:
function: is_not_in_future
arguments:
column: pickup_datetime
name: pickup_datetime_not_in_future
criticality: warn
""")
# validate the checks
status = DQEngine.validate_checks(checks)
assert not status.has_errors
dq_engine = DQEngine(WorkspaceClient())
# read the data, limit to 1000 rows for demo purpose
bronze_df = spark.read.format("delta").load("/databricks-datasets/delta-sharing/samples/nyctaxi_2019").limit(1000)
# apply your business logic here
bronze_transformed_df = bronze_df.filter("vendor_id in (1, 2)")
# apply quality checks
silver_df, quarantine_df = dq_engine.apply_checks_by_metadata_and_split(bronze_transformed_df, checks)
# save results
dq_engine.save_results_in_table(
output_df=silver_df,
quarantine_df=quarantine_df,
output_config=OutputConfig(f"{demo_catalog_name}.{demo_schema_name}.dqx_output", mode="overwrite"),
quarantine_config=OutputConfig(f"{demo_catalog_name}.{demo_schema_name}.dqx_quarantine", mode="overwrite")
)
# COMMAND ----------
display(spark.table(f"{demo_catalog_name}.{demo_schema_name}.dqx_output"))
# COMMAND ----------
display(spark.table(f"{demo_catalog_name}.{demo_schema_name}.dqx_quarantine"))
# COMMAND ----------
# MAGIC %md
# MAGIC ## End-to-end quality checking
# COMMAND ----------
# end-to-end quality checking flow
dq_engine.apply_checks_by_metadata_and_save_in_table(
input_config=InputConfig("/databricks-datasets/delta-sharing/samples/nyctaxi_2019"),
checks=checks,
output_config=OutputConfig(f"{demo_catalog_name}.{demo_schema_name}.dqx_e2e_output", mode="overwrite"),
quarantine_config=OutputConfig(f"{demo_catalog_name}.{demo_schema_name}.dqx_e2e_quarantine", mode="overwrite")
)
# display the results saved to output and quarantine tables
display(spark.table(f"{demo_catalog_name}.{demo_schema_name}.dqx_e2e_output"))
display(spark.table(f"{demo_catalog_name}.{demo_schema_name}.dqx_e2e_quarantine"))
# COMMAND ----------
# MAGIC %md
# MAGIC ## Using Foreign Key check
# COMMAND ----------
# Using DQX classes to define foreign key check
from databricks.labs.dqx.engine import DQEngine
from databricks.sdk import WorkspaceClient
checks = [
DQDatasetRule(
criticality="error",
check_func=check_funcs.foreign_key,
columns=["col1"],
check_func_kwargs={
"ref_columns": ["ref_col1"],
# either provide reference DataFrame name
"ref_df_name": "ref_df_key",
# or provide name of the reference table
# "ref_table": "catalog1.schema1.ref_table",
},
),
DQDatasetRule(
name="foreign_key_check_on_composite_key",
criticality="warn",
check_func=check_funcs.foreign_key,
columns=["col1", "col2"], # composite key
check_func_kwargs={
"ref_columns": ["ref_col1", "ref_col2"],
"ref_df_name": "ref_df_key",
},
),
]
input_df = spark.createDataFrame([[1, 1], [2, 2], [None, None]], "col1: int, col2: int")
reference_df = spark.createDataFrame([[1, 1]], "ref_col1: int, ref_col2: int")
dq_engine = DQEngine(WorkspaceClient())
# When applying foreign key checks with a specified `ref_df_name` argument,
# you must pass a dictionary of reference DataFrame to the `apply_checks` or `apply_checks_and_split` methods
refs_dfs = {"ref_df_key": reference_df}
valid_and_quarantine_df = dq_engine.apply_checks(input_df, checks, ref_dfs=refs_dfs)
display(valid_and_quarantine_df)
# COMMAND ----------
# Using yaml to define the foreign key check
import yaml
from databricks.labs.dqx.engine import DQEngine
from databricks.sdk import WorkspaceClient
checks = yaml.safe_load(
"""
- criticality: error
check:
function: foreign_key
arguments:
columns:
- col1
ref_columns:
- ref_col1
# either provide reference DataFrame name
ref_df_name: ref_df_key
# or provide name of the reference table
#ref_table: catalog1.schema1.ref_table
- criticality: warn
name: foreign_key_check_on_composite_key
check:
function: foreign_key
arguments:
columns:
- col1
- col2
ref_columns:
- ref_col1
- ref_col2
ref_df_name: ref_df_key
""")
input_df = spark.createDataFrame([[1, 1], [2, 2], [None, None]], "col1: int, col2: int")
reference_df = spark.createDataFrame([[1, 1]], "ref_col1: int, ref_col2: int")
dq_engine = DQEngine(WorkspaceClient())
# When applying foreign key checks with a specified `ref_df_name` argument,
# you must pass a dictionary of reference DataFrame to the `apply_checks_by_metadata` or `apply_checks_by_metadata_and_split` methods
refs_dfs = {"ref_df_key": reference_df}
valid_and_quarantine_df = dq_engine.apply_checks_by_metadata(input_df, checks, ref_dfs=refs_dfs)
display(valid_and_quarantine_df)
# COMMAND ----------
# MAGIC %md
# MAGIC ## Creating custom checks
# COMMAND ----------
# MAGIC %md
# MAGIC ### Creating custom row-level check function
# COMMAND ----------
import pyspark.sql.functions as F
from pyspark.sql import Column
from databricks.labs.dqx.check_funcs import make_condition
from databricks.labs.dqx.rule import register_rule
@register_rule("row")
def not_ends_with(column: str, suffix: str) -> Column:
col_expr = F.col(column)
return make_condition(col_expr.endswith(suffix), f"Column {column} ends with {suffix}",
f"{column}_ends_with_{suffix}")
# COMMAND ----------
# MAGIC %md
# MAGIC ### Applying custom row-level check function using DQX classes
# COMMAND ----------
from databricks.labs.dqx.engine import DQEngine
from databricks.sdk import WorkspaceClient
from databricks.labs.dqx.rule import DQRowRule
from databricks.labs.dqx.check_funcs import is_not_null_and_not_empty, sql_expression
checks = [
# custom check
DQRowRule(criticality="warn", check_func=not_ends_with, column="col1", check_func_kwargs={"suffix": "foo"}),
# sql expression check
DQRowRule(criticality="warn", check_func=sql_expression, check_func_kwargs={
"expression": "col1 like 'str%'", "msg": "col1 not starting with 'str'"
}),
# built-in check
DQRowRule(criticality="error", check_func=is_not_null_and_not_empty, column="col1"),
]
schema = "col1: string, col2: string"
input_df = spark.createDataFrame([[None, "foo"], ["foo", None], [None, None]], schema)
dq_engine = DQEngine(WorkspaceClient())
valid_and_quarantine_df = dq_engine.apply_checks(input_df, checks)
display(valid_and_quarantine_df)
# COMMAND ----------
# MAGIC %md
# MAGIC ### Applying custom row-level check function using YAML definition
# COMMAND ----------
import yaml
from databricks.labs.dqx.engine import DQEngine
from databricks.sdk import WorkspaceClient
checks = yaml.safe_load(
"""
# custom python check
- criticality: warn
check:
function: not_ends_with
arguments:
column: col1
suffix: foo
# sql expression check
- criticality: warn
check:
function: sql_expression
arguments:
expression: col1 like 'str%'
msg: col1 not starting with 'str'
# built-in check
- criticality: error
check:
function: is_not_null_and_not_empty
arguments:
column: col1
"""
)
schema = "col1: string, col2: string"
input_df = spark.createDataFrame([[None, "foo"], ["foo", None], [None, None]], schema)
dq_engine = DQEngine(WorkspaceClient())
custom_check_functions = {"not_ends_with": not_ends_with}
# alternatively, you can also use globals to include all available functions
# custom_check_functions = globals()
status = dq_engine.validate_checks(checks, custom_check_functions)
assert not status.has_errors
valid_and_quarantine_df = dq_engine.apply_checks_by_metadata(input_df, checks, custom_check_functions)
display(valid_and_quarantine_df)
# COMMAND ----------
# MAGIC %md
# MAGIC ### Extended Aggregate Functions for Data Quality Checks
# MAGIC
# MAGIC DQX now supports 20 curated aggregate functions for advanced data quality monitoring:
# MAGIC - **Statistical functions**: `stddev`, `variance`, `median`, `mode`, `skewness`, `kurtosis` for anomaly detection
# MAGIC - **Percentile functions**: `percentile`, `approx_percentile` for SLA monitoring
# MAGIC - **Cardinality functions**: `count_distinct`, `approx_count_distinct` (uses HyperLogLog++)
# MAGIC - **Any Databricks built-in aggregate**: Supported with runtime validation
# COMMAND ----------
# MAGIC %md
# MAGIC #### Example 1: Statistical Functions - Anomaly Detection with Standard Deviation
# MAGIC
# MAGIC Detect unusual variance in sensor readings per machine. High standard deviation indicates unstable sensors that may need calibration.
# COMMAND ----------
from databricks.labs.dqx.engine import DQEngine
from databricks.labs.dqx.rule import DQDatasetRule
from databricks.labs.dqx import check_funcs
from databricks.sdk import WorkspaceClient
# Manufacturing sensor data with readings from multiple machines
manufacturing_df = spark.createDataFrame([
["M1", "2024-01-01", 20.1],
["M1", "2024-01-02", 20.3],
["M1", "2024-01-03", 20.2], # Machine 1: stable readings (low stddev)
["M2", "2024-01-01", 18.5],
["M2", "2024-01-02", 25.7],
["M2", "2024-01-03", 15.2], # Machine 2: unstable readings (high stddev) - should FAIL
["M3", "2024-01-01", 19.8],
["M3", "2024-01-02", 20.1],
["M3", "2024-01-03", 19.9], # Machine 3: stable readings
], "machine_id: string, date: string, temperature: double")
# Quality check: Standard deviation should not exceed 3.0 per machine
checks = [
DQDatasetRule(
criticality="error",
check_func=check_funcs.is_aggr_not_greater_than,
column="temperature",
check_func_kwargs={
"aggr_type": "stddev",
"group_by": ["machine_id"],
"limit": 3.0
},
),
]
dq_engine = DQEngine(WorkspaceClient())
result_df = dq_engine.apply_checks(manufacturing_df, checks)
display(result_df)
# COMMAND ----------
# MAGIC %md
# MAGIC #### Example 2: Approximate Aggregate Functions - Efficient Cardinality Estimation
# MAGIC
# MAGIC **`approx_count_distinct`** provides fast, memory-efficient cardinality estimation for large datasets.
# MAGIC
# MAGIC **From [Databricks Documentation](https://docs.databricks.com/aws/en/sql/language-manual/functions/approx_count_distinct.html):**
# MAGIC - Uses **HyperLogLog++** (HLL++) algorithm, a state-of-the-art cardinality estimator
# MAGIC - **Accurate within 5%** by default (configurable via `relativeSD` parameter)
# MAGIC - **Memory efficient**: Uses fixed memory regardless of cardinality
# MAGIC - **Ideal for**: High-cardinality columns, large datasets, real-time analytics
# MAGIC
# MAGIC **Use Case**: Monitor daily active users without expensive exact counting.
# COMMAND ----------
# User activity data with high cardinality
user_activity_df = spark.createDataFrame([
["2024-01-01", f"user_{i}"] for i in range(1, 95001) # 95,000 distinct users on day 1
] + [
["2024-01-02", f"user_{i}"] for i in range(1, 50001) # 50,000 distinct users on day 2
], "activity_date: string, user_id: string")
# Quality check: Ensure daily active users don't drop below 60,000
# Using approx_count_distinct is much faster than count_distinct for large datasets
checks = [
DQDatasetRule(
criticality="warn",
check_func=check_funcs.is_aggr_not_less_than,
column="user_id",
check_func_kwargs={
"aggr_type": "approx_count_distinct", # Fast approximate counting
"group_by": ["activity_date"],
"limit": 60000
},
),
]
result_df = dq_engine.apply_checks(user_activity_df, checks)
display(result_df)
# COMMAND ----------
# MAGIC %md
# MAGIC #### Example 3: Non-Curated Aggregate Functions with Runtime Validation
# MAGIC
# MAGIC DQX supports any Databricks built-in aggregate function beyond the curated list:
# MAGIC - **Warning**: Non-curated functions trigger a warning
# MAGIC - **Runtime validation**: Ensures the function returns numeric values compatible with comparisons
# MAGIC - **Graceful errors**: Invalid aggregates (e.g., `collect_list` returning arrays) fail with clear messages
# MAGIC
# MAGIC **Note**: User-Defined Aggregate Functions (UDAFs) are not currently supported.
# COMMAND ----------
import warnings
# Sensor data with multiple readings per sensor
sensor_sample_df = spark.createDataFrame([
["S1", 45.2],
["S1", 45.8],
["S2", 78.1],
["S2", 78.5],
], "sensor_id: string, reading: double")
# Using a valid but non-curated aggregate function: any_value
# This will work but produce a warning
checks = [
DQDatasetRule(
criticality="warn",
check_func=check_funcs.is_aggr_not_greater_than,
column="reading",
check_func_kwargs={
"aggr_type": "any_value", # Not in curated list - triggers warning
"group_by": ["sensor_id"],
"limit": 100.0
},
),
]
# Capture warnings during execution
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
result_df = dq_engine.apply_checks(sensor_sample_df, checks)
# Display warning message if present
if w:
print(f"⚠️ Warning: {w[0].message}")
display(result_df)
# COMMAND ----------
# MAGIC %md
# MAGIC #### Example 4: Percentile Functions for SLA Monitoring
# MAGIC
# MAGIC Monitor P95 latency to ensure 95% of API requests meet SLA requirements.
# MAGIC
# MAGIC **Using `aggr_params`:** Pass aggregate function parameters as a dictionary.
# MAGIC - Single parameter: `aggr_params={"percentile": 0.95}`
# MAGIC - Multiple parameters: `aggr_params={"percentile": 0.99, "accuracy": 10000}`
# COMMAND ----------
# API latency data in milliseconds
api_latency_df = spark.createDataFrame([
["2024-01-01", i * 10.0] for i in range(1, 101) # 10ms to 1000ms latencies
], "date: string, latency_ms: double")
# Quality check: P95 latency must be under 950ms
checks = [
DQDatasetRule(
criticality="error",
check_func=check_funcs.is_aggr_not_greater_than,
column="latency_ms",
check_func_kwargs={
"aggr_type": "percentile",
"aggr_params": {"percentile": 0.95}, # aggr_params as dict
"group_by": ["date"],
"limit": 950.0
},
),
]
result_df = dq_engine.apply_checks(api_latency_df, checks)
display(result_df)
# COMMAND ----------
# MAGIC %md
# MAGIC #### Example 5: Uniqueness Validation with Count Distinct
# MAGIC
# MAGIC Ensure referential integrity: each country should have exactly one country code.
# MAGIC
# MAGIC Use `count_distinct` for exact cardinality validation across groups.
# COMMAND ----------
# Country data with potential duplicates
country_df = spark.createDataFrame([
["US", "USA"],
["US", "USA"], # OK: same code
["FR", "FRA"],
["FR", "FRN"], # ERROR: different codes for same country
["DE", "DEU"],
], "country: string, country_code: string")
# Quality check: Each country must have exactly one distinct country code
checks = [
DQDatasetRule(
criticality="error",
check_func=check_funcs.is_aggr_not_greater_than,
column="country_code",
check_func_kwargs={
"aggr_type": "count_distinct", # Exact distinct count per group
"group_by": ["country"],
"limit": 1
},
),
]
result_df = dq_engine.apply_checks(country_df, checks)
display(result_df)
# COMMAND ----------
# MAGIC %md
# MAGIC ### Creating custom dataset-level checks
# MAGIC Requirement: Fail all readings from a sensor if any reading for that sensor exceeds a specified threshold from the sensor specification table.
# COMMAND ----------
# MAGIC %md
# MAGIC #### Define input data
# COMMAND ----------
from databricks.labs.dqx.engine import DQEngine
from databricks.sdk import WorkspaceClient
# sensor data
sensor_df = spark.createDataFrame([
[1, 1, 4],
[1, 2, 1],
[2, 2, 110]
], "measurement_id: int, sensor_id: int, reading_value: int")
# reference specs
sensor_specs_df = spark.createDataFrame([
[1, 5],
[2, 100],
], "sensor_id: int, min_threshold: int")
dq_engine = DQEngine(WorkspaceClient())
# COMMAND ----------
# MAGIC %md
# MAGIC #### Using `sql_query` check - Row-level validation
# MAGIC
# MAGIC The `sql_query` check supports two modes:
# MAGIC - **Row-level validation** (with `merge_columns`): Query results are joined back to mark specific rows
# MAGIC - **Dataset-level validation** (without `merge_columns`): Check result applies to all rows
# COMMAND ----------
# Row-level validation example: Check each sensor against its threshold
from databricks.labs.dqx.rule import DQDatasetRule
from databricks.labs.dqx.check_funcs import sql_query
query = """
WITH joined AS (
SELECT
sensor.*,
COALESCE(specs.min_threshold, 100) AS effective_threshold
FROM {{ sensor }} sensor
LEFT JOIN {{ sensor_specs }} specs
ON sensor.sensor_id = specs.sensor_id
)
SELECT
sensor_id,
MAX(CASE WHEN reading_value > effective_threshold THEN 1 ELSE 0 END) = 1 AS condition
FROM joined
GROUP BY sensor_id
"""
checks = [
DQDatasetRule(
criticality="error",
check_func=sql_query,
check_func_kwargs={
"query": query,
"merge_columns": ["sensor_id"], # Results joined back by sensor_id
"condition_column": "condition", # the check fails if this column evaluates to True
"msg": "one of the sensor reading is greater than limit",
"name": "sensor_reading_check",
"input_placeholder": "sensor",
},
),
]
# Pass reference DataFrame with sensor specifications
ref_dfs = {"sensor_specs": sensor_specs_df}
valid_and_quarantine_df = dq_engine.apply_checks(sensor_df, checks, ref_dfs=ref_dfs)
display(valid_and_quarantine_df)
# COMMAND ----------
# MAGIC %md
# MAGIC #### Using `sql_query` check - Dataset-level validation
# MAGIC
# MAGIC When `merge_columns` is not provided, the check applies to all rows (all pass or all fail together).