DataChain
The DataChain class creates a data chain, which is a sequence of data manipulation
steps such as reading data from storages, running AI or LLM models or calling external
services API to validate or enrich data. See DataChain
for examples of how to create a chain.
C
module-attribute
ConnectionType
module-attribute
listings
Generate chain with list of cached listings. Listing is a special kind of dataset which has directory listing data of some underlying storage (e.g S3 bucket).
Example
Source code in datachain/lib/dc/listings.py
read_csv
Generate chain from csv files.
Parameters:
-
path(str | PathLike[str] | list[str] | list[PathLike[str]]) –Storage URI with directory. URI must start with storage prefix such as
s3://,gs://,az://or "file:///". -
delimiter(str | None, default:None) –Character for delimiting columns. Takes precedence if also specified in
parse_options. Defaults to ",". -
header(bool, default:True) –Whether the files include a header row.
-
output(OutputType, default:None) –Dictionary or feature class defining column names and their corresponding types. List of column names is also accepted, in which case types will be inferred.
-
column(str, default:'') –Created column name.
-
model_name(str, default:'') –Generated model name.
-
source(bool, default:True) –Whether to include info about the source file.
-
nrows(int | None, default:None) –Optional row limit.
-
session(Session | None, default:None) –Session to use for the chain.
-
settings(dict | None, default:None) –Settings to use for the chain.
-
column_types(dict[str, str | DataType] | None, default:None) –Dictionary of column names and their corresponding types. It is passed to CSV reader and for each column specified type auto inference is disabled.
-
parse_options(dict[str, str | bool | Callable] | None, default:None) –Tells the parser how to process lines. See https://arrow.apache.org/docs/python/generated/pyarrow.csv.ParseOptions.html
Example
Reading a csv file:
Reading csv files from a directory as a combined dataset:
Source code in datachain/lib/dc/csv.py
read_dataset
Get data from a saved Dataset. It returns the chain itself. If dataset or version is not found locally, it will try to pull it from Studio.
Parameters:
-
name(str) –The dataset name, which can be a fully qualified name including the namespace and project. Alternatively, it can be a regular name, in which case the explicitly defined namespace and project will be used if they are set; otherwise, default values will be applied. The name can also include a version using the
name@versionformat (e.g."my_dataset@1.0.0"). Ifversionis also provided explicitly, it takes priority. -
namespace(str | None, default:None) –optional name of namespace in which dataset to read is created
-
project(str | None, default:None) –optional name of project in which dataset to read is created
-
version(str | int | None, default:None) –dataset version. Supports: - Exact version strings: "1.2.3" - Legacy integer versions: 1, 2, 3 (finds latest major version) - Version specifiers (PEP 440): ">=1.0.0,<2.0.0", "~=1.4.2", "==1.2.*", etc.
-
session(Session | None, default:None) –Session to use for the chain.
-
settings(dict | None, default:None) –Settings to use for the chain.
-
delta(bool | None, default:False) –If True, only process new or changed files instead of reprocessing everything. This saves time by skipping files that were already processed in previous versions. The optimization is working when a new version of the dataset is created. Default is False.
-
delta_on(str | Sequence[str] | None, default:('file.path', 'file.etag', 'file.version')) –Field(s) that uniquely identify each record in the source data. Used to detect which records are new or changed. Default is ("file.path", "file.etag", "file.version").
-
delta_result_on(str | Sequence[str] | None, default:None) –Field(s) in the result dataset that match
delta_onfields. Only needed if you rename the identifying fields during processing. Default is None. -
delta_compare(str | Sequence[str] | None, default:None) –Field(s) used to detect if a record has changed. If not specified, all fields except
delta_onfields are used. Default is None. -
delta_retry(bool | str | None, default:None) –Controls retry behavior for failed records: - String (field name): Reprocess records where this field is not empty (error mode) - True: Reprocess records missing from the result dataset (missing mode) - None: No retry processing (default)
-
update(bool, default:False) –If True always checks for newer versions available on Studio, even if some version of the dataset exists locally already. If False (default), it will only fetch the dataset from Studio if it is not found locally.
-
delta_unsafe(bool, default:False) –Allow restricted ops in delta: merge, union, subtract, diff, file_diff, agg, group_by, distinct. When multiple delta sources participate in one composed query, this must be enabled on every participating delta source.
Example
Source code in datachain/lib/dc/datasets.py
read_hf
Generate chain from Hugging Face Hub dataset.
Parameters:
-
dataset(HFDatasetType) –Path or name of the dataset to read from Hugging Face Hub, or an instance of
datasets.Dataset-like object. -
args(Any, default:()) –Additional positional arguments to pass to
datasets.load_dataset. -
session(Session | None, default:None) –Session to use for the chain.
-
settings(dict | None, default:None) –Settings to use for the chain.
-
column(str, default:'') –Generated object column name.
-
model_name(str, default:'') –Generated model name.
-
limit(int, default:0) –The maximum number of items to read from the HF dataset. Applies
take(limit)todatasets.load_dataset. Defaults to 0 (no limit). -
kwargs(Any, default:{}) –Parameters to pass to
datasets.load_dataset.
Example
Load from Hugging Face Hub:
Generate chain from loaded dataset:
Streaming with limit, for large datasets:
or use HF split syntax (not supported if streaming is enabled):
Source code in datachain/lib/dc/hf.py
read_json
Get data from JSON. It returns the chain itself.
Parameters:
-
path(str | PathLike[str]) –storage URI with directory. URI must start with storage prefix such as
s3://,gs://,az://or "file:///" -
type(FileType, default:'text') –read file as "binary", "text", or "image" data. Default is "text".
-
spec(DataType | None, default:None) –optional Data Model
-
schema_from(str | None, default:'auto') –path to sample to infer spec (if schema not provided)
-
column(str | None, default:'') –generated column name
-
model_name(str | None, default:None) –optional generated model name
-
format(str | None, default:'json') –"json", "jsonl"
-
jmespath(str | None, default:None) –optional JMESPATH expression to reduce JSON
-
nrows(int | None, default:None) –optional row limit for jsonl and JSON arrays
Example
infer JSON schema from data, reduce using JMESPATH
infer JSON schema from a particular path
Source code in datachain/lib/dc/json.py
read_pandas
Generate chain from pandas data-frame.
Example
Source code in datachain/lib/dc/pandas.py
read_parquet
Generate chain from parquet files.
Parameters:
-
path(str | PathLike[str] | list[str] | list[PathLike[str]]) –Storage path(s) or URI(s). Can be a local path or start with a storage prefix like
s3://,gs://,az://,hf://or "file:///". Supports glob patterns: -*: wildcard -**: recursive wildcard -?: single character -{a,b}: brace expansion list -{1..9}: brace numeric or alphabetic range -
partitioning(Any, default:'hive') –Any pyarrow partitioning schema.
-
output(dict[str, DataType] | None, default:None) –Dictionary defining column names and their corresponding types.
-
column(str, default:'') –Created column name.
-
model_name(str, default:'') –Generated model name.
-
source(bool, default:True) –Whether to include info about the source file.
-
session(Session | None, default:None) –Session to use for the chain.
-
settings(dict | None, default:None) –Settings to use for the chain.
Example
Reading a single file:
All files from a directory:
Only parquet files from a directory, and all it's subdirectories:
Using filename patterns - numeric, list, starting with zeros:
Source code in datachain/lib/dc/parquet.py
read_records
Create a DataChain from the provided records. This is a low-level function
that directly inserts records into the database. Unlike convenience functions
like read_values() or read_csv(), you have to provide the schema and records
explicitly.
Compare it with read_values() which infers schema automatically and is using
higher-level abstractions which makes it less efficient. E.g. read_values() cannot
handle large datasets efficiently since it needs to load all data into memory.
Parameters:
-
to_insert(dict | Iterable[dict] | None) –records to insert (empty list / None to create an empty chain). Can be a list, iterator, or generator. Iterators are processed lazily without loading all records into memory at once.
-
schema(dict[str, DataType]) –describes chain signals and their corresponding types.
Example
Notes
This call blocks until all records are inserted, but iterators are processed in batches to avoid loading all data into memory at once.
Source code in datachain/lib/dc/records.py
read_storage
Get data from storage(s) as a list of file with all file attributes. It returns the chain itself as usual.
Parameters:
-
uri(str | PathLike[str] | list[str] | list[PathLike[str]]) –Storage path(s) or URI(s). Can be a local path or start with a storage prefix like
s3://,gs://,az://,hf://or "file:///". Supports glob patterns: -*: wildcard -**: recursive wildcard -?: single character -{a,b}: brace expansion list -{1..9}: brace numeric or alphabetic range -
type(FileType, default:'binary') –read file as "binary", "text", or "image" data. Default is "binary".
-
recursive(bool | None, default:True) –search recursively for the given path.
-
column(str, default:'file') –Column name that will contain File objects. Default is "file".
-
update(bool, default:False) –force storage reindexing. Default is False.
-
anon(bool | None, default:None) –If True, we will treat cloud bucket as public one.
-
versions(bool, default:True) –If False, list only current objects, without versions.
-
client_config(dict | None, default:None) –Optional client configuration for the storage client.
-
delta(bool | None, default:False) –If True, only process new or changed files instead of reprocessing everything. This saves time by skipping files that were already processed in previous versions. The optimization is working when a new version of the dataset is created. Default is False.
-
delta_on(str | Sequence[str] | None, default:('file.path', 'file.etag', 'file.version')) –Field(s) that uniquely identify each record in the source data. Used to detect which records are new or changed. Default is ("file.path", "file.etag", "file.version").
-
delta_result_on(str | Sequence[str] | None, default:None) –Field(s) in the result dataset that match
delta_onfields. Only needed if you rename the identifying fields during processing. Default is None. -
delta_compare(str | Sequence[str] | None, default:None) –Field(s) used to detect if a record has changed. If not specified, all fields except
delta_onfields are used. Default is None. -
delta_retry(bool | str | None, default:None) –Controls retry behavior for failed records: - String (field name): Reprocess records where this field is not empty (error mode) - True: Reprocess records missing from the result dataset (missing mode) - None: No retry processing (default)
-
delta_unsafe(bool, default:False) –Allow restricted ops in delta: merge, union, subtract, diff, file_diff, agg, group_by, distinct. When multiple delta sources participate in one composed query, this must be enabled on every participating delta source. Caller must ensure datasets are consistent and not partially updated.
Returns:
-
DataChain(DataChain) –A DataChain object containing the file information.
Examples:
Simple call from s3:
Match all .json files recursively using glob pattern
Match image file extensions for directories with pattern
By ranges in filenames:
Multiple URIs:
Current objects only, without the history of a versioned bucket:
With AWS S3-compatible storage:
Source code in datachain/lib/dc/storage.py
read_zarr
Generate a chain with one row per Zarr store.
Unlike :func:read_storage, which emits one row per physical object, this
reader collapses every object under a store root into a single
:class:~datachain.lib.zarr.ZarrStore row. Stores are discovered using the
standard *.zarr naming convention.
Parameters:
-
path(str | PathLike[str] | list[str] | list[PathLike[str]]) –Storage path(s) or URI(s). Can be a local path or start with a storage prefix like
s3://,gs://,az://orfile://. Supports glob patterns. -
column(str, default:'zarr') –Created column name. Defaults to
"zarr". -
session(Session | None, default:None) –Session to use for the chain.
-
settings(dict | None, default:None) –Settings to use for the chain.
-
in_memory(bool, default:False) –If True, use an in-memory database.
Example
Source code in datachain/lib/dc/zarr.py
read_values
Generate chain from list of values.
Example
Source code in datachain/lib/dc/values.py
read_database
Read the results of a SQL query into a DataChain.
Parameters:
-
query(str | Executable) –The SQL query to execute. Can be a raw SQL string or a SQLAlchemy
Executableobject. -
connection(ConnectionType) –SQLAlchemy connectable, str, or a sqlite3 connection Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported. The user is responsible for engine disposal and connection closure for the SQLAlchemy connectable; str connections are closed automatically.
-
params(Sequence[Mapping[str, Any]] | Mapping[str, Any] | None, default:None) –Parameters to pass to execute method.
-
output(dict[str, DataType] | None, default:None) –A dictionary mapping column names to types, used to override the schema inferred from the query results.
-
session(Session | None, default:None) –Session to use for the chain.
-
settings(dict | None, default:None) –Settings to use for the chain.
-
in_memory(bool, default:False) –If True, creates an in-memory session. Defaults to False.
-
infer_schema_length(int | None, default:100) –The maximum number of rows to scan for inferring schema. If set to
None, the full data may be scanned. The rows used for schema inference are stored in memory, so large values can lead to high memory usage. Only applies if theoutputparameter is not set for the given column.
Examples:
Reading from a SQL query against a user-supplied connection:
Load data from a SQLAlchemy driver/engine:
Load data from a parameterized SQLAlchemy query:
Notes
- This function works with a variety of databases — including, but not limited to, SQLite, DuckDB, PostgreSQL, and Snowflake, provided the appropriate driver is installed.
- This call is blocking, and will execute the query and return once the results are saved.
Source code in datachain/lib/dc/database.py
datasets
Generate chain with list of registered datasets.
Parameters:
-
session(Session | None, default:None) –Optional session instance. If not provided, uses default session.
-
settings(dict | None, default:None) –Optional dictionary of settings to configure the chain.
-
in_memory(bool, default:False) –If True, creates an in-memory session. Defaults to False.
-
column(str | None, default:None) –Name of the output column in the chain. Defaults to None which means no top level column will be created.
-
include_listing(bool, default:False) –If True, includes listing datasets. Defaults to False.
-
studio(bool, default:False) –If True, returns datasets from Studio only, otherwise returns all local datasets. Defaults to False.
-
attrs(list[str] | None, default:None) –Optional list of attributes to filter datasets on. It can be just attribute without value e.g "NLP", or attribute with value e.g "location=US". Attribute with value can also accept "" to target all that have specific name e.g "location="
-
include_removed(bool, default:False) –If True, also lists REMOVING and REMOVED versions. Defaults to False.
Returns:
-
DataChain(DataChain) –A new DataChain instance containing dataset information.
Example
Source code in datachain/lib/dc/datasets.py
delete_dataset
Removes specific dataset version or all dataset versions, depending on a force flag.
The rows table is dropped but the version metadata is kept so the semver stays reserved and dependents can still resolve lineage.
Parameters:
-
name(str) –The dataset name, which can be a fully qualified name including the namespace and project. Alternatively, it can be a regular name, in which case the explicitly defined namespace and project will be used if they are set; otherwise, default values will be applied.
-
namespace(str | None, default:None) –optional name of namespace in which dataset to delete is created
-
project(str | None, default:None) –optional name of project in which dataset to delete is created
-
version(str | None, default:None) –Optional dataset version
-
force(bool | None, default:False) –If true, all datasets versions will be removed. Defaults to False.
-
studio(bool | None, default:False) –If True, removes dataset from Studio only, otherwise removes local dataset. Defaults to False.
-
session(Session | None, default:None) –Optional session instance. If not provided, uses default session.
-
in_memory(bool, default:False) –If True, creates an in-memory session. Defaults to False.
Returns: None
Example
Source code in datachain/lib/dc/datasets.py
move_dataset
Moves an entire dataset between namespaces and projects.
Parameters:
-
src(str) –The source dataset name. This can be a fully qualified name that includes the namespace and project, or a regular name. If a regular name is used, default values will be applied. The source dataset will no longer exist after the move.
-
dest(str) –The destination dataset name. This can also be a fully qualified name with a namespace and project, or just a regular name (default values will be used in that case). The original dataset will be moved here.
-
session(Session | None, default:None) –An optional session instance. If not provided, the default session will be used.
-
in_memory(bool, default:False) –If True, creates an in-memory session. Defaults to False.
Returns:
-
None–None
Examples:
Source code in datachain/lib/dc/datasets.py
delete_namespace
Removes a namespace by name.
Raises:
-
NamespaceNotFoundError–If the namespace does not exist.
-
NamespaceDeleteNotAllowedError–If the namespace is non-empty, is the default namespace, or is a system namespace, as these cannot be removed.
Parameters:
-
name(str) –The name of the namespace.
-
session(Session | None, default:None) –Session to use for getting project.
Example
Source code in datachain/lib/namespaces.py
is_studio
Check if the runtime environment is Studio (not local).
Source code in datachain/lib/dc/utils.py
is_local
Check if the runtime environment is local (not Studio).
Source code in datachain/lib/dc/utils.py
Column
Bases: ColumnClause
Source code in datachain/query/schema.py
glob
Search for matches using glob pattern matching.
Source code in datachain/query/schema.py
regexp
Search for matches using regexp pattern matching.
Source code in datachain/query/schema.py
ColumnExpr
A column expression - either a Column reference
like C("file.size") or any arithmetic or comparison expression built from columns.
DataChainSchema
Dict-like public view of a DataChain schema.
Top-level schema fields are available through the standard dict API.
Use :meth:flatten for leaf columns and :meth:to_string for the printable
tree format.
Source code in datachain/lib/dc/datachain.py
__str__
Return the printable schema tree.
Source code in datachain/lib/dc/datachain.py
flatten
Return flattened leaf column names and their types.
Parameters:
-
include_hidden(bool, default:True) –Whether to include hidden fields from complex signals.
Source code in datachain/lib/dc/datachain.py
DataChain
DataChain - a data structure for batch data processing and evaluation.
It represents a sequence of data manipulation steps such as reading data from storages, running AI or LLM models or calling external services API to validate or enrich data.
Data in DataChain is presented as Python classes with arbitrary set of fields,
including nested classes. The data classes have to inherit from DataModel class.
The supported set of field types include: majority of the type supported by the
underlyind library Pydantic.
See Also
read_storage("s3://my-bucket/my-dir/") - reading unstructured
data files from storages such as S3, gs or Azure ADLS.
DataChain.save("name") - saving to a dataset.
read_dataset("name") - reading from a dataset.
read_values(fib=[1, 2, 3, 5, 8]) - generating from values.
read_pandas(pd.DataFrame(...)) - generating from pandas.
read_json("file.json") - generating from json.
read_csv("file.csv") - generating from csv.
read_parquet("file.parquet") - generating from parquet.
Example
Source code in datachain/lib/dc/datachain.py
dataset
property
Underlying dataset, if there is one.
delta
property
Return True if this chain is running in "delta" update mode.
delta_unsafe
property
Returns True if the chain runs in unsafe "delta" update mode.
empty
property
Return True if the chain has zero rows.
job
property
Get the job for this chain.
Returns the existing job if running in SaaS, or creates a new one if running locally.
name
property
Name of the underlying dataset, if there is one.
namespace_name
property
Current namespace name in which the chain is running.
project_name
property
Current project name in which the chain is running.
schema
property
Get a dict-like schema view of the chain.
The returned object maps top-level signal names to Python types and can also produce leaf-column views:
session
property
Session of the chain.
version
property
Version of the underlying dataset, if there is one.
__iter__
Make DataChain objects iterable.
Yields:
-
tuple[DataValue, ...]–Yields tuples of all column values for each row.
Example
Source code in datachain/lib/dc/datachain.py
__or__
Return self.union(other).
Source code in datachain/lib/dc/datachain.py
__repr__
Return a string representation of the chain.
Source code in datachain/lib/dc/datachain.py
agg
Aggregate rows using partition_by statement and apply a function to the
groups of aggregated rows. The function needs to return new objects for each
group of the new rows. It returns a chain itself with new signals.
Input-output relationship: N:M
This method bears similarity to gen() and map(), employing a comparable set
of parameters, yet differs in two crucial aspects:
- The
partition_byparameter: This specifies the column name or a list of column names that determine the grouping criteria for aggregation. - Group-based UDF function input: Instead of individual rows, the function
receives a list of all rows within each group defined by
partition_by.
If partition_by is not set or is an empty list, all rows will be placed
into a single group.
Parameters:
-
func(Callable | None, default:None) –Function applied to each group of rows.
-
partition_by(PartitionByType | None, default:None) –Column name(s) to group by. If None, all rows go into one group.
-
params(str | Sequence[str] | None, default:None) –List of column names used as input for the function. Default is taken from function signature.
-
output(OutputType, default:None) –Dictionary defining new signals and their corresponding types. Default type is taken from function signature.
-
**signal_map(Callable, default:{}) –kwargs can be used to define
functogether with its return signal name in format ofagg(result_column=my_func).
Examples:
Basic aggregation with lambda function:
An alternative syntax, when you need to specify a more complex function:
Using complex signals for partitioning (File or any Pydantic BaseModel):
Aggregating all rows into a single group (when partition_by is not set):
Multiple partition columns:
Source code in datachain/lib/dc/datachain.py
apply
Apply any function to the chain.
Useful for reusing in a chain of operations.
Example
Source code in datachain/lib/dc/datachain.py
avg
Compute the average of a column.
Parameters:
-
col(str) –The column to compute the average for.
Returns:
-
StandardType–The average of the column values.
Example
Source code in datachain/lib/dc/datachain.py
c
Returns Column instance attached to the current chain.
Source code in datachain/lib/dc/datachain.py
chunk
Split a chain into smaller chunks for e.g. parallelization.
Parameters:
Example
Note
Bear in mind that index is 0-indexed but total isn't.
Use 0/3, 1/3 and 2/3, not 1/3, 2/3 and 3/3.
Source code in datachain/lib/dc/datachain.py
clone
Make a copy of the chain in a new table.
Source code in datachain/lib/dc/datachain.py
column
Returns Column instance with a type if name is found in current schema, otherwise raises an exception.
Source code in datachain/lib/dc/datachain.py
count
Return the number of rows in the chain.
Source code in datachain/lib/dc/datachain.py
diff
Calculate differences between two chains.
This method identifies records that are added, deleted, modified, or unchanged between two chains. It adds a status column with values: A=added, D=deleted, M=modified, S=same.
Parameters:
-
other(DataChain) –Chain to compare against.
-
on(str | Sequence[str]) –Column(s) to match records between chains.
-
right_on(str | Sequence[str] | None, default:None) –Column(s) in the other chain to match against. Defaults to
on. -
compare(str | Sequence[str] | None, default:None) –Column(s) to check for changes. If not specified,all columns are used.
-
right_compare(str | Sequence[str] | None, default:None) –Column(s) in the other chain to compare against. Defaults to values of
compare. -
added(bool, default:True) –Include records that exist in this chain but not in the other.
-
deleted(bool, default:True) –Include records that exist only in the other chain.
-
modified(bool, default:True) –Include records that exist in both but have different values.
-
same(bool, default:False) –Include records that are identical in both chains.
-
status_col(str, default:None) –Name for the status column showing differences.
Default behavior: By default, shows added, deleted, and modified records, but excludes unchanged records (same=False). Status column is not created.
Example
Source code in datachain/lib/dc/datachain.py
distinct
Removes duplicate rows based on uniqueness of some input column(s) i.e if rows are found with the same value of input column(s), only one row is left in the result set.
Example
Source code in datachain/lib/dc/datachain.py
exec
Execute the chain.
Source code in datachain/lib/dc/datachain.py
explode
Explodes a column containing JSON objects (dict or str DataChain type) into individual columns based on the schema of the JSON. Schema is inferred from the first row of the column.
Parameters:
-
col(str) –the name of the column containing JSON to be exploded.
-
model_name(str | None, default:None) –optional generated model name. By default generates the name automatically.
-
column(str | None, default:None) –optional generated column name. By default generates the name automatically.
-
schema_sample_size(int, default:1) –the number of rows to use for inferring the schema of the JSON (in case some fields are optional and it's not enough to analyze a single row).
Returns:
-
DataChain(DataChain) –A new DataChain instance with the new set of columns.
Source code in datachain/lib/dc/datachain.py
file_diff
Calculate differences between two chains containing files.
This method is specifically designed for file chains. It uses file source
and path to match files, and file version and etag to detect changes.
Parameters:
-
other(DataChain) –Chain to compare against.
-
on(str, default:'file') –File column name in this chain. Default is "file".
-
right_on(str | None, default:None) –File column name in the other chain. Defaults to
on. -
added(bool, default:True) –Include files that exist in this chain but not in the other.
-
deleted(bool, default:False) –Include files that exist only in the other chain.
-
modified(bool, default:True) –Include files that exist in both but have different versions/etags.
-
same(bool, default:False) –Include files that are identical in both chains.
-
status_col(str, default:None) –Name for the status column showing differences (A=added, D=deleted, M=modified, S=same).
Default behavior: By default, includes only new files (added=True and modified=True). This is useful for incremental processing.
Example
Source code in datachain/lib/dc/datachain.py
filter
Filter the chain according to conditions.
Example
Basic usage with built-in operators
Using glob to match patterns (case-sensitive, shell-style wildcards)
Using like / ilike for SQL pattern matching with % and _
wildcards. like is case-sensitive; ilike is case-insensitive:
Using regexp for regular-expression matching. Case-sensitive by
default; prepend the (?i) inline flag for case-insensitive:
Using in to match lists
Using datachain.func
Combining filters with "or"
Combining filters with "and"
Combining filters with "not"
Quick reference for column-level filter operators:
Source code in datachain/lib/dc/datachain.py
gen
Apply a function to each row to create new rows (with potentially new signals). The function needs to return a new objects for each of the new rows. It returns a chain itself with new signals.
Input-output relationship: 1:N
This method is similar to map(), uses the same list of parameters, but with
one key differences: It produces a sequence of rows for each input row (like
extracting multiple file records from a single tar file or bounding boxes from a
single image file).
Example
Source code in datachain/lib/dc/datachain.py
group_by
Group rows by specified set of signals and return new signals with aggregated values.
The supported functions
count(), sum(), avg(), min(), max(), any_value(), collect(), concat()
Example
Using complex signals:
Source code in datachain/lib/dc/datachain.py
limit
Return the first n rows of the chain.
If the chain is unordered, which rows are returned is undefined.
If the chain has less than n rows, the whole chain is returned.
Parameters:
-
n(int) –Number of rows to return.
Source code in datachain/lib/dc/datachain.py
map
Apply a function to each row to create new signals. The function should return a new object for each row. It returns a chain itself with new signals.
Input-output relationship: 1:1
Parameters:
-
func(Callable | None, default:None) –Function applied to each row.
-
params(str | Sequence[str] | None, default:None) –List of column names used as input for the function. Default is taken from function signature.
-
output(OutputType, default:None) –Dictionary defining new signals and their corresponding types. Default type is taken from function signature. Default can be also taken from kwargs - **signal_map (see below). If signal name is defined using signal_map (see below) only a single type value can be used.
-
**signal_map(Any, default:{}) –kwargs can be used to define
functogether with its return signal name in format ofmap(my_sign=my_func). This helps define signal names and functions in a nicer way.
Example
Using signal_map and single type in output:
Using func and output as a map:
Defining multiple signals in one call (single UDF stage, both functions run per row, no intermediate column materialized):
Source code in datachain/lib/dc/datachain.py
max
Compute the maximum of a column.
Parameters:
-
col(str) –The column to compute the maximum for.
Returns:
-
StandardType–The maximum value in the column.
Example
Source code in datachain/lib/dc/datachain.py
merge
Merge two chains based on the specified criteria.
Parameters:
-
right_ds(DataChain) –Chain to join with.
-
on(MergeColType | Sequence[MergeColType]) –Predicate ("column.name", C("column.name"), or Func) or list of Predicates to join on. If both chains have the same predicates then this predicate is enough for the join. Otherwise,
right_onparameter has to specify the predicates for the other chain. -
right_on(MergeColType | Sequence[MergeColType] | None, default:None) –Optional predicate or list of Predicates for the
right_dsto join. -
inner(bool, default:False) –Whether to run inner join or outer join.
-
full(bool, default:False) –Whether to run full outer join.
-
rname(str, default:'right_') –Name prefix for conflicting signal names.
Examples:
)
Source code in datachain/lib/dc/datachain.py
min
Compute the minimum of a column.
Parameters:
-
col(str) –The column to compute the minimum for.
Returns:
-
StandardType–The minimum value in the column.
Example
Source code in datachain/lib/dc/datachain.py
mutate
Create or modify signals based on existing signals.
This method is vectorized and more efficient compared to map(), and it does not extract or download any data from the internal database. However, it can only utilize predefined built-in functions and their combinations.
Supported functions
Numerical: +, -, *, /, rand(), avg(), count(), func(), greatest(), least(), max(), min(), sum() String: length(), split(), replace(), regexp_replace() Filename: name(), parent(), file_stem(), file_ext() Array: length(), sip_hash_64(), euclidean_distance(), cosine_distance() Window: row_number(), rank(), dense_rank(), first()
Example:
Window function example:
This method can be also used to rename signals. If the Column("name") provided
as value for the new signal - the old signal will be dropped. Otherwise a new
signal is created. Exception, if the old signal is nested one (e.g.
C("file.path")), it will be kept to keep the object intact.
Example:
Source code in datachain/lib/dc/datachain.py
offset
Return the results starting with the offset row.
If the chain is unordered, which rows are skipped in undefined.
If the chain has less than offset rows, the result is an empty chain.
Parameters:
-
offset(int) –Number of rows to skip.
Source code in datachain/lib/dc/datachain.py
order_by
Orders by specified set of columns.
Parameters:
-
descending(bool, default:False) –Whether to sort in descending order or not.
Example
Note
Order is not guaranteed when steps are added after an order_by statement.
I.e. when using read_dataset an order_by statement should be used if
the order of the records in the chain is important.
Using order_by directly before limit, to_list and similar methods
will give expected results.
See https://github.com/datachain-ai/datachain/issues/477
for further details.
Source code in datachain/lib/dc/datachain.py
parse_tabular
Generate chain from list of tabular files.
Parameters:
-
output(OutputType, default:None) –Dictionary or feature class defining column names and their corresponding types. List of column names is also accepted, in which case types will be inferred.
-
column(str, default:'') –Generated column name.
-
model_name(str, default:'') –Generated model name.
-
source(bool, default:True) –Whether to include info about the source file.
-
nrows(int | None, default:None) –Optional row limit.
-
kwargs(Any, default:{}) –Parameters to pass to pyarrow.dataset.dataset.
Example
Reading a json lines file:
Reading a filtered list of files as a dataset:
Source code in datachain/lib/dc/datachain.py
persist
Saves temporary chain that will be removed after the process ends. Temporary datasets are useful for optimization, for example when we have multiple chains starting with identical sub-chain. We can then persist that common chain and use it to calculate other chains, to avoid re-calculation every time. It returns the chain itself.
Source code in datachain/lib/dc/datachain.py
print_schema
Deprecated. Use print(chain.schema).
Source code in datachain/lib/dc/datachain.py
reset_settings
Reset all chain settings to default values.
Source code in datachain/lib/dc/datachain.py
results
Return all rows, optionally built via row_factory.
Source code in datachain/lib/dc/datachain.py
sample
Return a random sample from the chain.
Parameters:
-
n(int) –Number of samples to draw.
Note
Samples are not deterministic, and streamed/paginated queries or multiple workers will draw samples with replacement.
Source code in datachain/lib/dc/datachain.py
save
Save to a Dataset. It returns the chain itself.
Parameters:
-
name(str) –dataset name. This can be either a fully qualified name, including the namespace and project, or just a regular dataset name. In the latter case, the namespace and project will be taken from the settings (if specified) or from the default values otherwise.
-
version(str | None, default:None) –version of a dataset. If version is not specified and dataset already exists, version patch increment will happen e.g 1.2.1 -> 1.2.2.
-
description(str | None, default:None) –description of a dataset.
-
attrs(list[str] | None, default:None) –attributes of a dataset. They can be without value, e.g "NLP", or with a value, e.g "location=US".
-
update_version(str | None, default:'patch') –which part of the dataset version to automatically increase. Available values:
major,minororpatch. Default ispatch.
Source code in datachain/lib/dc/datachain.py
select
Select only a specified set of signals.
Nested selections (e.g. "file.path") preserve the parent object by
generating partial models rather than flattening into standalone fields.
Example
Source code in datachain/lib/dc/datachain.py
select_except
Select all signals except the specified ones.
Supports excluding nested fields (e.g. "file.path"), in which case a
partial model is generated for the parent signal.
Example
Source code in datachain/lib/dc/datachain.py
settings
Set chain execution parameters. Returns the chain itself, allowing method
chaining for subsequent operations. To restore all settings to their default
values, use reset_settings().
Parameters:
-
cache(bool | None, default:None) –Enable files caching to speed up subsequent accesses to the same files from the same or different chains. Defaults to False.
-
prefetch(bool | int | None, default:None) –Number of files to download in full ahead of the UDF, per process on each worker. Defaults to 2. Set to 0 or False for UDFs that read only part of a file, such as
get_info(). -
parallel(bool | int | None, default:None) –Number of processes to use for processing user-defined functions (UDFs) in parallel. If an integer is provided, it specifies the number of CPUs to use. If True, all available CPUs are used. Defaults to 1.
-
namespace(str | None, default:None) –Namespace to use for the chain by default.
-
project(str | None, default:None) –Project to use for the chain by default.
-
min_task_size(int | None, default:None) –Minimum number of rows per worker/process for parallel processing by UDFs. Defaults to 1.
-
batch_size(int | None, default:None) –Number of rows per insert by UDF to fine tune and balance speed and memory usage. This might be useful when processing large rows or when running into memory issues. Defaults to 2000.
-
ephemeral(bool | None, default:None) –If True, no persistent objects are created in the metastore (no jobs, checkpoints, or datasets). UDF execution still uses temporary tables. Calling .save() in ephemeral mode will raise an error.
-
llm(str | None, default:None) –Provider-prefixed model string (e.g.
"anthropic/claude-haiku-4-5") used bydatachain.llmoperations downstream in the chain. Inherited by everyllm.*call unless overridden by a per-callllm=. -
llm_params(LLMParams | None, default:None) –Extra parameters passed to the underlying model call (e.g. credentials,
api_base). Either a dict, or a no-argument callable returning a dict that is resolved per-worker (so secrets are never serialized into the task).
Example
Source code in datachain/lib/dc/datachain.py
setup
Setup variables to pass to UDF functions.
Use before running map/gen/agg to save an object and pass it as an argument to the UDF.
The value must be a callable (a lambda: <value> syntax can be used to quickly
create one) that returns the object to be passed to the UDF. It is evaluated
lazily when UDF is running, in case of multiple machines the callable is run on
a worker machine.
Example
Source code in datachain/lib/dc/datachain.py
show
Show a preview of the chain results.
Parameters:
-
limit(int, default:20) –How many rows to show.
-
flatten(bool, default:False) –Whether to use a multiindex or flatten column names.
-
transpose(bool, default:False) –Whether to transpose rows and columns.
-
truncate(bool, default:True) –Whether or not to truncate the contents of columns.
-
include_hidden(bool, default:False) –Whether to include hidden columns.
Source code in datachain/lib/dc/datachain.py
shuffle
Shuffle rows with a best-effort deterministic ordering.
This produces repeatable shuffles. Merge and union operations can lead to non-deterministic results. Use order by or save a dataset afterward to guarantee the same result.
Source code in datachain/lib/dc/datachain.py
similarity_search
Return rows whose column embedding is closest to query.
Shortcut for .mutate(...).order_by(...).limit(k).
Parameters:
-
column(str) –name of the embedding column on each row.
-
query(Sequence[float]) –reference embedding (the vector to compare against).
-
k(int | None, default:10) –how many closest rows to return.
Noneskips the limit and annotates/sorts every row. -
metric(str, default:'cosine') –"cosine","euclidean"or"l2"("l2"is an alias for"euclidean"). -
score_column(str | None, default:None) –name to store the distance under. If
None(default) the score is not included in the result.
Example
Source code in datachain/lib/dc/datachain.py
subtract
Remove rows that appear in another chain.
Parameters:
-
other(DataChain) –chain whose rows will be removed from
self -
on(str | Sequence[str] | None, default:None) –columns to consider for determining row equality in
self. If unspecified, defaults to all common columns betweenselfandother. -
right_on(str | Sequence[str] | None, default:None) –columns to consider for determining row equality in
other. If unspecified, defaults to the same values ason.
Source code in datachain/lib/dc/datachain.py
sum
Compute the sum of a column.
Parameters:
-
col(str) –The column to compute the sum for.
Returns:
-
StandardType–The sum of the column values.
Example
Source code in datachain/lib/dc/datachain.py
to_columnar_data_with_names
Returns column names and the results as an iterator that provides chunks, with each chunk containing a list of columns, where each column contains a list of the row values for that column in that chunk. Useful for columnar data formats, such as parquet or other OLAP databases.
Source code in datachain/lib/dc/datachain.py
to_csv
Save chain to a csv (comma-separated values) file and return the stored
File.
Parameters:
-
path(str | PathLike[str]) –Path to save the file. This supports local paths as well as remote paths, such as s3:// or hf:// with fsspec.
-
delimiter(str, default:',') –Delimiter to use for the resulting file.
-
fs_kwargs(dict[str, Any] | None, default:None) –Optional kwargs forwarded to the underlying fsspec filesystem when writing (e.g., s3://, gs://, hf://), fsspec-specific options are supported.
Returns:
-
File(File) –The stored file with refreshed metadata (version, etag, size).
Source code in datachain/lib/dc/datachain.py
to_database
Save chain to a database table using a given database connection.
This method exports all DataChain records to a database table, creating the table if it doesn't exist and appending data if it does. The table schema is automatically inferred from the DataChain's signal schema.
For PostgreSQL, tables are created in the schema specified by the connection's search_path (defaults to 'public'). Use URL parameters to target specific schemas.
Parameters:
-
table_name(str) –Name of the database table to create/write to.
-
connection(ConnectionType) –SQLAlchemy connectable, str, or a sqlite3 connection Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported. The user is responsible for engine disposal and connection closure for the SQLAlchemy connectable; str connections are closed automatically.
-
batch_size(int, default:DEFAULT_DATABASE_BATCH_SIZE) –Number of rows to insert per batch for optimal performance. Larger batches are faster but use more memory. Default: 10,000.
-
on_conflict(str | None, default:None) –Strategy for handling duplicate rows (requires table constraints): - None: Raise error (
sqlalchemy.exc.IntegrityError) on conflict (default) - "ignore": Skip duplicate rows silently - "update": Update existing rows with new values -
conflict_columns(list[str] | None, default:None) –List of column names that form a unique constraint for conflict resolution. Required when on_conflict='update' and using PostgreSQL.
-
column_mapping(dict[str, str | None] | None, default:None) –Optional mapping to rename or skip columns: - Dict mapping DataChain column names to database column names - Set values to None to skip columns entirely, or use
defaultdictto skip all columns except those specified.
Returns:
-
int(int) –Number of rows affected (inserted/updated). -1 if DB driver doesn't support telemetry.
Examples:
Basic usage with PostgreSQL:
Using SQLite with connection string:
Column mapping and renaming:
Handling conflicts (requires PRIMARY KEY or UNIQUE constraints):
Working with different databases:
PostgreSQL with schema support:
Source code in datachain/lib/dc/datachain.py
to_iter
Yields rows of values, optionally limited to the specified columns.
Parameters:
-
*cols(str | Column, default:()) –Limit to the specified columns. String names and plain
C("...")column references are supported. By default, all columns are selected.
Yields:
Example
Iterating over all rows:
DataChain is iterable and can be used in a for loop directly which is
equivalent to ds.to_iter():
Iterating over all rows with selected columns:
Iterating over a single column:
Source code in datachain/lib/dc/datachain.py
to_json
Save chain to a JSON file and return the stored File.
Parameters:
-
path(str | PathLike[str]) –Path to save the file. This supports local paths as well as remote paths, such as s3:// or hf:// with fsspec.
-
fs_kwargs(dict[str, Any] | None, default:None) –Optional kwargs forwarded to the underlying fsspec filesystem when writing (e.g., s3://, gs://, hf://), fsspec-specific options are supported.
-
include_outer_list(bool, default:True) –Sets whether to include an outer list for all rows. Setting this to True makes the file valid JSON, while False instead writes in the JSON lines format.
Returns:
-
File(File) –The stored file with refreshed metadata (version, etag, size).
Source code in datachain/lib/dc/datachain.py
to_jsonl
Save chain to a JSON lines file.
Parameters:
-
path(str | PathLike[str]) –Path to save the file. This supports local paths as well as remote paths, such as s3:// or hf:// with fsspec.
-
fs_kwargs(dict[str, Any] | None, default:None) –Optional kwargs forwarded to the underlying fsspec filesystem when writing (e.g., s3://, gs://, hf://), fsspec-specific options are supported.
Returns:
-
File(File) –The stored file with refreshed metadata (version, etag, size).
Source code in datachain/lib/dc/datachain.py
to_list
Returns a list of rows of values, optionally limited to the specified columns.
Parameters:
-
*cols(str | Column, default:()) –Limit to the specified columns. String names and plain
C("...")column references are supported. By default, all columns are selected.
Returns:
-
list[tuple[DataValue, ...]]–list[tuple[DataType, ...]]: Returns a list of tuples of items for each row.
Example
Getting all rows as a list:
Getting all rows with selected columns as a list:
Getting a single column as a list:
Source code in datachain/lib/dc/datachain.py
to_pandas
Return a pandas DataFrame from the chain.
Parameters:
-
flatten(bool, default:False) –Whether to use a multiindex or flatten column names.
-
include_hidden(bool, default:True) –Whether to include hidden columns.
-
as_object(bool, default:False) –Whether to emit a dataframe backed by Python objects rather than pandas-inferred dtypes.
Returns:
-
DataFrame–pd.DataFrame: A pandas DataFrame representation of the chain.
Source code in datachain/lib/dc/datachain.py
to_parquet
Save chain to parquet file with SignalSchema metadata.
Parameters:
-
path(str | PathLike[str] | BinaryIO) –Path or a file-like binary object to save the file. This supports local paths as well as remote paths, such as s3:// or hf:// with fsspec.
-
partition_cols(Sequence[str] | None, default:None) –Column names by which to partition the dataset.
-
chunk_size(int, default:DEFAULT_PARQUET_CHUNK_SIZE) –The chunk size of results to read and convert to columnar data, to avoid running out of memory.
-
fs_kwargs(dict[str, Any] | None, default:None) –Optional kwargs forwarded to the underlying fsspec filesystem when writing (e.g., s3://, gs://, hf://), fsspec-specific options are supported.
Source code in datachain/lib/dc/datachain.py
to_pytorch
Convert to pytorch dataset format.
Parameters:
-
transform(Transform, default:None) –Torchvision transforms to apply to the dataset.
-
tokenizer(Callable, default:None) –Tokenizer to use to tokenize text values.
-
tokenizer_kwargs(dict, default:None) –Additional kwargs to pass when calling tokenizer.
-
num_samples(int, default:0) –Number of random samples to draw for each epoch. This argument is ignored if
num_samples=0(the default). -
remove_prefetched(bool, default:False) –Whether to remove prefetched files after reading.
Example
Source code in datachain/lib/dc/datachain.py
to_records
Convert every row to a dictionary.
Source code in datachain/lib/dc/datachain.py
to_storage
Export files from a specified signal to a directory. Files can be exported to a local or cloud directory.
Parameters:
-
output(str | PathLike[str]) –Path to the target directory for exporting files.
-
signal(str, default:'file') –Name of the signal to export files from.
-
placement(ExportPlacement, default:'fullpath') –The method to use for naming exported files. The possible values are: "filename", "etag", "fullpath", "filepath", and "checksum". Example path translations for an object located at
s3://bucket/data/img.jpgand exported to./out:- "filename" ->
./out/img.jpg(no directories) - "filepath" ->
./out/data/img.jpg(relative path kept) - "fullpath" ->
./out/bucket/data/img.jpg(remote host kept) - "etag" ->
./out/<etag>.jpg(unique name via object digest)
Local sources behave like "filepath" for "fullpath" placement. Relative destinations such as "." or ".." and absolute paths are supported for every strategy.
- "filename" ->
-
link_type(Literal['copy', 'symlink'], default:'copy') –Method to use for exporting files. Falls back to
'copy'if symlinking fails. -
num_threads(int | None, default:EXPORT_FILES_MAX_THREADS) –number of threads to use for exporting files. By default, it uses 5 threads.
-
anon(bool | None, default:None) –If True, we will treat cloud bucket as a public one. Default behavior depends on the previous session configuration (e.g. happens in the initial
read_storage) and particular cloud storage client implementation (e.g. S3 fallbacks to anonymous access if no credentials were found). -
client_config(dict | None, default:None) –Optional configuration for the destination storage client
Example
Cross cloud transfer
Source code in datachain/lib/dc/datachain.py
to_values
Returns a flat list of values from a single column.
Parameters:
-
col(str | Column) –The column to extract values from. String names and plain
C("...")column references are supported.
Returns:
-
list[DataValue]–list[DataValue]: Returns a flat list of values from the specified column.
Example
Getting all values from a single column:
Getting all file sizes:
Source code in datachain/lib/dc/datachain.py
union
Return the set union of the two datasets.
Parameters:
-
other(Self) –chain whose rows will be added to
self.
Source code in datachain/lib/dc/datachain.py
DataChainError
Bases: Exception
Session
Session is a context that keeps track of temporary DataChain datasets for a proper cleanup. By default, a global session is created.
Temporary or ephemeral datasets are the ones created without specified name. They are useful for optimization purposes and should be automatically removed.
Temp dataset has specific name format
"session_"
The suffix is optional. Both s are auto-generated.
Temp dataset examples
session_myname_624b41_48e8b4 session_4b962d_2a5dff
Parameters:
name (str): The name of the session. Only latters and numbers are supported. It can be empty. catalog (Catalog): Catalog object.
Source code in datachain/query/session.py
get
classmethod
Creates a Session() object from a catalog.
Parameters:
-
session(Session, default:None) –Optional Session(). If not provided a new session will be created. It's needed mostly for simple API purposes.
-
catalog(Catalog, default:None) –Optional catalog. By default, a new catalog is created.
Source code in datachain/query/session.py
get_job
Return the current job if one exists, without creating a new one.
Checks the cached _CURRENT_JOB and DATACHAIN_JOB_ID env var.
Returns None if no job is found.
Source code in datachain/query/session.py
get_or_create_job
Get or create a Job for this process.
Returns:
-
Job(Job) –The active Job instance.
Behavior
- If a job already exists, it is returned.
- If in Studio without DATACHAIN_JOB_ID, raises an error.
- If
DATACHAIN_JOB_IDis set, the corresponding job is fetched. - Otherwise, a new job is created:
- Name = absolute path to the Python script.
- Query = empty string.
- Parent = last job with the same name, if available.
- Status = "running". Exit hooks are registered to finalize the job.
Note
Job is shared across all Session instances to ensure one job per process.