๐ Data Engineering
Great Expectations
Great Expectations
A data quality validation framework. Define expectations and run tests.
Great Expectations
A data quality validation framework. Define expectations and run tests.
Great Expectations (GX) is an open-source Python library for validating and documenting data quality. It defines "Expectations" about your data and automatically verifies whether the actual data meets them.
| Categories | Expectation | Description |
|---|---|---|
| Column Existence | expect_column_to_exist | Check that a specific column exists |
| Null Check | expect_column_values_to_not_be_null | Check that there are no null values |
| Uniqueness | expect_column_values_to_be_unique | Check that there are no duplicate values |
| Range | expect_column_values_to_be_between | Check the value range |
| Set | expect_column_values_to_be_in_set | Check the set of allowed values |
| Pattern | expect_column_values_to_match_regex | Regular expression pattern matching |
# Great Expectations๋ฅผ ์ฌ์ฉํ ๋ฐ์ดํฐ ํ์ง ๊ฒ์ฆ
import great_expectations as gx
from great_expectations.core.expectation_configuration import ExpectationConfiguration
import pandas as pd
# ์ปจํ
์คํธ ์ด๊ธฐํ
context = gx.get_context()
# ๋ฐ์ดํฐ ์์ค ์ค์
datasource = context.sources.add_pandas("my_pandas_datasource")
# ๋ฐ์ดํฐ ์์
์ถ๊ฐ
data_asset = datasource.add_dataframe_asset(name="user_data")
# ์ํ ๋ฐ์ดํฐ๋ก ๋ฐฐ์น ์์ฒญ
df = pd.DataFrame({
'user_id': [1, 2, 3, 4, 5],
'email': ['a@test.com', 'b@test.com', 'c@test.com', 'd@test.com', 'e@test.com'],
'age': [25, 30, 35, 40, -5], # -5๋ ์ด์๊ฐ
'status': ['active', 'inactive', 'active', 'pending', 'unknown']
})
batch_request = data_asset.build_batch_request(dataframe=df)
# Expectation Suite ์์ฑ
suite_name = "user_data_quality_suite"
context.add_or_update_expectation_suite(expectation_suite_name=suite_name)
# Validator ์์ฑ
validator = context.get_validator(
batch_request=batch_request,
expectation_suite_name=suite_name
)
# Expectations ์ ์
# 1. user_id๋ null์ด ์๋์ด์ผ ํจ
validator.expect_column_values_to_not_be_null(column="user_id")
# 2. user_id๋ ์ ์ผํด์ผ ํจ
validator.expect_column_values_to_be_unique(column="user_id")
# 3. email์ ์ด๋ฉ์ผ ํ์์ด์ด์ผ ํจ
validator.expect_column_values_to_match_regex(
column="email",
regex=r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
)
# 4. age๋ 0~120 ์ฌ์ด์ฌ์ผ ํจ
validator.expect_column_values_to_be_between(
column="age",
min_value=0,
max_value=120
)
# 5. status๋ ํน์ ๊ฐ๋ค ์ค ํ๋์ฌ์ผ ํจ
validator.expect_column_values_to_be_in_set(
column="status",
value_set=["active", "inactive", "pending"]
)
# Suite ์ ์ฅ
validator.save_expectation_suite(discard_failed_expectations=False)
# ๊ฒ์ฆ ์คํ
checkpoint = context.add_or_update_checkpoint(
name="user_data_checkpoint",
validations=[
{
"batch_request": batch_request,
"expectation_suite_name": suite_name
}
]
)
result = checkpoint.run()
print(f"๊ฒ์ฆ ์ฑ๊ณต: {result.success}")
# Airflow DAG์์ Great Expectations ์ฌ์ฉ
from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.utils.dates import days_ago
import great_expectations as gx
def validate_source_data(**context):
"""์์ค ๋ฐ์ดํฐ ๊ฒ์ฆ"""
gx_context = gx.get_context()
checkpoint_result = gx_context.run_checkpoint(
checkpoint_name="source_data_checkpoint"
)
if not checkpoint_result.success:
# ๊ฒ์ฆ ์คํจ ์ ์์ธ ์ ๋ณด ๋ก๊น
for validation_result in checkpoint_result.run_results.values():
for result in validation_result["validation_result"]["results"]:
if not result["success"]:
print(f"์คํจ: {result['expectation_config']['expectation_type']}")
print(f"์ธ๋ถ์ฌํญ: {result['result']}")
raise ValueError("๋ฐ์ดํฐ ํ์ง ๊ฒ์ฆ ์คํจ!")
return "๊ฒ์ฆ ํต๊ณผ"
def validate_transformed_data(**context):
"""๋ณํ๋ ๋ฐ์ดํฐ ๊ฒ์ฆ"""
gx_context = gx.get_context()
checkpoint_result = gx_context.run_checkpoint(
checkpoint_name="transformed_data_checkpoint"
)
if not checkpoint_result.success:
raise ValueError("๋ณํ ๋ฐ์ดํฐ ํ์ง ๊ฒ์ฆ ์คํจ!")
return "๋ณํ ๋ฐ์ดํฐ ๊ฒ์ฆ ํต๊ณผ"
with DAG(
dag_id="data_quality_pipeline",
start_date=days_ago(1),
schedule_interval="@daily",
catchup=False
) as dag:
validate_source = PythonOperator(
task_id="validate_source_data",
python_callable=validate_source_data
)
# ETL ์์
(์๋ต)
# transform_data = ...
validate_output = PythonOperator(
task_id="validate_transformed_data",
python_callable=validate_transformed_data
)
validate_source >> validate_output
# great_expectations/expectations/user_data_suite.json
{
"expectation_suite_name": "user_data_suite",
"ge_cloud_id": null,
"expectations": [
{
"expectation_type": "expect_table_row_count_to_be_between",
"kwargs": {
"min_value": 1,
"max_value": 1000000
},
"meta": {
"notes": "ํ
์ด๋ธ์ ์ต์ 1๊ฐ, ์ต๋ 100๋ง ๊ฐ์ ํ์ด ์์ด์ผ ํจ"
}
},
{
"expectation_type": "expect_column_values_to_not_be_null",
"kwargs": {
"column": "user_id"
},
"meta": {
"notes": "user_id๋ ํ์ ํ๋"
}
},
{
"expectation_type": "expect_column_values_to_be_unique",
"kwargs": {
"column": "user_id"
},
"meta": {
"notes": "user_id๋ ๊ธฐ๋ณธ ํค๋ก ์ ์ผํด์ผ ํจ"
}
},
{
"expectation_type": "expect_column_values_to_be_between",
"kwargs": {
"column": "age",
"min_value": 0,
"max_value": 120,
"mostly": 0.99
},
"meta": {
"notes": "age๋ 0-120 ์ฌ์ด, 99% ์ด์ ์ถฉ์กฑ ํ์"
}
},
{
"expectation_type": "expect_column_values_to_match_strftime_format",
"kwargs": {
"column": "created_at",
"strftime_format": "%Y-%m-%d %H:%M:%S"
},
"meta": {
"notes": "๋ ์ง ํ์ ๊ฒ์ฆ"
}
}
],
"data_asset_type": null
}
# ์ปค์คํ
Expectation ์ ์
from great_expectations.expectations.expectation import ColumnMapExpectation
from great_expectations.execution_engine import PandasExecutionEngine
from great_expectations.expectations.metrics import ColumnMapMetricProvider, column_condition_partial
class ExpectColumnValuesToBeValidKoreanPhoneNumber(ColumnMapExpectation):
"""ํ๊ตญ ์ ํ๋ฒํธ ํ์ ๊ฒ์ฆ Expectation"""
expectation_type = "expect_column_values_to_be_valid_korean_phone_number"
# ์ค๋ช
map_metric = "column_values.valid_korean_phone"
success_keys = ("mostly",)
default_kwarg_values = {
"mostly": 1.0, # ๊ธฐ๋ณธ์ ์ผ๋ก 100% ์ถฉ์กฑ ํ์
}
class ColumnValuesValidKoreanPhone(ColumnMapMetricProvider):
condition_metric_name = "column_values.valid_korean_phone"
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
import re
# ํ๊ตญ ์ ํ๋ฒํธ ํจํด: 010-1234-5678 ๋๋ 02-123-4567
pattern = r'^(01[016789]-\d{3,4}-\d{4}|0\d{1,2}-\d{3,4}-\d{4})$'
return column.str.match(pattern, na=False)
# ์ฌ์ฉ ์์
validator.expect_column_values_to_be_valid_korean_phone_number(
column="phone_number",
mostly=0.95 # 95% ์ด์ ์ถฉ์กฑ
)