forked from awslabs/deequ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Check.scala
1254 lines (1118 loc) · 48 KB
/
Check.scala
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
/**
* Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License
* is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazon.deequ.checks
import com.amazon.deequ.analyzers.runners.AnalyzerContext
import com.amazon.deequ.analyzers.Analyzer
import com.amazon.deequ.analyzers.AnalyzerOptions
import com.amazon.deequ.analyzers.DataSynchronizationAnalyzer
import com.amazon.deequ.analyzers.DataSynchronizationState
import com.amazon.deequ.analyzers.Histogram
import com.amazon.deequ.analyzers.KLLParameters
import com.amazon.deequ.analyzers.Patterns
import com.amazon.deequ.analyzers.State
import com.amazon.deequ.anomalydetection.HistoryUtils
import com.amazon.deequ.anomalydetection.AnomalyDetectionStrategy
import com.amazon.deequ.anomalydetection.AnomalyDetector
import com.amazon.deequ.anomalydetection.DataPoint
import com.amazon.deequ.checks.ColumnCondition.isAnyNotNull
import com.amazon.deequ.checks.ColumnCondition.isEachNotNull
import com.amazon.deequ.constraints.Constraint._
import com.amazon.deequ.constraints._
import com.amazon.deequ.metrics.BucketDistribution
import com.amazon.deequ.metrics.Distribution
import com.amazon.deequ.metrics.Metric
import com.amazon.deequ.repository.MetricsRepository
import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.expressions.UserDefinedFunction
import scala.util.matching.Regex
object CheckLevel extends Enumeration {
val Error, Warning = Value
}
object CheckStatus extends Enumeration {
val Success, Warning, Error = Value
}
case class CheckResult(
check: Check,
status: CheckStatus.Value,
constraintResults: Seq[ConstraintResult])
/**
* A class representing a list of constraints that can be applied to a given
* [[org.apache.spark.sql.DataFrame]]. In order to run the checks, use the `run` method. You can
* also use VerificationSuite.run to run your checks along with other Checks and Analysis objects.
* When run with VerificationSuite, Analyzers required by multiple checks/analysis blocks is
* optimized to run once.
*
* @param level Assertion level of the check group. If any of the constraints fail this
* level is used for the status of the check.
* @param description The name describes the check block. Generally will be used to show in
* the logs.
* @param constraints The constraints to apply when this check is run. New ones can be added
* and will return a new object
*/
case class Check(
level: CheckLevel.Value,
description: String,
private[deequ] val constraints: Seq[Constraint] = Seq.empty) {
/**
* Returns the name of the columns where each Constraint puts row-level results, if any
*
*/
def getRowLevelConstraintColumnNames(): Seq[String] = {
constraints.flatMap(c => {
c match {
case c: RowLevelConstraint => Some(c.getColumnName)
case _ => None
}
})
}
/**
* Returns a new Check object with the given constraint added to the constraints list.
*
* @param constraint New constraint to be added
* @return
*/
def addConstraint(constraint: Constraint): Check = {
Check(level, description, constraints :+ constraint)
}
/** Adds a constraint that can subsequently be replaced with a filtered version */
private[this] def addFilterableConstraint(
creationFunc: Option[String] => Constraint)
: CheckWithLastConstraintFilterable = {
val constraintWithoutFiltering = creationFunc(None)
CheckWithLastConstraintFilterable(level, description,
constraints :+ constraintWithoutFiltering, creationFunc)
}
/**
* Creates a constraint that calculates the data frame size and runs the assertion on it.
*
* @param assertion Function that receives a long input parameter and returns a boolean
* Assertion functions might refer to the data frame size by "_"
* .hasSize(_>5), meaning the number of rows should be greater than 5
* Or more elaborate function might be provided
* .hasSize{ aNameForSize => aNameForSize > 0 && aNameForSize < 10 }
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasSize(assertion: Long => Boolean, hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter => Constraint.sizeConstraint(assertion, filter, hint) }
}
/**
* Creates a constraint that asserts on a column completion.
*
* @param column Column to run the assertion on
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def isComplete(column: String, hint: Option[String] = None): CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter => completenessConstraint(column, Check.IsOne, filter, hint) }
}
/**
* Creates a constraint that asserts on a column completion.
* Uses the given history selection strategy to retrieve historical completeness values on this
* column from the history provider.
*
* @param column Column to run the assertion on
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasCompleteness(
column: String,
assertion: Double => Boolean,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter => completenessConstraint(column, assertion, filter, hint) }
}
/**
* Creates a constraint that asserts on completion in combined set of columns.
*
* @param columns Columns to run the assertion on
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def areComplete(
columns: Seq[String],
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
satisfies(isEachNotNull(columns), "Combined Completeness", Check.IsOne, hint, columns = columns.toList)
}
/**
* Creates a constraint that assert on completion in combined set of columns.
*
* @param columns Columns to run the assertion on
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def haveCompleteness(
columns: Seq[String],
assertion: Double => Boolean,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
satisfies(isEachNotNull(columns), "Combined Completeness", assertion, hint, columns = columns.toList)
}
/**
* Creates a constraint that asserts on completion in combined set of columns.
*
* @param columns Columns to run the assertion on
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def areAnyComplete(
columns: Seq[String],
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
satisfies(isAnyNotNull(columns), "Any Completeness", Check.IsOne, hint, columns = columns.toList)
}
/**
* Creates a constraint that assert on completion in combined set of columns.
*
* @param columns Columns to run the assertion on
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def haveAnyCompleteness(
columns: Seq[String],
assertion: Double => Boolean,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
satisfies(isAnyNotNull(columns), "Any Completeness", assertion, hint, columns = columns.toList)
}
/**
* Creates a constraint that asserts on a column uniqueness.
*
* @param column Column to run the assertion on
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def isUnique(column: String, hint: Option[String] = None): CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter =>
uniquenessConstraint(Seq(column), Check.IsOne, filter, hint) }
}
/**
* Creates a constraint that asserts on a column(s) primary key characteristics.
* Currently only checks uniqueness, but reserved for primary key checks if there is another
* assertion to run on primary key columns.
*
* @param column Columns to run the assertion on
* @return
*/
def isPrimaryKey(column: String, columns: String*): CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter =>
uniquenessConstraint(column :: columns.toList, Check.IsOne, filter) }
}
/**
* Creates a constraint that asserts on a column(s) primary key characteristics.
* Currently only checks uniqueness, but reserved for primary key checks if there is another
* assertion to run on primary key columns.
*
* @param column Columns to run the assertion on
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def isPrimaryKey(column: String, hint: Option[String], columns: String*)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter =>
uniquenessConstraint(column :: columns.toList, Check.IsOne, filter, hint) }
}
/**
* Creates a constraint that asserts on uniqueness in a single or combined set of key columns.
*
* @param columns Key columns
* @param assertion Function that receives a double input parameter and returns a boolean.
* Refers to the fraction of unique values
* @return
*/
def hasUniqueness(columns: Seq[String], assertion: Double => Boolean)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter => uniquenessConstraint(columns, assertion, filter) }
}
/**
* Creates a constraint that asserts on uniqueness in a single or combined set of key columns.
*
* @param columns Key columns
* @param assertion Function that receives a double input parameter and returns a boolean.
* Refers to the fraction of unique values
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasUniqueness(
columns: Seq[String],
assertion: Double => Boolean,
hint: Option[String])
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter => uniquenessConstraint(columns, assertion, filter, hint) }
}
/**
* Creates a constraint that asserts on the uniqueness of a key column.
*
* @param column Key column
* @param assertion Function that receives a double input parameter and returns a boolean.
* Refers to the fraction of unique values.
* @return
*/
def hasUniqueness(column: String, assertion: Double => Boolean)
: CheckWithLastConstraintFilterable = {
hasUniqueness(Seq(column), assertion)
}
/**
* Creates a constraint that asserts on the uniqueness of a key column.
*
* @param column Key column
* @param assertion Function that receives a double input parameter and returns a boolean.
* Refers to the fraction of unique values.
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasUniqueness(column: String, assertion: Double => Boolean, hint: Option[String])
: CheckWithLastConstraintFilterable = {
hasUniqueness(Seq(column), assertion, hint)
}
/**
* Creates a constraint on the distinctness in a single or combined set of key columns.
*
* @param columns columns
* @param assertion Function that receives a double input parameter and returns a boolean.
* Refers to the fraction of distinct values.
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasDistinctness(
columns: Seq[String], assertion: Double => Boolean,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter => distinctnessConstraint(columns, assertion, filter, hint) }
}
/**
* Creates a constraint on the unique value ratio in a single or combined set of key columns.
*
* @param columns columns
* @param assertion Function that receives a double input parameter and returns a boolean.
* Refers to the fraction of distinct values.
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasUniqueValueRatio(
columns: Seq[String],
assertion: Double => Boolean,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter =>
uniqueValueRatioConstraint(columns, assertion, filter, hint) }
}
/**
* Performs a data synchronization check between the base DataFrame supplied to
* [[com.amazon.deequ.VerificationSuite.onData]] and other DataFrame supplied to this check using Deequ's
* [[com.amazon.deequ.comparison.DataSynchronization.columnMatch]] framework.
* This method compares specified columns of both DataFrames and assesses synchronization based on a custom assertion.
*
* Utilizes [[com.amazon.deequ.analyzers.DataSynchronizationAnalyzer]] for comparing the data
* and Constraint [[com.amazon.deequ.constraints.DataSynchronizationConstraint]].
*
* Usage:
* To use this method, create a VerificationSuite and invoke this method as part of adding checks:
* {{{
* val baseDataFrame: DataFrame = ...
* val otherDataFrame: DataFrame = ...
* val columnMappings: Map[String, String] = Map("baseCol1" -> "otherCol1", "baseCol2" -> "otherCol2")
* val assertionFunction: Double => Boolean = _ > 0.7
*
* val check = new Check(CheckLevel.Error, "Data Synchronization Check")
* .isDataSynchronized(otherDataFrame, columnMappings, assertionFunction)
*
* val verificationResult = VerificationSuite()
* .onData(baseDataFrame)
* .addCheck(check)
* .run()
* }}}
*
* This will add a data synchronization check to the VerificationSuite, comparing the specified columns of
* baseDataFrame and otherDataFrame based on the provided assertion function.
*
*
* @param otherDf The DataFrame to be compared with the current one. Analyzed in conjunction with the
* current DataFrame to assess data synchronization.
* @param columnMappings A map defining the column correlations between the current DataFrame and otherDf.
* Keys represent column names in the current DataFrame,
* and values are corresponding column names in otherDf.
* @param assertion A function that takes a Double (result of the comparison) and returns a Boolean.
* Defines the condition under which the data in both DataFrames is considered synchronized.
* For example (_ > 0.7) denoting metric value > 0.7 or 70% of records.
* @param hint Optional. Additional context or information about the synchronization check.
* Helpful for understanding the intent or specifics of the check. Default is None.
* @return A [[com.amazon.deequ.checks.Check]] object representing the outcome
* of the synchronization check. This object can be used in Deequ's verification suite to
* assert data quality constraints.
*
*/
def isDataSynchronized(otherDf: DataFrame, columnMappings: Map[String, String], assertion: Double => Boolean,
hint: Option[String] = None): Check = {
val dataSyncAnalyzer = DataSynchronizationAnalyzer(otherDf, columnMappings, assertion)
val constraint = AnalysisBasedConstraint[DataSynchronizationState, Double, Double](dataSyncAnalyzer, assertion,
hint = hint)
addConstraint(constraint)
}
/**
* Creates a constraint that asserts on the number of distinct values a column has.
*
* @param column Column to run the assertion on
* @param assertion Function that receives a long input parameter and returns a boolean
* @param binningUdf An optional binning function
* @param maxBins Histogram details is only provided for N column values with top counts.
* maxBins sets the N
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasNumberOfDistinctValues(
column: String,
assertion: Long => Boolean,
binningUdf: Option[UserDefinedFunction] = None,
maxBins: Integer = Histogram.MaximumAllowedDetailBins,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter =>
histogramBinConstraint(column, assertion, binningUdf, maxBins, filter, hint, computeFrequenciesAsRatio = false) }
}
/**
* Creates a constraint that asserts on column's value distribution.
*
* @param column Column to run the assertion on
* @param assertion Function that receives a Distribution input parameter and returns a boolean.
* E.g
* .hasHistogramValues("att2", _.absolutes("f") == 3)
* .hasHistogramValues("att2",
* _.ratios(Histogram.NullFieldReplacement) == 2/6.0)
* @param binningUdf An optional binning function
* @param maxBins Histogram details is only provided for N column values with top counts.
* maxBins sets the N
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasHistogramValues(
column: String,
assertion: Distribution => Boolean,
binningUdf: Option[UserDefinedFunction] = None,
maxBins: Integer = Histogram.MaximumAllowedDetailBins,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter =>
histogramConstraint(column, assertion, binningUdf, maxBins, filter, hint) }
}
/**
* Creates a constraint that asserts on column's sketch size.
*
* @param column Column to run the assertion on
* @param assertion Function that receives a Distribution input parameter and returns a boolean.
* E.g
* .hasLargeKLLSketchSize("att2", _.parameters(1) >= 16,
* kllParameters = Option(kllParameters(2, 0.64, 2)))
* @param kllParameters parameters of KLL Sketch
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def kllSketchSatisfies(
column: String,
assertion: BucketDistribution => Boolean,
kllParameters: Option[KLLParameters] = None,
hint: Option[String] = None)
: Check = {
addConstraint(kllConstraint(column, assertion, kllParameters, hint))
}
/**
* Creates a constraint that runs AnomalyDetection on the new value
*
* @param metricsRepository A metrics repository to get the previous results
* @param anomalyDetectionStrategy The anomaly detection strategy
* @param analyzer The analyzer for the metric to run anomaly detection on
* @param withTagValues Can contain a Map with tag names and the corresponding values
* to filter for
* @param beforeDate The maximum dateTime of previous AnalysisResults to use for
* the Anomaly Detection
* @param afterDate The minimum dateTime of previous AnalysisResults to use for
* the Anomaly Detection
* @param hint A hint to provide additional context why a constraint
* could have failed
* @return
*/
private[deequ] def isNewestPointNonAnomalous[S <: State[S]](
metricsRepository: MetricsRepository,
anomalyDetectionStrategy: AnomalyDetectionStrategy,
analyzer: Analyzer[S, Metric[Double]],
withTagValues: Map[String, String],
afterDate: Option[Long],
beforeDate: Option[Long],
hint: Option[String] = None)
: Check = {
val anomalyAssertionFunction = Check.isNewestPointNonAnomalous(
metricsRepository,
anomalyDetectionStrategy,
analyzer,
withTagValues,
afterDate,
beforeDate
)(_)
addConstraint(anomalyConstraint(analyzer, anomalyAssertionFunction, hint))
}
/**
* Creates a constraint that asserts on a column entropy.
*
* @param column Column to run the assertion on
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasEntropy(
column: String,
assertion: Double => Boolean,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter => entropyConstraint(column, assertion, filter, hint) }
}
/**
* Creates a constraint that asserts on a mutual information between two columns.
*
* @param columnA First column for mutual information calculation
* @param columnB Second column for mutual information calculation
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasMutualInformation(
columnA: String,
columnB: String,
assertion: Double => Boolean,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter =>
mutualInformationConstraint(columnA, columnB, assertion, filter, hint) }
}
/**
* Creates a constraint that asserts on an approximated quantile
*
* @param column Column to run the assertion on
* @param quantile Which quantile to assert on
* @param assertion Function that receives a double input parameter (the computed quantile)
* and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasApproxQuantile(column: String,
quantile: Double,
assertion: Double => Boolean,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint( filter =>
approxQuantileConstraint(column, quantile, assertion, filter, hint))
}
/**
* Creates a constraint that asserts on an exact quantile
*
* @param column Column to run the assertion on
* @param quantile Which quantile to assert on
* @param assertion Function that receives a double input parameter (the computed quantile)
* and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasExactQuantile(column: String,
quantile: Double,
assertion: Double => Boolean,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint(filter =>
exactQuantileConstraint(column, quantile, assertion, filter, hint))
}
/**
* Creates a constraint that asserts on the minimum length of the column
*
* @param column Column to run the assertion on
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasMinLength(
column: String,
assertion: Double => Boolean,
hint: Option[String] = None,
analyzerOptions: Option[AnalyzerOptions] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter => minLengthConstraint(column, assertion, filter, hint, analyzerOptions) }
}
/**
* Creates a constraint that asserts on the maximum length of the column
*
* @param column Column to run the assertion on
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasMaxLength(
column: String,
assertion: Double => Boolean,
hint: Option[String] = None,
analyzerOptions: Option[AnalyzerOptions] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter => maxLengthConstraint(column, assertion, filter, hint, analyzerOptions) }
}
/**
* Creates a constraint that asserts on the minimum of the column
*
* @param column Column to run the assertion on
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasMin(
column: String,
assertion: Double => Boolean,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter => minConstraint(column, assertion, filter, hint) }
}
/**
* Creates a constraint that asserts on the maximum of the column
*
* @param column Column to run the assertion on
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasMax(
column: String,
assertion: Double => Boolean,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter => maxConstraint(column, assertion, filter, hint) }
}
/**
* Creates a constraint that asserts on the mean of the column
*
* @param column Column to run the assertion on
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasMean(
column: String,
assertion: Double => Boolean,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter => meanConstraint(column, assertion, filter, hint) }
}
/**
* Creates a constraint that asserts on the sum of the column
*
* @param column Column to run the assertion on
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasSum(
column: String,
assertion: Double => Boolean,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter => sumConstraint(column, assertion, filter, hint) }
}
/**
* Creates a constraint that asserts on the standard deviation of the column
*
* @param column Column to run the assertion on
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasStandardDeviation(
column: String,
assertion: Double => Boolean,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter =>
standardDeviationConstraint(column, assertion, filter, hint) }
}
/**
* Creates a constraint that asserts on the approximate count distinct of the given column
*
* @param column Column to run the assertion on
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasApproxCountDistinct(
column: String,
assertion: Double => Boolean,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter =>
approxCountDistinctConstraint(column, assertion, filter, hint) }
}
/**
* Creates a constraint that asserts on the pearson correlation between two columns.
*
* @param columnA First column for correlation calculation
* @param columnB Second column for correlation calculation
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasCorrelation(
columnA: String,
columnB: String,
assertion: Double => Boolean,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter =>
correlationConstraint(columnA, columnB, assertion, filter, hint) }
}
/**
* Creates a constraint that runs the given condition on the data frame.
*
* @param columnCondition Data frame column which is a combination of expression and the column
* name. It has to comply with Spark SQL syntax.
* Can be written in an exact same way with conditions inside the
* `WHERE` clause.
* @param constraintName A name that summarizes the check being made. This name is being used to
* name the metrics for the analysis being done.
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def satisfies(
columnCondition: String,
constraintName: String,
assertion: Double => Boolean = Check.IsOne,
hint: Option[String] = None,
columns: List[String] = List.empty[String])
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter =>
complianceConstraint(constraintName, columnCondition, assertion, filter, hint, columns)
}
}
/**
* Checks for pattern compliance. Given a column name and a regular expression, defines a
* Check on the average compliance of the column's values to the regular expression.
*
* @param column Name of the column that should be checked.
* @param pattern The columns values will be checked for a match against this pattern.
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasPattern(
column: String,
pattern: Regex,
assertion: Double => Boolean = Check.IsOne,
name: Option[String] = None,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter =>
Constraint.patternMatchConstraint(column, pattern, assertion, filter, name, hint)
}
}
/**
* Check to run against the compliance of a column against a Credit Card pattern.
*
* @param column Name of the column that should be checked.
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def containsCreditCardNumber(
column: String,
assertion: Double => Boolean = Check.IsOne,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
hasPattern(column, Patterns.CREDITCARD, assertion, Some(s"containsCreditCardNumber($column)"),
hint)
}
/**
* Check to run against the compliance of a column against an e-mail pattern.
*
* @param column Name of the column that should be checked.
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def containsEmail(
column: String,
assertion: Double => Boolean = Check.IsOne,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
hasPattern(column, Patterns.EMAIL, assertion, Some(s"containsEmail($column)"), hint)
}
/**
* Check to run against the compliance of a column against an URL pattern.
*
* @param column Name of the column that should be checked.
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def containsURL(
column: String,
assertion: Double => Boolean = Check.IsOne,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
hasPattern(column, Patterns.URL, assertion, Some(s"containsURL($column)"), hint)
}
/**
* Check to run against the compliance of a column against the Social security number pattern
* for the US.
*
* @param column Name of the column that should be checked.
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def containsSocialSecurityNumber(
column: String,
assertion: Double => Boolean = Check.IsOne,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
hasPattern(column, Patterns.SOCIAL_SECURITY_NUMBER_US, assertion,
Some(s"containsSocialSecurityNumber($column)"), hint)
}
/**
* Check to run against the fraction of rows that conform to the given data type.
*
* @param column Name of the columns that should be checked.
* @param dataType Data type that the columns should be compared against.
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def hasDataType(
column: String,
dataType: ConstrainableDataTypes.Value,
assertion: Double => Boolean = Check.IsOne,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
addFilterableConstraint { filter =>
Constraint.dataTypeConstraint(column, dataType, assertion, filter, hint) }
}
/**
* Creates a constraint that asserts that a column contains no negative values
*
* @param column Column to run the assertion on
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def isNonNegative(
column: String,
assertion: Double => Boolean = Check.IsOne,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
satisfies(
// coalescing column to not count NULL values as non-compliant
// NOTE: cast to DECIMAL(20, 10) is needed to handle scientific notations
s"COALESCE(CAST($column AS DECIMAL(20,10)), 0.0) >= 0",
s"$column is non-negative",
assertion,
hint = hint,
columns = List(column)
)
}
/**
* Creates a constraint that asserts that a column contains no negative values
*
* @param column Column to run the assertion on
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def isPositive(
column: String,
assertion: Double => Boolean = Check.IsOne,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
// coalescing column to not count NULL values as non-compliant
// NOTE: cast to DECIMAL(20, 10) is needed to handle scientific notations
satisfies(
s"COALESCE(CAST($column AS DECIMAL(20,10)), 1.0) > 0",
s"$column is positive",
assertion,
hint,
columns = List(column)
)
}
/**
*
* Asserts that, in each row, the value of columnA is less than the value of columnB
*
* @param columnA Column to run the assertion on
* @param columnB Column to run the assertion on
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def isLessThan(
columnA: String,
columnB: String,
assertion: Double => Boolean = Check.IsOne,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
satisfies(s"$columnA < $columnB", s"$columnA is less than $columnB", assertion,
hint = hint, columns = List(columnA, columnB))
}
/**
* Asserts that, in each row, the value of columnA is less than or equal to the value of columnB
*
* @param columnA Column to run the assertion on
* @param columnB Column to run the assertion on
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def isLessThanOrEqualTo(
columnA: String,
columnB: String,
assertion: Double => Boolean = Check.IsOne,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
satisfies(s"$columnA <= $columnB", s"$columnA is less than or equal to $columnB",
assertion, hint = hint, columns = List(columnA, columnB))
}
/**
* Asserts that, in each row, the value of columnA is greater than the value of columnB
*
* @param columnA Column to run the assertion on
* @param columnB Column to run the assertion on
* @param assertion Function that receives a double input parameter and returns a boolean
* @param hint A hint to provide additional context why a constraint could have failed
* @return
*/
def isGreaterThan(
columnA: String,
columnB: String,
assertion: Double => Boolean = Check.IsOne,
hint: Option[String] = None)
: CheckWithLastConstraintFilterable = {
satisfies(s"$columnA > $columnB", s"$columnA is greater than $columnB",