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.
Column
Bases: ColumnClause
Source code in datachain/query/schema.py
glob
read_csv
read_csv(
path: (
str
| PathLike[str]
| list[str]
| list[PathLike[str]]
),
delimiter: str | None = None,
header: bool = True,
output: OutputType = None,
column: str = "",
model_name: str = "",
source: bool = True,
nrows: int | None = None,
session: Session | None = None,
settings: dict | None = None,
column_types: dict[str, str | DataType] | None = None,
parse_options: (
dict[str, str | bool | Callable] | None
) = None,
**kwargs
) -> DataChain
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
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 |
|
read_dataset
read_dataset(
name: str,
namespace: str | None = None,
project: str | None = None,
version: str | int | None = None,
session: Session | None = None,
settings: dict | None = None,
delta: bool | None = False,
delta_on: str | Sequence[str] | None = (
"file.path",
"file.etag",
"file.version",
),
delta_result_on: str | Sequence[str] | None = None,
delta_compare: str | Sequence[str] | None = None,
delta_retry: bool | str | None = None,
delta_unsafe: bool = False,
update: bool = False,
) -> DataChain
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.
-
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_on
fields. 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_on
fields 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, agg, union, group_by, distinct.
Example
# Legacy integer version support (finds latest in major version)
chain = dc.read_dataset("my_cats", version=1) # Latest 1.x.x version
Source code in datachain/lib/dc/datasets.py
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 |
|
datasets
datasets(
session: Session | None = None,
settings: dict | None = None,
in_memory: bool = False,
column: str | None = None,
include_listing: bool = False,
studio: bool = False,
attrs: list[str] | None = None,
) -> DataChain
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="
Returns:
-
DataChain
(DataChain
) βA new DataChain instance containing dataset information.
Example
Source code in datachain/lib/dc/datasets.py
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 |
|
delete_dataset
delete_dataset(
name: str,
namespace: str | None = None,
project: str | None = None,
version: str | None = None,
force: bool | None = False,
studio: bool | None = False,
session: Session | None = None,
in_memory: bool = False,
) -> None
Removes specific dataset version or all dataset versions, depending on a force flag.
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
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 |
|
move_dataset
move_dataset(
src: str,
dest: str,
session: Session | None = None,
in_memory: bool = False,
) -> None
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.
Source code in datachain/lib/namespaces.py
read_hf
read_hf(
dataset: HFDatasetType,
*args: Any,
session: Session | None = None,
settings: dict | None = None,
column: str = "",
model_name: str = "",
limit: int = 0,
**kwargs: Any
) -> DataChain
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:
from datasets import load_dataset
ds = load_dataset("beans", split="train")
import datachain as dc
chain = dc.read_hf(ds)
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
read_json(
path: str | PathLike[str],
type: FileType = "text",
spec: DataType | None = None,
schema_from: str | None = "auto",
jmespath: str | None = None,
column: str | None = "",
model_name: str | None = None,
format: str | None = "json",
nrows: int | None = None,
**kwargs
) -> DataChain
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
listings
listings(
session: Session | None = None,
in_memory: bool = False,
column: str = "listing",
**kwargs
) -> DataChain
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).
Source code in datachain/lib/dc/listings.py
read_pandas
read_pandas(
df: DataFrame,
name: str = "",
session: Session | None = None,
settings: dict | None = None,
in_memory: bool = False,
column: str = "",
) -> DataChain
Generate chain from pandas data-frame.
Example
Source code in datachain/lib/dc/pandas.py
read_parquet
read_parquet(
path: (
str
| PathLike[str]
| list[str]
| list[PathLike[str]]
),
partitioning: Any = "hive",
output: dict[str, DataType] | None = None,
column: str = "",
model_name: str = "",
source: bool = True,
session: Session | None = None,
settings: dict | None = None,
**kwargs
) -> DataChain
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
read_records(
to_insert: dict | Iterable[dict] | None,
session: Session | None = None,
settings: dict | None = None,
in_memory: bool = False,
schema: dict[str, DataType] | None = None,
) -> DataChain
Create a DataChain from the provided records. This method can be used for programmatically generating a chain in contrast of reading data from storages or other sources.
Parameters:
-
to_insert
(dict | Iterable[dict] | None
) βrecords (or a single record) to insert. Each record is a dictionary of signals and their values.
-
schema
(dict[str, DataType] | None
, default:None
) βdescribes chain signals and their corresponding types
Notes
This call blocks until all records are inserted.
Source code in datachain/lib/dc/records.py
read_storage
read_storage(
uri: (
str
| PathLike[str]
| list[str]
| list[PathLike[str]]
),
*,
type: FileType = "binary",
session: Session | None = None,
settings: dict | None = None,
in_memory: bool = False,
recursive: bool | None = True,
column: str = "file",
update: bool = False,
anon: bool | None = None,
delta: bool | None = False,
delta_on: str | Sequence[str] | None = (
"file.path",
"file.etag",
"file.version",
),
delta_result_on: str | Sequence[str] | None = None,
delta_compare: str | Sequence[str] | None = None,
delta_retry: bool | str | None = None,
delta_unsafe: bool = False,
client_config: dict | None = None
) -> DataChain
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.
-
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_on
fields. 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_on
fields 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, agg, union, group_by, distinct. 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:
With AWS S3-compatible storage:
dc.read_storage(
"s3://my-bucket/my-dir",
client_config = {"aws_endpoint_url": "<minio-endpoint-url>"}
)
Source code in datachain/lib/dc/storage.py
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 |
|
read_values
read_values(
ds_name: str = "",
session: Session | None = None,
settings: dict | None = None,
in_memory: bool = False,
output: OutputType = None,
column: str = "",
**fr_map
) -> DataChain
Generate chain from list of values.
Source code in datachain/lib/dc/values.py
read_database
read_database(
query: str | Executable,
connection: ConnectionType,
params: (
Sequence[Mapping[str, Any]]
| Mapping[str, Any]
| None
) = None,
*,
output: dict[str, DataType] | None = None,
session: Session | None = None,
settings: dict | None = None,
in_memory: bool = False,
infer_schema_length: int | None = 100
) -> DataChain
Read the results of a SQL query into a DataChain, using a given database connection.
Parameters:
-
query
(str | Executable
) βThe SQL query to execute. Can be a raw SQL string or a SQLAlchemy
Executable
object. -
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 theoutput
parameter is not set for the given column.
Examples:
Reading from a SQL query against a user-supplied connection:
query = "SELECT key, value FROM tbl"
chain = dc.read_database(query, connection, output={"value": float})
Load data from a SQLAlchemy driver/engine:
from sqlalchemy import create_engine
engine = create_engine("postgresql+psycopg://myuser:mypassword@localhost:5432/mydb")
chain = dc.read_database("select * from tbl", engine)
Load data from a parameterized SQLAlchemy query:
query = "SELECT key, value FROM tbl WHERE value > :value"
dc.read_database(query, engine, params={"value": 50})
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
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 |
|
ConnectionType
module-attribute
ConnectionType = (
str
| URL
| Connectable
| Engine
| Connection
| Session
| Connection
)
DataChain
DataChain(
query: DatasetQuery,
settings: Settings,
signal_schema: SignalSchema,
setup: dict | None = None,
_sys: bool = False,
)
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
import os
from mistralai.client import MistralClient
from mistralai.models.chat_completion import ChatMessage
import datachain as dc
PROMPT = (
"Was this bot dialog successful? "
"Describe the 'result' as 'Yes' or 'No' in a short JSON"
)
model = "mistral-large-latest"
api_key = os.environ["MISTRAL_API_KEY"]
chain = (
dc.read_storage("gs://datachain-demo/chatbot-KiT/")
.limit(5)
.settings(cache=True, parallel=5)
.map(
mistral_response=lambda file: MistralClient(api_key=api_key)
.chat(
model=model,
response_format={"type": "json_object"},
messages=[
ChatMessage(role="user", content=f"{PROMPT}: {file.read()}")
],
)
.choices[0]
.message.content,
)
.persist()
)
try:
print(chain.select("mistral_response").results())
except Exception as e:
print(f"do you have the right Mistral API key? {e}")
Source code in datachain/lib/dc/datachain.py
__iter__
Make DataChain objects iterable.
Yields:
-
tuple[DataValue, ...]
βYields tuples of all column values for each row.
Source code in datachain/lib/dc/datachain.py
__or__
__repr__
__repr__() -> str
Return a string representation of the chain.
Source code in datachain/lib/dc/datachain.py
agg
agg(
func: Callable | None = None,
partition_by: PartitionByType | None = None,
params: str | Sequence[str] | None = None,
output: OutputType = None,
**signal_map: Callable
) -> Self
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_by
parameter: 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
func
together with its return signal name in format ofagg(result_column=my_func)
.
Examples:
Basic aggregation with lambda function:
chain = chain.agg(
total=lambda category, amount: [sum(amount)],
output=float,
partition_by="category",
)
chain.save("new_dataset")
An alternative syntax, when you need to specify a more complex function:
# It automatically resolves which columns to pass to the function
# by looking at the function signature.
def agg_sum(
file: list[File], amount: list[float]
) -> Iterator[tuple[File, float]]:
yield file[0], sum(amount)
chain = chain.agg(
agg_sum,
output={"file": File, "total": float},
# Alternative syntax is to use `C` (short for Column) to specify
# a column name or a nested column, e.g. C("file.path").
partition_by=C("category"),
)
chain.save("new_dataset")
Using complex signals for partitioning (File
or any Pydantic BaseModel
):
def my_agg(files: list[File]) -> Iterator[tuple[File, int]]:
yield files[0], sum(f.size for f in files)
chain = chain.agg(
my_agg,
params=("file",),
output={"file": File, "total": int},
partition_by="file", # Column referring to all sub-columns of File
)
chain.save("new_dataset")
Aggregating all rows into a single group (when partition_by
is not set):
chain = chain.agg(
total_size=lambda file, size: [sum(size)],
output=int,
# No partition_by specified - all rows go into one group
)
chain.save("new_dataset")
Multiple partition columns:
chain = chain.agg(
total=lambda category, subcategory, amount: [sum(amount)],
output=float,
partition_by=["category", "subcategory"],
)
chain.save("new_dataset")
Source code in datachain/lib/dc/datachain.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 |
|
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
avg(col: str) -> StandardType
Compute the average of a column.
Parameters:
-
col
(str
) βThe column to compute the average for.
Returns:
-
StandardType
βThe average of the column values.
Source code in datachain/lib/dc/datachain.py
batch_map
batch_map(
func: Callable | None = None,
params: str | Sequence[str] | None = None,
output: OutputType = None,
batch: int = 1000,
**signal_map
) -> Self
This is a batch version of map()
.
Input-output relationship: N:N
It accepts the same parameters plus an additional parameter:
batch: Size of each batch passed to `func`. Defaults to 1000.
Example
.. deprecated:: 0.29.0
This method is deprecated and will be removed in a future version.
Use agg()
instead, which provides the similar functionality.
Source code in datachain/lib/dc/datachain.py
c
Returns Column instance attached to the current chain.
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
collect
Deprecated. Use to_iter
method instead.
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
count() -> int
diff
diff(
other: DataChain,
on: str | Sequence[str],
right_on: str | Sequence[str] | None = None,
compare: str | Sequence[str] | None = None,
right_compare: str | Sequence[str] | None = None,
added: bool = True,
deleted: bool = True,
modified: bool = True,
same: bool = False,
status_col: str | None = None,
) -> DataChain
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
1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 |
|
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.
Source code in datachain/lib/dc/datachain.py
exec
explode
explode(
col: str,
model_name: str | None = None,
column: str | None = None,
schema_sample_size: int = 1,
) -> DataChain
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
file_diff(
other: DataChain,
on: str = "file",
right_on: str | None = None,
added: bool = True,
modified: bool = True,
deleted: bool = False,
same: bool = False,
status_col: str | None = None,
) -> DataChain
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
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 |
|
filter
filter(*args: Any) -> Self
Filter the chain according to conditions.
Example
Basic usage with built-in operators
Using glob to match patterns
Using in to match lists
Using datachain.func
Combining filters with "or"
Combining filters with "and"
Combining filters with "not"
Source code in datachain/lib/dc/datachain.py
2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 |
|
gen
gen(
func: Callable | Generator | None = None,
params: str | Sequence[str] | None = None,
output: OutputType = None,
**signal_map
) -> Self
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_by(
*,
partition_by: (
str | Func | Sequence[str | Func] | None
) = None,
**kwargs: Func
) -> Self
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
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 |
|
hash
hash() -> str
Calculates SHA hash of this chain. Hash calculation is fast and consistent. It takes into account all the steps added to the chain and their inputs. Order of the steps is important.
Source code in datachain/lib/dc/datachain.py
limit
limit(n: int) -> Self
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
map(
func: Callable | None = None,
params: str | Sequence[str] | None = None,
output: OutputType = None,
**signal_map: Any
) -> Self
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
func
together 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:
Source code in datachain/lib/dc/datachain.py
max
max(col: str) -> StandardType
Compute the maximum of a column.
Parameters:
-
col
(str
) βThe column to compute the maximum for.
Returns:
-
StandardType
βThe maximum value in the column.
Source code in datachain/lib/dc/datachain.py
merge
merge(
right_ds: DataChain,
on: MergeColType | Sequence[MergeColType],
right_on: (
MergeColType | Sequence[MergeColType] | None
) = None,
inner=False,
full=False,
rname="right_",
) -> Self
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_on
parameter 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_ds
to 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:
imgs.merge(captions,
on=func.path.file_stem(imgs.c("file.path")),
right_on=func.path.file_stem(captions.c("file.path"))
)
Source code in datachain/lib/dc/datachain.py
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 |
|
min
min(col: str) -> StandardType
Compute the minimum of a column.
Parameters:
-
col
(str
) βThe column to compute the minimum for.
Returns:
-
StandardType
βThe minimum value in the column.
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:
dc.mutate(
area=Column("image.height") * Column("image.width"),
extension=file_ext(Column("file.path")),
dist=cosine_distance(embedding_text, embedding_image)
)
Window function example:
window = func.window(partition_by="file.parent", order_by="file.size")
dc.mutate(
row_number=func.row_number().over(window),
)
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
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 |
|
offset
offset(offset: int) -> Self
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
order_by(*args, descending: bool = False) -> Self
Orders by specified set of columns.
Parameters:
-
descending
(bool
, default:False
) βWhether to sort in descending order or not.
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/iterative/datachain/issues/477 for further details.
Source code in datachain/lib/dc/datachain.py
parse_tabular
parse_tabular(
output: OutputType = None,
column: str = "",
model_name: str = "",
source: bool = True,
nrows: int | None = None,
**kwargs: Any
) -> Self
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:
import datachain as dc
chain = dc.read_storage("s3://mybucket/file.jsonl")
chain = chain.parse_tabular(format="json")
Reading a filtered list of files as a dataset:
Source code in datachain/lib/dc/datachain.py
2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 |
|
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
print_schema(file: IO | None = None) -> None
reset_settings
sample
sample(n: int) -> Self
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(
name: str,
version: str | None = None,
description: str | None = None,
attrs: list[str] | None = None,
update_version: str | None = "patch",
**kwargs
) -> DataChain
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
,minor
orpatch
. Default ispatch
.
Source code in datachain/lib/dc/datachain.py
select
Select only a specified set of signals.
Source code in datachain/lib/dc/datachain.py
select_except
select_except(*args: str) -> Self
Select all the signals expect the specified signals.
Source code in datachain/lib/dc/datachain.py
settings
settings(
cache: bool | None = None,
prefetch: bool | int | None = None,
parallel: bool | int | None = None,
workers: int | None = None,
namespace: str | None = None,
project: str | None = None,
min_task_size: int | None = None,
batch_size: int | None = None,
sys: bool | None = None,
) -> Self
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
) βEnable prefetching of files. This will download files in advance in parallel. If an integer is provided, it specifies the number of files to prefetch concurrently for each process on each worker. Defaults to 2. Set to 0 or False to disable prefetching.
-
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.
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
import anthropic
from anthropic.types import Message
import datachain as dc
(
dc.read_storage(DATA, type="text")
.settings(parallel=4, cache=True)
# Setup Anthropic client and pass it to the UDF below automatically
# The value is callable (see the note above)
.setup(client=lambda: anthropic.Anthropic(api_key=API_KEY))
.map(
claude=lambda client, file: client.messages.create(
model=MODEL,
system=PROMPT,
messages=[{"role": "user", "content": file.get_value()}],
),
output=Message,
)
)
Source code in datachain/lib/dc/datachain.py
show
show(
limit: int = 20,
flatten: bool = False,
transpose: bool = False,
truncate: bool = True,
include_hidden: bool = False,
) -> None
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
subtract
subtract(
other: DataChain,
on: str | Sequence[str] | None = None,
right_on: str | Sequence[str] | None = None,
) -> Self
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 betweenself
andother
. -
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
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 |
|
sum
sum(col: str) -> StandardType
Compute the sum of a column.
Parameters:
-
col
(str
) βThe column to compute the sum for.
Returns:
-
StandardType
βThe sum of the column values.
Source code in datachain/lib/dc/datachain.py
to_columnar_data_with_names
to_columnar_data_with_names(
chunk_size: int = DEFAULT_PARQUET_CHUNK_SIZE,
) -> tuple[list[str], Iterator[list[list[Any]]]]
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
to_csv(
path: str | PathLike[str],
delimiter: str = ",",
fs_kwargs: dict[str, Any] | None = None,
**kwargs
) -> None
Save chain to a csv (comma-separated values) 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 to pass to the fsspec filesystem, used only for write, for fsspec-type URLs, such as s3:// or hf:// when provided as the destination path.
Source code in datachain/lib/dc/datachain.py
to_database
to_database(
table_name: str,
connection: ConnectionType,
*,
batch_size: int = DEFAULT_DATABASE_BATCH_SIZE,
on_conflict: str | None = None,
conflict_columns: list[str] | None = None,
column_mapping: dict[str, str | None] | None = None
) -> int
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
defaultdict
to 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:
import datachain as dc
rows_affected = (dc
.read_storage("s3://my-bucket/")
.to_database("files_table", "postgresql://user:pass@localhost/mydb")
)
print(f"Inserted/updated {rows_affected} rows")
Using SQLite with connection string:
rows_affected = chain.to_database("my_table", "sqlite:///data.db")
print(f"Affected {rows_affected} rows")
Column mapping and renaming:
mapping = {
"user.id": "id",
"user.name": "name",
"user.password": None # Skip this column
}
chain.to_database("users", engine, column_mapping=mapping)
Handling conflicts (requires PRIMARY KEY or UNIQUE constraints):
# Skip duplicates
chain.to_database("my_table", engine, on_conflict="ignore")
# Update existing records
chain.to_database(
"my_table", engine, on_conflict="update", conflict_columns=["id"]
)
Working with different databases:
# MySQL
mysql_engine = sa.create_engine("mysql+pymysql://user:pass@host/db")
chain.to_database("mysql_table", mysql_engine)
# SQLite in-memory
chain.to_database("temp_table", "sqlite:///:memory:")
PostgreSQL with schema support:
pg_url = "postgresql://user:pass@host/db?options=-c search_path=analytics"
chain.to_database("processed_data", pg_url)
Source code in datachain/lib/dc/datachain.py
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 |
|
to_iter
Yields rows of values, optionally limited to the specified columns.
Parameters:
-
*cols
(str
, default:()
) βLimit to the specified columns. 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
to_json(
path: str | PathLike[str],
fs_kwargs: dict[str, Any] | None = None,
include_outer_list: bool = True,
) -> None
Save chain to a JSON 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 to pass to the fsspec filesystem, used only for write, for fsspec-type URLs, such as s3:// or hf:// when provided as the destination path.
-
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.
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 to pass to the fsspec filesystem, used only for write, for fsspec-type URLs, such as s3:// or hf:// when provided as the destination path.
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
, default:()
) βLimit to the specified columns. 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
to_pandas(
flatten: bool = False,
include_hidden: bool = True,
as_object: bool = False,
) -> DataFrame
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
to_parquet(
path: str | PathLike[str] | BinaryIO,
partition_cols: Sequence[str] | None = None,
chunk_size: int = DEFAULT_PARQUET_CHUNK_SIZE,
fs_kwargs: dict[str, Any] | None = None,
**kwargs
) -> None
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 to pass to the fsspec filesystem, used only for write, for fsspec-type URLs, such as s3:// or hf:// when provided as the destination path.
Source code in datachain/lib/dc/datachain.py
2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 |
|
to_pytorch
to_pytorch(
transform=None,
tokenizer=None,
tokenizer_kwargs=None,
num_samples=0,
remove_prefetched: bool = False,
)
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
to_storage(
output: str | PathLike[str],
signal: str = "file",
placement: ExportPlacement = "fullpath",
link_type: Literal["copy", "symlink"] = "copy",
num_threads: int | None = EXPORT_FILES_MAX_THREADS,
anon: bool | None = None,
client_config: dict | None = None,
) -> None
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", and "checksum".
-
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
2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 |
|
to_values
Returns a flat list of values from a single column.
Parameters:
-
col
(str
) βThe name of the column to extract values from.
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(
name="",
catalog: Catalog | None = None,
client_config: dict | None = None,
in_memory: bool = False,
)
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
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
get(
session: Session | None = None,
catalog: Catalog | None = None,
client_config: dict | None = None,
in_memory: bool = False,
) -> Session
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.