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: Union[
str, PathLike[str], list[str], list[PathLike[str]]
],
delimiter: Optional[str] = None,
header: bool = True,
output: OutputType = None,
column: str = "",
model_name: str = "",
source: bool = True,
nrows: Optional[int] = None,
session: Optional[Session] = None,
settings: Optional[dict] = None,
column_types: Optional[
dict[str, Union[str, DataType]]
] = None,
parse_options: Optional[
dict[str, Union[str, Union[bool, Callable]]]
] = None,
**kwargs
) -> DataChain
Generate chain from csv files.
Parameters:
-
path
(Union[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
(Optional[str]
, 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
(Optional[int]
, default:None
) βOptional row limit.
-
session
(Optional[Session]
, default:None
) βSession to use for the chain.
-
settings
(Optional[dict]
, default:None
) βSettings to use for the chain.
-
column_types
(Optional[dict[str, Union[str, DataType]]]
, 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
(Optional[dict[str, Union[str, Union[bool, Callable]]]]
, 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: Optional[str] = None,
project: Optional[str] = None,
version: Optional[Union[str, int]] = None,
session: Optional[Session] = None,
settings: Optional[dict] = None,
delta: Optional[bool] = False,
delta_on: Optional[Union[str, Sequence[str]]] = (
"file.path",
"file.etag",
"file.version",
),
delta_result_on: Optional[
Union[str, Sequence[str]]
] = None,
delta_compare: Optional[
Union[str, Sequence[str]]
] = None,
delta_retry: Optional[Union[bool, str]] = 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
(Optional[str]
, default:None
) βoptional name of namespace in which dataset to read is created
-
project
(Optional[str]
, default:None
) βoptional name of project in which dataset to read is created
-
version
(Optional[Union[str, int]]
, 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
(Optional[Session]
, default:None
) βSession to use for the chain.
-
settings
(Optional[dict]
, default:None
) βSettings to use for the chain.
-
delta
(Optional[bool]
, 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
(Optional[Union[str, Sequence[str]]]
, 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
(Optional[Union[str, Sequence[str]]]
, 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
(Optional[Union[str, Sequence[str]]]
, 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
(Optional[Union[bool, str]]
, 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: Optional[Session] = None,
settings: Optional[dict] = None,
in_memory: bool = False,
column: Optional[str] = None,
include_listing: bool = False,
studio: bool = False,
attrs: Optional[list[str]] = None,
) -> DataChain
Generate chain with list of registered datasets.
Parameters:
-
session
(Optional[Session]
, default:None
) βOptional session instance. If not provided, uses default session.
-
settings
(Optional[dict]
, 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
(Optional[str]
, 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
(Optional[list[str]]
, 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: Optional[str] = None,
project: Optional[str] = None,
version: Optional[str] = None,
force: Optional[bool] = False,
studio: Optional[bool] = False,
session: Optional[Session] = 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
(Optional[str]
, default:None
) βoptional name of namespace in which dataset to delete is created
-
project
(Optional[str]
, default:None
) βoptional name of project in which dataset to delete is created
-
version
(Optional[str]
, default:None
) βOptional dataset version
-
force
(Optional[bool]
, default:False
) βIf true, all datasets versions will be removed. Defaults to False.
-
studio
(Optional[bool]
, default:False
) βIf True, removes dataset from Studio only, otherwise removes local dataset. Defaults to False.
-
session
(Optional[Session]
, 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: Optional[Session] = 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
(Optional[Session]
, 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
read_hf
read_hf(
dataset: Union[str, HFDatasetType],
*args: Any,
session: Optional[Session] = None,
settings: Optional[dict] = None,
column: str = "",
model_name: str = "",
limit: int = 0,
**kwargs: Any
) -> DataChain
Generate chain from Hugging Face Hub dataset.
Parameters:
-
dataset
(Union[str, 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
(Optional[Session]
, default:None
) βSession to use for the chain.
-
settings
(Optional[dict]
, 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: Union[str, PathLike[str]],
type: FileType = "text",
spec: Optional[DataType] = None,
schema_from: Optional[str] = "auto",
jmespath: Optional[str] = None,
column: Optional[str] = "",
model_name: Optional[str] = None,
format: Optional[str] = "json",
nrows: Optional[int] = None,
**kwargs
) -> DataChain
Get data from JSON. It returns the chain itself.
Parameters:
-
path
(Union[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
(Optional[DataType]
, default:None
) βoptional Data Model
-
schema_from
(Optional[str]
, default:'auto'
) βpath to sample to infer spec (if schema not provided)
-
column
(Optional[str]
, default:''
) βgenerated column name
-
model_name
(Optional[str]
, default:None
) βoptional generated model name
-
format
(Optional[str]
, default:'json'
) β"json", "jsonl"
-
jmespath
(Optional[str]
, default:None
) βoptional JMESPATH expression to reduce JSON
-
nrows
(Optional[int]
, 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: Optional[Session] = 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: Optional[Session] = None,
settings: Optional[dict] = 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: Union[
str, PathLike[str], list[str], list[PathLike[str]]
],
partitioning: Any = "hive",
output: Optional[dict[str, DataType]] = None,
column: str = "",
model_name: str = "",
source: bool = True,
session: Optional[Session] = None,
settings: Optional[dict] = None,
**kwargs
) -> DataChain
Generate chain from parquet files.
Parameters:
-
path
(Union[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:///". -
partitioning
(Any
, default:'hive'
) βAny pyarrow partitioning schema.
-
output
(Optional[dict[str, DataType]]
, 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
(Optional[Session]
, default:None
) βSession to use for the chain.
-
settings
(Optional[dict]
, default:None
) βSettings to use for the chain.
Example
Reading a single file:
Reading a partitioned dataset from a directory:
Source code in datachain/lib/dc/parquet.py
read_records
read_records(
to_insert: Optional[Union[dict, Iterable[dict]]],
session: Optional[Session] = None,
settings: Optional[dict] = None,
in_memory: bool = False,
schema: Optional[dict[str, DataType]] = 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
(Optional[Union[dict, Iterable[dict]]]
) βrecords (or a single record) to insert. Each record is a dictionary of signals and their values.
-
schema
(Optional[dict[str, DataType]]
, 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: Union[
str, PathLike[str], list[str], list[PathLike[str]]
],
*,
type: FileType = "binary",
session: Optional[Session] = None,
settings: Optional[dict] = None,
in_memory: bool = False,
recursive: Optional[bool] = True,
column: str = "file",
update: bool = False,
anon: Optional[bool] = None,
delta: Optional[bool] = False,
delta_on: Optional[Union[str, Sequence[str]]] = (
"file.path",
"file.etag",
"file.version",
),
delta_result_on: Optional[
Union[str, Sequence[str]]
] = None,
delta_compare: Optional[
Union[str, Sequence[str]]
] = None,
delta_retry: Optional[Union[bool, str]] = None,
delta_unsafe: bool = False,
client_config: Optional[dict] = 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
(Union[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 -
type
(FileType
, default:'binary'
) βread file as "binary", "text", or "image" data. Default is "binary".
-
recursive
(Optional[bool]
, 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
(Optional[bool]
, default:None
) βIf True, we will treat cloud bucket as public one.
-
client_config
(Optional[dict]
, default:None
) βOptional client configuration for the storage client.
-
delta
(Optional[bool]
, 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
(Optional[Union[str, Sequence[str]]]
, 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
(Optional[Union[str, Sequence[str]]]
, 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
(Optional[Union[str, Sequence[str]]]
, 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
(Optional[Union[bool, str]]
, 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
Multiple URIs:
With AWS S3-compatible storage:
chain = 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 |
|
read_values
read_values(
ds_name: str = "",
session: Optional[Session] = None,
settings: Optional[dict] = 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: Union[str, Executable],
connection: ConnectionType,
params: Union[
Sequence[Mapping[str, Any]], Mapping[str, Any], None
] = None,
*,
output: Optional[dict[str, DataType]] = None,
session: Optional[Session] = None,
settings: Optional[dict] = None,
in_memory: bool = False,
infer_schema_length: Optional[int] = 100
) -> DataChain
Read the results of a SQL query into a DataChain, using a given database connection.
Parameters:
-
query
(Union[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
(Union[Sequence[Mapping[str, Any]], Mapping[str, Any], None]
, default:None
) βParameters to pass to execute method.
-
output
(Optional[dict[str, DataType]]
, default:None
) βA dictionary mapping column names to types, used to override the schema inferred from the query results.
-
session
(Optional[Session]
, default:None
) βSession to use for the chain.
-
settings
(Optional[dict]
, 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
(Optional[int]
, 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
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 379 |
|
ConnectionType
module-attribute
ConnectionType = Union[
str,
URL,
Connectable,
Engine,
Connection,
Session,
Connection,
]
DataChain
DataChain(
query: DatasetQuery,
settings: Settings,
signal_schema: SignalSchema,
setup: Optional[dict] = 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: Optional[Callable] = None,
partition_by: Optional[PartitionByType] = None,
params: Union[None, str, Sequence[str]] = 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
(Optional[Callable]
, default:None
) βFunction applied to each group of rows.
-
partition_by
(Optional[PartitionByType]
, default:None
) βColumn name(s) to group by. If None, all rows go into one group.
-
params
(Union[None, str, Sequence[str]]
, 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
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 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 |
|
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: Optional[Callable] = None,
params: Union[None, str, Sequence[str]] = 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: Union[str, Sequence[str]],
right_on: Optional[Union[str, Sequence[str]]] = None,
compare: Optional[Union[str, Sequence[str]]] = None,
right_compare: Optional[
Union[str, Sequence[str]]
] = None,
added: bool = True,
deleted: bool = True,
modified: bool = True,
same: bool = False,
status_col: Optional[str] = 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
(Union[str, Sequence[str]]
) βColumn(s) to match records between chains.
-
right_on
(Optional[Union[str, Sequence[str]]]
, default:None
) βColumn(s) in the other chain to match against. Defaults to
on
. -
compare
(Optional[Union[str, Sequence[str]]]
, default:None
) βColumn(s) to check for changes. If not specified,all columns are used.
-
right_compare
(Optional[Union[str, Sequence[str]]]
, 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
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 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 |
|
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: Optional[str] = None,
column: Optional[str] = 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
(Optional[str]
, default:None
) βoptional generated model name. By default generates the name automatically.
-
column
(Optional[str]
, 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: Optional[str] = None,
added: bool = True,
modified: bool = True,
deleted: bool = False,
same: bool = False,
status_col: Optional[str] = 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
(Optional[str]
, 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
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 1793 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 |
|
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
2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 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 |
|
gen
gen(
func: Optional[Union[Callable, Generator]] = None,
params: Union[None, str, Sequence[str]] = 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: Optional[
Union[str, Func, Sequence[Union[str, Func]]]
] = 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
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 |
|
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: Optional[Callable] = None,
params: Union[None, str, Sequence[str]] = 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
(Optional[Callable]
, default:None
) βFunction applied to each row.
-
params
(Union[None, str, Sequence[str]]
, 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: Union[MergeColType, Sequence[MergeColType]],
right_on: Optional[
Union[MergeColType, Sequence[MergeColType]]
] = 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
(Union[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
(Optional[Union[MergeColType, Sequence[MergeColType]]]
, 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
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 |
|
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
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 |
|
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: Optional[int] = 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
(Optional[int]
, 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
1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 |
|
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
reset_settings
reset_settings(settings: Optional[Settings] = None) -> Self
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: Optional[str] = None,
description: Optional[str] = None,
attrs: Optional[list[str]] = None,
update_version: Optional[str] = "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
(Optional[str]
, 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
(Optional[str]
, default:None
) βdescription of a dataset.
-
attrs
(Optional[list[str]]
, default:None
) βattributes of a dataset. They can be without value, e.g "NLP", or with a value, e.g "location=US".
-
update_version
(Optional[str]
, 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
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 |
|
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: Optional[bool] = None,
prefetch: Optional[Union[bool, int]] = None,
parallel: Optional[Union[bool, int]] = None,
workers: Optional[int] = None,
namespace: Optional[str] = None,
project: Optional[str] = None,
min_task_size: Optional[int] = None,
batch_size: Optional[int] = None,
sys: Optional[bool] = 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
(Optional[bool]
, default:None
) βEnable files caching to speed up subsequent accesses to the same files from the same or different chains. Defaults to False.
-
prefetch
(Optional[Union[bool, int]]
, 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
(Optional[Union[bool, int]]
, 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
(Optional[str]
, default:None
) βNamespace to use for the chain by default.
-
project
(Optional[str]
, default:None
) βProject to use for the chain by default.
-
min_task_size
(Optional[int]
, default:None
) βMinimum number of rows per worker/process for parallel processing by UDFs. Defaults to 1.
-
batch_size
(Optional[int]
, 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: Optional[Union[str, Sequence[str]]] = None,
right_on: Optional[Union[str, Sequence[str]]] = None,
) -> Self
Remove rows that appear in another chain.
Parameters:
-
other
(DataChain
) βchain whose rows will be removed from
self
-
on
(Optional[Union[str, Sequence[str]]]
, default:None
) βcolumns to consider for determining row equality in
self
. If unspecified, defaults to all common columns betweenself
andother
. -
right_on
(Optional[Union[str, Sequence[str]]]
, 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
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 |
|
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: Union[str, PathLike[str]],
delimiter: str = ",",
fs_kwargs: Optional[dict[str, Any]] = None,
**kwargs
) -> None
Save chain to a csv (comma-separated values) file.
Parameters:
-
path
(Union[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
(Optional[dict[str, Any]]
, 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: Optional[str] = None,
conflict_columns: Optional[list[str]] = None,
column_mapping: Optional[
dict[str, Optional[str]]
] = 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
(Optional[str]
, 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
(Optional[list[str]]
, default:None
) βList of column names that form a unique constraint for conflict resolution. Required when on_conflict='update' and using PostgreSQL.
-
column_mapping
(Optional[dict[str, Optional[str]]]
, 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
2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 |
|
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: Union[str, PathLike[str]],
fs_kwargs: Optional[dict[str, Any]] = None,
include_outer_list: bool = True,
) -> None
Save chain to a JSON file.
Parameters:
-
path
(Union[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
(Optional[dict[str, Any]]
, 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
(Union[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
(Optional[dict[str, Any]]
, 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
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.
Returns:
-
DataFrame
βpd.DataFrame: A pandas DataFrame representation of the chain.
Source code in datachain/lib/dc/datachain.py
to_parquet
to_parquet(
path: Union[str, PathLike[str], BinaryIO],
partition_cols: Optional[Sequence[str]] = None,
chunk_size: int = DEFAULT_PARQUET_CHUNK_SIZE,
fs_kwargs: Optional[dict[str, Any]] = None,
**kwargs
) -> None
Save chain to parquet file with SignalSchema metadata.
Parameters:
-
path
(Union[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
(Optional[Sequence[str]]
, 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
(Optional[dict[str, Any]]
, 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
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 2183 2184 2185 2186 2187 2188 |
|
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: Union[str, PathLike[str]],
signal: str = "file",
placement: ExportPlacement = "fullpath",
link_type: Literal["copy", "symlink"] = "copy",
num_threads: Optional[int] = EXPORT_FILES_MAX_THREADS,
anon: Optional[bool] = None,
client_config: Optional[dict] = None,
) -> None
Export files from a specified signal to a directory. Files can be exported to a local or cloud directory.
Parameters:
-
output
(Union[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
(Optional[int]
, default:EXPORT_FILES_MAX_THREADS
) βnumber of threads to use for exporting files. By default, it uses 5 threads.
-
anon
(Optional[bool]
, 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
(Optional[dict]
, default:None
) βOptional configuration for the destination storage client
Example
Cross cloud transfer
Source code in datachain/lib/dc/datachain.py
2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 |
|
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: Optional[Catalog] = None,
client_config: Optional[dict] = 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: Optional[Session] = None,
catalog: Optional[Catalog] = None,
client_config: Optional[dict] = 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.