Automation7 min read

Great Expectations: Data Quality Testing with GX Core

How GX Core 1.x works: Data Context, Data Sources, Batch Definitions, Expectation Suites, Validation Definitions, Checkpoints and Data Docs, with working code.

By AI Agents DirectoryLast checked
A laptop and a tablet on a desk

Great Expectations (GX) lets you write tests for data the way you write unit tests for code. You state what a column or table should look like, run those assertions against a batch of records, and get back a structured pass/fail report. This guide covers GX Core, the open-source Python library, using the 1.x API as the official documentation describes it in version 1.24.1. A lot of older tutorials online still show the 0.x API, which no longer runs as written, so the code here comes from the current docs and was run against 1.24.1.

What you get

GX Core is licensed Apache-2.0. Its source lives in the fivetran/great_expectations repository on GitHub, and the package installs from PyPI as great_expectations. The docs list Python 3.10 to 3.14 as supported.

Install it in a virtual environment:

pip install great_expectations

GX connects to three broad kinds of data: SQL databases, files in a folder hierarchy (local or cloud object storage), and in-memory pandas or Spark dataframes.

The pieces and how they fit

Every GX workflow follows the same four steps: set up a context, connect to data, define Expectations, then run validations. Each step has its own objects.

ComponentWhat it does
Data ContextThe entry point. Holds configuration for sources, suites and checkpoints, plus validation results
Data SourceTells GX how to reach a data store (a database, a file location, a dataframe type)
Data AssetA set of records inside a source, such as one table or a query result
Batch DefinitionDecides how an asset is split into Batches: the whole thing, or by year, month or day
ExpectationOne checkable assertion, for example “values in this column fall between 1 and 6”
Expectation SuiteA named group of Expectations applied together
Validation DefinitionPairs one Batch Definition with one Expectation Suite
CheckpointRuns one or more Validation Definitions and then fires Actions on the results
Data DocsStatic HTML pages that render your suites and validation results

Data Context: file or ephemeral

gx.get_context() looks for a File Data Context in the current folder and its parents. If it finds none, you get an Ephemeral Data Context that lives only in memory for that Python session.

  • File Data Context (mode="file") writes configuration as files on disk, so suites, sources and checkpoints survive between runs and can sit in version control.
  • Ephemeral Data Context (mode="ephemeral") suits throwaway work: exploring data, CI jobs where the environment is rebuilt every time, or containers and hosted notebooks with no persistent disk.

Expectations, severity and mostly

Expectations are classes in gx.expectations, named after what they check: ExpectColumnValuesToBeBetween, ExpectColumnValuesToNotBeNull, ExpectColumnMaxToBeBetween and many more. The Expectation Gallery lists them with their arguments.

Two optional parameters matter in practice:

  • severity can be critical, warning or info. If you leave it out, the Expectation is treated as critical. Checkpoint Actions can react differently depending on the worst failure.
  • mostly lets an Expectation pass when only a fraction of rows meet it, for columns where a small amount of noise is acceptable.

Parameters such as min_value can also be filled in at run time. You pass {"$PARAMETER": "some_key"} when you create the Expectation, then supply expectation_parameters={"some_key": ...} when you run the Checkpoint.

A working example

This is the official Try GX Core quickstart, using its pandas path with the suite and Checkpoint from its SQL path, so it runs without a database. It loads a sample of NYC taxi trips and checks two things: passenger count between 1 and 6 (a warning) and fares not negative (critical).

import great_expectations as gx
import pandas as pd

context = gx.get_context()
df = pd.read_csv(
    "https://raw.githubusercontent.com/great-expectations/gx_tutorials/main/data/yellow_tripdata_sample_2019-01.csv"
)

# Connect: Data Source -> Data Asset -> Batch Definition
data_source = context.data_sources.add_pandas("pandas")
data_asset = data_source.add_dataframe_asset(name="pd dataframe asset")
batch_definition = data_asset.add_batch_definition_whole_dataframe("batch definition")

# Define Expectations in a suite
suite = context.suites.add(gx.ExpectationSuite(name="taxi_suite"))
suite.add_expectation(gx.expectations.ExpectColumnValuesToBeBetween(
    column="passenger_count", min_value=1, max_value=6, severity="warning"))
suite.add_expectation(gx.expectations.ExpectColumnValuesToBeBetween(
    column="fare_amount", min_value=0, severity="critical"))

# Tie data to suite, then run through a Checkpoint
vd = context.validation_definitions.add(
    gx.ValidationDefinition(name="taxi_vd", data=batch_definition, suite=suite))
checkpoint = context.checkpoints.add(
    gx.Checkpoint(name="taxi_cp", validation_definitions=[vd]))

result = checkpoint.run(batch_parameters={"dataframe": df})
print(result.describe())

With a dataframe, the data itself goes in at run time through batch_parameters. For a SQL table or files, the Batch Definition already knows where the data is, and batch_parameters instead picks a slice such as {"year": 2019, "month": 1}.

In our run the passenger check passed and the fare check failed. The result JSON shows how many rows broke the rule, a sample of the bad values (negative fares such as -52.0) and their row indexes. The docs’ SQL version of the same suite reports the same pattern: one Expectation met, one not. By default only part of the failing values is included; the result_format setting controls how much detail you get.

To use this as a gate in a pipeline, check the outcome and stop:

if not result.success:
    raise RuntimeError("Data quality check failed")

Checkpoint Actions and Data Docs

A Checkpoint can do more than return results. Actions live in great_expectations.checkpoint and their class names end in Action. The docs show two together:

from great_expectations.checkpoint import SlackNotificationAction, UpdateDataDocsAction

actions = [
    SlackNotificationAction(
        name="send_slack_notification_on_failed_expectations",
        slack_token="${validation_notification_slack_webhook}",
        slack_channel="${validation_notification_slack_channel}",
        notify_on="failure",
        show_failed_expectations=True,
    ),
    UpdateDataDocsAction(name="update_all_data_docs"),
]
checkpoint = gx.Checkpoint(name="my_checkpoint",
                           validation_definitions=validation_definitions,
                           actions=actions)

notify_on accepts all, success, failure, critical, warning or info. The highest severity in a result wins, so a run with both warning and info failures triggers warning Actions but not info ones. The ${...} strings are filled from environment variables, which keeps tokens out of code.

The Data Docs setup guide assumes a File Data Context. By default the site is written under uncommitted/data_docs/local_site/ inside the project folder. You can build it by hand with context.build_data_docs() or let UpdateDataDocsAction rebuild it after each Checkpoint run. Because the pages are generated from the suites themselves, the documentation stays in step with the tests.

Coming from GX 0.x

If your existing code calls context.get_validator(...) and then validator.expect_..., it was written for 0.x. The GX V0 to V1 migration guide spells out the changes. Among them:

  • Validation Definitions became a separate object, and Checkpoints now take a list of them instead of the old validations block with top-level arguments.
  • evaluation_parameters was renamed suite_parameters.
  • Arbitrary batching regexes are gone; time-based Batch Definitions are yearly, monthly or daily.
  • Options such as template_name and run_name_template on Checkpoints are no longer supported.

Treat any blog post or Stack Overflow answer that uses get_validator or YAML Checkpoint files as 0.x material.

Where GX fits in ML and LLM pipelines

Models are only as good as what goes into them, and GX checks are cheap to run at each handoff. A few patterns that use only the features above:

  • Before training. Run a suite on the training table: no nulls in the label column, feature ranges within known bounds, categorical columns limited to a fixed set. Failing the build on critical errors stops a bad batch from producing a bad model. Pair it with model versioning so you know which data each model saw.
  • After LLM extraction. If you use an LLM to turn free text into rows, as in using LLMs in data pipelines, a schema library such as Instructor checks each record’s shape. GX checks the whole batch: are invoice totals ever negative, are dates inside the expected window, did a required field come back empty too often. Load the extracted rows into a dataframe and validate them before they reach a database.
  • Per stage. The docs suggest giving each pipeline stage its own dataframe Data Asset so validation results are grouped by stage. That makes it easy to see whether bad values appeared at ingestion, after cleaning (for example with IBM data-prep-kit), or after model output.
  • In CI. An Ephemeral Data Context fits CI, where nothing persists between runs. Keep suites in code, run the Checkpoint, and fail the job on result.success == False.

For more tools in this space, see the data and research category.

Limits worth knowing

GX tells you whether data matches rules you wrote. It does not invent the rules, so a suite is only as useful as the assumptions you encode. Dataframe Batch Definitions always cover the whole dataframe, so slicing happens before you hand it over. The Data Docs configuration guide assumes a File Data Context, so plan on one if you want a persistent HTML site. And because the 1.x API differs so much from 0.x, check the version banner on any documentation page you follow.

#Great Expectations#Data quality#Data engineering#Python#MLOps
AI

Written by AI Agents Directory

Editorial team

Facts in this guide are checked against official documentation and repositories, which are linked in the article.