๐Ÿ“Š Data Engineering

Great Expectations

Great Expectations

A data quality validation framework. Define expectations and run tests.

Detailed Explanation

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.

Core Concepts of Great Expectations

  • Expectation: A validation rule for data (e.g., no nulls, values within a range)
  • Expectation Suite: A collection of Expectations
  • Checkpoint: A unit of validation execution
  • Data Docs: Automatically generated documentation pages
  • Validation Result: A validation result report

Main Expectation Types

CategoriesExpectationDescription
Column Existenceexpect_column_to_existCheck that a specific column exists
Null Checkexpect_column_values_to_not_be_nullCheck that there are no null values
Uniquenessexpect_column_values_to_be_uniqueCheck that there are no duplicate values
Rangeexpect_column_values_to_be_betweenCheck the value range
Setexpect_column_values_to_be_in_setCheck the set of allowed values
Patternexpect_column_values_to_match_regexRegular expression pattern matching

Code Example

Basic Data Validation Setup

# 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}")

Integration with ETL Pipelines

# 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

Defining an Expectation Suite in YAML

# 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
}

Writing Custom Expectations

# ์ปค์Šคํ…€ 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% ์ด์ƒ ์ถฉ์กฑ
)

Practical Conversation Example

Data Engineer: "Sometimes bad data comes into our ETL pipeline and the analysis results end up looking strange. Is there any way to prevent that in advance?"
Data Team Lead: "Let's adopt Great Expectations. If we define expectations for our data and validate automatically in the ETL pipeline, we can keep bad data from getting in."
Data Engineer: "How do we define the expectations? One by one, manually?"
Data Team Lead: "If you use the Profiler, it analyzes existing data and recommends expectations automatically. You can adjust them from there. For example, if the age column is between 0 and 100, it automatically generates a range expectation."
Data Engineer: "How do we handle it when validation fails?"
Data Team Lead: "In an Airflow task, you can set it to stop the pipeline when validation fails, or to send a notification to Slack. You can also see visually which rules failed through Data Docs."

Cautions

Expectation Design

  • Expectations that are too strict can reject normal data as well
  • Set an acceptable ratio with the mostly parameter (e.g., 99% satisfied)
  • Expectations need to be defined to match business requirements

Performance Considerations

  • Consider sampling when validating large datasets
  • Validating all columns takes a long time - prioritize important columns
  • Use pushdown queries when integrating with Spark/BigQuery

Operational Cautions

  • The Expectation Suite needs to be updated when the schema changes
  • Re-review expectations when new data patterns appear
  • Build a system for managing validation result history and monitoring

Related Terms

Learn More