I/O#
Daft offers a variety of approaches to creating a DataFrame from reading various data sources (in-memory data, files, data catalogs, and integrations) and writing to various data sources. See more about other Connectors in Daft User Guide.
Input#
from_arrow #
from_arrow(data: Union[Table, list[Table], Iterable[Table], ArrowStreamExportable]) -> DataFrame
Creates a DataFrame from Arrow data.
Accepts pyarrow Tables, lists/iterables of pyarrow Tables, or any object implementing the Arrow PyCapsule Interface <https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface> (i.e. has an __arrow_c_stream__ method). This includes pyarrow RecordBatchReaders, pandas DataFrames (2.2+), nanoarrow arrays, and other Arrow-compatible libraries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | Union[Table, list[Table], Iterable[Table], ArrowStreamExportable] | Arrow data to convert into a Daft DataFrame. | required |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | DataFrame created from the provided Arrow data. |
Examples:
1 2 3 4 5 | |
╭───────┬────────╮
│ a ┆ b │
│ --- ┆ --- │
│ Int64 ┆ String │
╞═══════╪════════╡
│ 1 ┆ foo │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
│ 2 ┆ bar │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
│ 3 ┆ baz │
╰───────┴────────╯
(Showing first 3 of 3 rows) Source code in daft/convert.py
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 | |
from_dask_dataframe #
from_dask_dataframe(ddf: DataFrame) -> DataFrame
Creates a Daft DataFrame from a Dask DataFrame.
The provided Dask DataFrame must have been created using Dask-on-Ray.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ddf | DataFrame | The Dask DataFrame to create a Daft DataFrame from. | required |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | Daft DataFrame created from the provided Dask DataFrame. |
Note
This function can only work if Daft is running using the RayRunner
Examples:
1 2 3 4 5 6 7 8 9 10 | |
╭───────┬────────╮
│ a ┆ b │
│ --- ┆ --- │
│ Int64 ┆ String │
╞═══════╪════════╡
│ 1 ┆ foo │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
│ 2 ┆ bar │
╰───────┴────────╯
(Showing first 2 of 2 rows) Source code in daft/convert.py
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 | |
from_glob_path #
Creates a DataFrame of file paths and other metadata from a glob path.
This method supports wildcards:
*matches any number of any characters including none?matches any single character[...]matches any single character in the brackets**recursively matches any number of layers of directories
The returned DataFrame will have the following columns:
- path: the path to the file/directory
- size: size of the object in bytes
- rows: the total rows of parquet object, it's None for other formats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path | str | list | Path to files on disk (allows wildcards). | required |
io_config | IOConfig | Configuration to use when running IO with remote services | None |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | DataFrame containing the path to each file as a row, along with other metadata parsed from the provided filesystem. |
Note
If no files match the glob pattern(s), an empty DataFrame is returned instead of raising an error.
Examples:
1 2 3 4 | |
Source code in daft/io/file_path.py
12 13 14 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 | |
from_pandas #
from_pandas(data: Union[DataFrame, list[DataFrame]]) -> DataFrame
Creates a Daft DataFrame from a pandas DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | Union[DataFrame, list[DataFrame]] | pandas DataFrame(s) that we wish to convert into a Daft DataFrame. | required |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | Daft DataFrame created from the provided pandas DataFrame. |
Examples:
1 2 3 4 5 | |
╭───────┬────────╮
│ a ┆ b │
│ --- ┆ --- │
│ Int64 ┆ String │
╞═══════╪════════╡
│ 1 ┆ foo │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
│ 2 ┆ bar │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
│ 3 ┆ baz │
╰───────┴────────╯
(Showing first 3 of 3 rows) Source code in daft/convert.py
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 | |
from_pydict #
from_pydict(data: dict[str, InputListType]) -> DataFrame
Creates a DataFrame from a Python dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | dict[str, InputListType] | Key -> Sequence[item] of data. Each Key is created as a column, and must have a value that is a Python list, Numpy array or PyArrow array. Values must be equal in length across all keys. | required |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | DataFrame created from dictionary of columns |
Examples:
1 2 3 | |
╭───────╮
│ foo │
│ --- │
│ Int64 │
╞═══════╡
│ 1 │
├╌╌╌╌╌╌╌┤
│ 2 │
╰───────╯
(Showing first 2 of 2 rows) Source code in daft/convert.py
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 | |
from_pylist #
from_pylist(data: list[dict[str, Any]]) -> DataFrame
Creates a DataFrame from a list of dictionaries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | list[dict[str, Any]] | List of dictionaries, where each key is a column name. | required |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | DataFrame created from list of dictionaries. |
Examples:
1 2 3 | |
╭───────╮
│ foo │
│ --- │
│ Int64 │
╞═══════╡
│ 1 │
├╌╌╌╌╌╌╌┤
│ 2 │
╰───────╯
(Showing first 2 of 2 rows) Source code in daft/convert.py
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 | |
from_ray_dataset #
from_ray_dataset(ds: Dataset) -> DataFrame
Creates a DataFrame from a Ray Dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ds | Dataset | The Ray Dataset to create a Daft DataFrame from. | required |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | Daft DataFrame created from the provided Ray dataset. |
Note
This function can only work if Daft is running using the RayRunner
Examples:
1 2 3 4 5 6 7 8 | |
╭───────┬────────╮
│ a ┆ b │
│ --- ┆ --- │
│ Int64 ┆ String │
╞═══════╪════════╡
│ 1 ┆ foo │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
│ 2 ┆ bar │
╰───────┴────────╯
(Showing first 2 of 2 rows) Source code in daft/convert.py
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 | |
read_blob #
read_blob(path: str | list[str], *, max_connections: int = 32, on_error: Literal['raise', 'null'] = 'raise', io_config: IOConfig | None = None) -> DataFrame
Creates a DataFrame from the contents of file(s), where each file is read as a single row of raw bytes.
This is similar to DuckDB's read_blob function, and is useful for reading files that are not stored in a tabular format, such as images, audio files, or other binary data.
This method supports wildcards:
*matches any number of any characters including none?matches any single character[...]matches any single character in the brackets**recursively matches any number of layers of directories
The returned DataFrame will have the following columns:
- path: the path to the file
- size: size of the file in bytes
- content: the raw bytes contents of the file
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path | str | list | Path to file(s) on disk or remote object stores such as | required |
max_connections | int | The maximum number of connections to use per thread to use for downloading file contents. Defaults to 32. | 32 |
on_error | Literal['raise', 'null'] | Behavior when a file download error is encountered - "raise" to raise the error immediately or "null" to log the error but fallback to a Null value. Defaults to "raise". | 'raise' |
io_config | IOConfig | Configuration to use when running IO with remote services | None |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | DataFrame with one row per file, containing the path, size and raw bytes contents of each file. |
Examples:
Read files from a local path:
1 2 | |
Read files from a public S3 bucket:
1 2 3 | |
Source code in daft/io/_blob.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 | |
read_csv #
read_csv(path: str | list[str], infer_schema: bool = True, schema: dict[str, DataType] | None = None, has_headers: bool = True, delimiter: str | None = None, double_quote: bool = True, quote: str | None = None, escape_char: str | None = None, comment: str | None = None, allow_variable_columns: bool = False, io_config: IOConfig | None = None, file_path_column: str | None = None, hive_partitioning: bool = False, ignore_corrupt_files: bool = False, _buffer_size: int | None = None, _chunk_size: int | None = None, checkpoint: CheckpointConfig | None = None) -> DataFrame
Creates a DataFrame from CSV file(s).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path | str | Path to CSV (allows for wildcards; supports remote URLs to object stores such as | required |
infer_schema | bool | Whether to infer the schema of the CSV, defaults to True. | True |
schema | dict[str, DataType] | A schema that is used as the definitive schema for the CSV if infer_schema is False, otherwise it is used as a schema hint that is applied after the schema is inferred (overriding the types of inferred columns, and appending any new columns not found during inference). | None |
has_headers | bool | Whether the CSV has a header or not, defaults to True | True |
delimiter | Str | Delimiter used in the CSV, defaults to "," | None |
double_quote | bool | Whether to support double quote escapes, defaults to True | True |
escape_char | str | Character to use as the escape character for double quotes, or defaults to | None |
comment | str | Character to treat as the start of a comment line, or None to not support comments | None |
allow_variable_columns | bool | Whether to allow for variable number of columns in the CSV, defaults to False. If set to True, Daft will append nulls to rows with less columns than the schema, and ignore extra columns in rows with more columns | False |
io_config | IOConfig | Config to be used with the native downloader | None |
file_path_column | str | None | Include the source path(s) as a column with this name. Defaults to None. | None |
hive_partitioning | bool | Whether to infer hive_style partitions from file paths and include them as columns in the Dataframe. Defaults to False. | False |
checkpoint | CheckpointConfig | None | Optional :class: | None |
ignore_corrupt_files | bool | If True, corrupt or unreadable CSV files are silently skipped instead of raising an error. Skipped files are recorded in | False |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | parsed DataFrame |
Examples:
Read a CSV file from a local path:
1 2 3 | |
Read a CSV file from a public S3 bucket:
1 2 3 4 | |
Source code in daft/io/_csv.py
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 | |
read_deltalake #
read_deltalake(table: Union[str, UnityCatalogTable], version: Union[int, str, datetime] | None = None, io_config: IOConfig | None = None, ignore_deletion_vectors: bool = False, _multithreaded_io: bool | None = None) -> DataFrame
Create a DataFrame from a Delta Lake table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table | Union[str, UnityCatalogTable] | Either a URI for the Delta Lake table (supports remote URLs to object stores such as | required |
version | optional | If int is passed, read the table with specified version number. Otherwise if string or datetime, read the timestamp version of the table. Strings must be RFC 3339 and ISO 8601 date and time format. Datetimes are assumed to be UTC timezone unless specified. By default, read the latest version of the table. | None |
io_config | optional | A custom :class: | None |
ignore_deletion_vectors | optional | Whether to skip checking for deletion vectors when reading the table. Defaults to False. | False |
_multithreaded_io | optional | Whether to use multithreading for IO threads. Setting this to False can be helpful in reducing the amount of system resources (number of connections and thread contention) when running in the Ray runner. Defaults to None, which will let Daft decide based on the runner it is currently using. | None |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | A DataFrame with the schema converted from the specified Delta Lake table. |
Note
This function requires the use of deltalake, a Python library for interacting with Delta Lake.
Examples:
Read a Delta Lake table from a local path:
1 2 3 4 5 | |
Read a Delta Lake table from a public S3 bucket:
1 2 3 4 | |
Source code in daft/io/delta_lake/_deltalake.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 | |
read_hudi #
read_hudi(table_uri: str, io_config: IOConfig | None = None, checkpoint: CheckpointConfig | None = None) -> DataFrame
Create a DataFrame from a Hudi table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table_uri | str | URI to the Hudi table (supports remote URLs to object stores such as | required |
io_config | IOConfig | None | A custom IOConfig to use when accessing Hudi table object storage data. Defaults to None. | None |
checkpoint | CheckpointConfig | None | Optional :class: | None |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | A DataFrame with the schema converted from the specified Hudi table. |
Examples:
Read a Hudi table from a local path:
1 2 3 | |
Read a Hudi table from a public S3 bucket:
1 2 3 4 | |
Source code in daft/io/hudi/_hudi.py
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 | |
read_iceberg #
read_iceberg(table: Union[str, PathLike[str], Table], snapshot_id: int | None = None, branch: str | None = None, tag: str | None = None, io_config: IOConfig | None = None, checkpoint: CheckpointConfig | None = None, ignore_corrupt_files: bool = False) -> DataFrame
Create a DataFrame from an Iceberg table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table | str, os.PathLike, or pyiceberg.table.Table | A path to an Iceberg metadata file (supports remote URLs to object stores such as | required |
snapshot_id | int | Snapshot ID of the table to query | None |
branch | str | Iceberg branch name to query. Cannot be combined with | None |
tag | str | Iceberg tag name to query. Cannot be combined with | None |
io_config | IOConfig | A custom IOConfig to use when accessing Iceberg object storage data. If provided, configurations set in | None |
checkpoint | CheckpointConfig | None | Optional :class: | None |
ignore_corrupt_files | bool | If True, silently skip corrupt or unreadable data files instead of raising an error. Skipped files are recorded in | False |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | a DataFrame with the schema converted from the specified Iceberg table |
Note
This function requires the use of PyIceberg, which is the Apache Iceberg's official project for Python.
Examples:
Read an Iceberg table from a PyIceberg table:
1 2 3 4 5 6 7 8 | |
Read an Iceberg table from S3 using IOConfig:
1 2 3 4 | |
Source code in daft/io/iceberg/_iceberg.py
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 | |
read_json #
read_json(path: str | list[str], infer_schema: bool = True, schema: dict[str, DataType] | None = None, io_config: IOConfig | None = None, file_path_column: str | None = None, hive_partitioning: bool = False, skip_empty_files: bool = False, _buffer_size: int | None = None, _chunk_size: int | None = None, checkpoint: CheckpointConfig | None = None) -> DataFrame
Creates a DataFrame from line-delimited JSON file(s).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path | str | Path to JSON files (allows for wildcards; supports remote URLs to object stores such as | required |
infer_schema | bool | Whether to infer the schema of the JSON, defaults to True. | True |
schema | dict[str, DataType] | A schema that is used as the definitive schema for the JSON if infer_schema is False, otherwise it is used as a schema hint that is applied after the schema is inferred (overriding the types of inferred columns, and appending any new columns not found during inference). | None |
io_config | IOConfig | Config to be used with the native downloader | None |
file_path_column | str | None | Include the source path(s) as a column with this name. Defaults to None. | None |
hive_partitioning | bool | Whether to infer hive_style partitions from file paths and include them as columns in the Dataframe. Defaults to False. | False |
skip_empty_files | bool | Whether to skip empty files when reading. Defaults to False. | False |
checkpoint | CheckpointConfig | None | Optional :class: | None |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | parsed DataFrame |
Examples:
Read a JSON file from a local path:
1 2 3 | |
Read a JSON file from a public S3 bucket:
1 2 3 4 | |
Source code in daft/io/_json.py
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 | |
read_kafka #
read_kafka(bootstrap_servers: str | Sequence[str], topics: str | Sequence[str], *, start: object = _KIND_EARLIEST, end: object = _KIND_LATEST, group_id: str = 'daft-bounded-kafka-reader', partitions: Sequence[int] | None = None, chunk_size: int = 1024, kafka_client_config: Mapping[str, object] | None = None, timeout_ms: int = 10000) -> DataFrame
Creates a DataFrame by reading messages from Kafka topic(s).
.. warning::
1 2 3 | |
This function reads bounded ranges of messages from one or more Kafka topics. It supports multiple ways to specify the start and end bounds: earliest/latest, timestamp, or explicit partition offsets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bootstrap_servers | str | Sequence[str] | Kafka bootstrap server(s) to connect to. Can be a single server string (e.g., "localhost:9092") or a sequence of servers. | required |
topics | str | Sequence[str] | Kafka topic(s) to read from. Can be a single topic string or a sequence of topics. | required |
start | object | The start bound for reading messages. Defaults to "earliest". Supported values: - "earliest": Start from the earliest available offset for each partition. - "latest": Start from the latest offset for each partition. - int: Timestamp in milliseconds since epoch. - datetime: A timezone-aware or naive datetime (naive datetimes are assumed UTC). - str: An ISO-8601 timestamp string (e.g., "2024-01-01T00:00:00Z"). - dict: For single topic: | _KIND_EARLIEST |
end | object | The end bound for reading messages. Defaults to "latest". Supports the same value types as | _KIND_LATEST |
group_id | str | Consumer group ID used for the Kafka consumer. Defaults to "daft-bounded-kafka-reader". | 'daft-bounded-kafka-reader' |
partitions | Sequence[int] | None | Optional sequence of partition IDs to read from. If None, reads from all partitions of the specified topic(s). Defaults to None. | None |
chunk_size | int | Maximum number of messages per RecordBatch. Defaults to 1024. | 1024 |
kafka_client_config | Mapping[str, object] | None | Optional additional configuration options passed directly to the underlying Kafka consumer. These are merged with the default configuration. Defaults to None. | None |
timeout_ms | int | Timeout in milliseconds for Kafka operations (metadata queries, message consumption, etc.). Defaults to 10_000 (10 seconds). | 10000 |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | A DataFrame with the following schema: - topic (string): The topic the message was read from. - partition (int32): The partition ID within the topic. - offset (int64): The offset of the message within the partition. - timestamp_ms (int64): The timestamp of the message in milliseconds since epoch, or null if not available. - key (binary): The message key as raw bytes, or null if not present. - value (binary): The message value as raw bytes. |
Examples:
Read from a single topic with default bounds (earliest to latest):
1 | |
Read from multiple topics:
1 | |
Read from specific partitions:
1 | |
Read from a timestamp range:
1 2 3 4 | |
Read from specific partition offsets:
1 | |
Read from multiple topics with per-topic offsets:
1 2 3 4 5 | |
Configure Kafka client options:
1 2 3 4 5 | |
Note
This function requires the confluent-kafka package. Install it with: pip install daft[kafka] or pip install confluent-kafka
Timestamp bounds use Kafka message timestamps. If your cluster uses CreateTime, producers can publish late/out-of-order timestamps; timestamp bounds are not a safe exactly-once checkpoint. Prefer offset-based checkpoints (e.g., partition offset maps or committed consumer offsets)
Source code in daft/io/_kafka.py
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 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 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 | |
read_lance #
read_lance(uri: str | PathLike[str] | None = None, io_config: Any = None, version: Any = None, asof: Any = None, block_size: Any = None, commit_lock: Any = None, index_cache_size: Any = None, default_scan_options: Any = None, metadata_cache_size_bytes: Any = None, fragment_group_size: Any = None, include_fragment_id: Any = None, checkpoint: Any = None, *, table_id: list[str] | None = None, namespace_impl: str | None = None, namespace_properties: dict[str, str] | None = None) -> Any
Create a DataFrame from a LanceDB table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri | str | PathLike[str] | None | The URI of the Lance table to read from. Accepts a local path or an object-store URI like "s3://bucket/path". Mutually exclusive with the namespace parameters. | None |
table_id | list[str] | None | Table identifier within a Lance Namespace, e.g. | None |
namespace_impl | str | None | Lance Namespace implementation, such as | None |
namespace_properties | dict[str, str] | None | Properties for connecting to the namespace. | None |
io_config | Any | A custom IOConfig to use when accessing LanceDB data. Defaults to None. | None |
version | optional, int | str If specified, load a specific version of the Lance dataset. Else, loads the latest version. A version number ( | required | |
asof | optional, datetime or str If specified, find the latest version created on or earlier than the given argument value. If a version is already specified, this arg is ignored. | required | |
block_size | optional, int Block size in bytes. Provide a hint for the size of the minimal I/O request. | required | |
commit_lock | optional, lance.commit.CommitLock A custom commit lock. Only needed if your object store does not support atomic commits. See the user guide for more details. | required | |
index_cache_size | optional, int Index cache size. Index cache is a LRU cache with TTL. This number specifies the number of index pages, for example, IVF partitions, to be cached in the host memory. Default value is Roughly, for an | required | |
default_scan_options | optional, dict Default scan options that are used when scanning the dataset. This accepts the same arguments described in This can be useful to supply defaults for common parameters such as It can also be used to create a view of the dataset that includes meta fields such as | required | |
metadata_cache_size_bytes | optional, int Size of the metadata cache in bytes. This cache is used to store metadata information about the dataset, such as schema and statistics. If not specified, a default size will be used. | required | |
fragment_group_size | optional, int Number of fragments to group together in a single scan task. If None or <= 1, each fragment will be processed individually (default behavior). | required | |
include_fragment_id | Optional, bool Whether to display fragment_id. if you have the behavior of 'merge_columns_df' or 'write_lance(mode = 'merge')', the | required | |
checkpoint | Any | Optional :class: | None |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | Any | a DataFrame with the schema converted from the specified LanceDB table |
Any | This function requires the use of LanceDB, which is the Python library for the LanceDB project. | |
Any | To ensure that this is installed with Daft, you may install: |
Examples:
Read a local LanceDB table:
1 2 | |
Read a LanceDB table and specify a version:
1 2 | |
Read a LanceDB table with fragment grouping:
1 2 | |
Read a LanceDB table from a public S3 bucket:
1 2 3 4 | |
Source code in daft/io/lance/_lance.py
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 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | |
read_parquet #
read_parquet(path: str | list[str], row_groups: list[list[int]] | None = None, infer_schema: bool = True, schema: dict[str, DataType] | None = None, io_config: IOConfig | None = None, file_path_column: str | None = None, hive_partitioning: bool = False, coerce_int96_timestamp_unit: str | TimeUnit | None = None, ignore_corrupt_files: bool = False, _multithreaded_io: bool | None = None, _chunk_size: int | None = None, checkpoint: CheckpointConfig | None = None) -> DataFrame
Creates a DataFrame from Parquet file(s).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path | str | Path to Parquet file (allows for wildcards; supports remote URLs to object stores such as | required |
row_groups | List[int] or List[List[int]] | List of row groups to read corresponding to each file. | None |
infer_schema | bool | Whether to infer the schema of the Parquet, defaults to True. | True |
schema | dict[str, DataType] | A schema that is used as the definitive schema for the Parquet file if infer_schema is False, otherwise it is used as a schema hint that is applied after the schema is inferred (overriding the types of inferred columns, and appending any new columns not found during inference). | None |
io_config | IOConfig | Config to be used with the native downloader | None |
file_path_column | str | None | Include the source path(s) as a column with this name. Defaults to None. | None |
hive_partitioning | bool | Whether to infer hive_style partitions from file paths and include them as columns in the Dataframe. Defaults to False. | False |
coerce_int96_timestamp_unit | str | TimeUnit | None | TimeUnit to coerce Int96 TimeStamps to. e.g.: [ns, us, ms], Defaults to None. | None |
ignore_corrupt_files | bool | If True, corrupt or unreadable Parquet files are silently skipped instead of raising an error. Skipped files are recorded in | False |
_multithreaded_io | bool | None | Whether to use multithreading for IO threads. Setting this to False can be helpful in reducing the amount of system resources (number of connections and thread contention) when running in the Ray runner. Defaults to None, which will let Daft decide based on the runner it is currently using. | None |
checkpoint | CheckpointConfig | None | Optional :class: | None |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | parsed DataFrame |
Examples:
Read a Parquet file from a local path:
1 2 3 | |
Read a Parquet file from a public S3 bucket:
1 2 3 4 | |
Source code in daft/io/_parquet.py
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_orc #
read_orc(path: str | list[str], io_config: IOConfig | None = None, batch_size: int = 128 * 1024) -> DataFrame
Creates a DataFrame from ORC file(s).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path | str | list[str] | Path to an ORC file, directory, glob, or list of paths. Directories are searched recursively for | required |
io_config | IOConfig | None | Configuration for the native file I/O backend. Defaults to the planning context's default I/O configuration. | None |
batch_size | int | Maximum number of rows yielded per record batch. Defaults to 131072. This does not impose a fixed memory limit. | 128 * 1024 |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | parsed DataFrame. |
Note
The schema is inferred from the first matched file. Later files are aligned to that schema: missing fields become nulls and extra fields are excluded. Conversions follow Daft's rules, as with Parquet reads: unsupported conversions raise an error, while some invalid values (such as invalid numeric strings) become nulls. An empty ORC file with a valid schema is supported. Each file is read by one task; stripes are not split into separate distributed tasks. Filters and limits use Daft's existing execution operators, without ORC-native predicate pruning. A limit does not guarantee early termination of file reads. The shared Python source bridge can continue reading and buffering batches after the returned-row limit is reached.
Examples:
Read ORC files from a local path:
1 2 3 | |
Source code in daft/io/_orc.py
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 | |
read_sql #
read_sql(sql: str, conn: Callable[[], Connection] | str, partition_col: str | None = None, num_partitions: int | None = None, partition_bound_strategy: str = 'min-max', disable_pushdowns_to_sql: bool = False, infer_schema: bool = True, infer_schema_length: int = 10, schema: dict[str, DataType] | None = None) -> DataFrame
Create a DataFrame from the results of a SQL query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sql | str | SQL query to execute | required |
conn | Union[Callable[[], Connection], str] | SQLAlchemy connection factory or database URL | required |
partition_col | Optional[str] | Column to partition the data by, defaults to None | None |
num_partitions | Optional[int] | Number of partitions to read the data into, defaults to None, which will lets Daft determine the number of partitions. If specified, | None |
partition_bound_strategy | str | Strategy to determine partition bounds, either "min-max" or "percentile", defaults to "min-max" | 'min-max' |
disable_pushdowns_to_sql | bool | Whether to disable pushdowns to the SQL query, defaults to False | False |
infer_schema | bool | Whether to turn on schema inference, defaults to True. If set to False, the schema parameter must be provided. | True |
infer_schema_length | int | The number of rows to scan when inferring the schema, defaults to 10. If infer_schema is False, this parameter is ignored. Note that if Daft is able to use ConnectorX to infer the schema, this parameter is ignored as ConnectorX is an Arrow backed driver. | 10 |
schema | Optional[Dict[str, DataType]] | A mapping of column names to datatypes. If infer_schema is False, this schema is used as the definitive schema for the data, otherwise it is used as a schema hint that is applied after the schema is inferred (overriding the types of inferred columns, and appending any new columns not found during inference). This can be useful if the types can be more precisely determined than what the inference can provide (e.g., if a column can be declared as a fixed-sized list rather than a list). | None |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | Dataframe containing the results of the query |
Note
-
Supported dialects: Daft uses SQLGlot to build and translate SQL queries between dialects. For a list of supported dialects, see SQLGlot's dialect documentation.
-
Partitioning: When
partition_colis specified, the function partitions the query based on that column. You can definenum_partitionsor leave it to Daft to decide. Daft uses thepartition_bound_strategyparameter to determine the partitioning strategy:min_max: Daft calculates the minimum and maximum values of the specified column, then partitions the query using equal ranges between the minimum and maximum values.percentile: Daft calculates the specified column's percentiles via aPERCENTILE_DISCfunction to determine partitions (e.g., fornum_partitions=3, it uses the 33rd and 66th percentiles).
-
Execution: Daft executes SQL queries using using ConnectorX or SQLAlchemy, preferring ConnectorX unless a SQLAlchemy connection factory is specified or the database dialect is unsupported by ConnectorX.
-
Pushdowns: Daft pushes down operations such as filtering, projections, and limits into the SQL query when possible. You can disable pushdowns by setting
disable_pushdowns_to_sql=True, which will execute the SQL query as is.
Examples:
Read data from a SQL query and a database URL:
1 | |
Read data from a SQL query and a SQLAlchemy connection factory:
1 2 3 | |
Read data from a SQL query and partition the data by a column:
1 | |
Read data from a SQL query and partition the data into 3 partitions:
1 2 3 | |
Source code in daft/io/_sql.py
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 | |
read_video_frames #
read_video_frames(path: str | list[str], image_height: int, image_width: int, is_key_frame: bool | None = None, *, sample_interval_seconds: float | None = None, io_config: IOConfig | None = None) -> DataFrame
Creates a DataFrame by reading the frames of one or more video files.
This produces a DataFrame with the following fields
- path (string): path to the video file that produced this frame.
- frame_index (int): frame index in the video.
- frame_time (float): frame time in fractional seconds as a floating point.
- frame_time_base (str): fractional unit of seconds in which timestamps are expressed.
- frame_pts (int): frame presentation timestamp in time_base units.
- frame_dts (int): frame decoding timestamp in time_base units.
- frame_duration (int): frame duration in time_base units.
- is_key_frame (bool): true iff this is a key frame.
Warning
This requires PyAV which can be installed with pip install av.
Note
This function will stream the frames from all videos as a DataFrame of images. If you wish to load an entire video into a single row, this can be done with DataFrame.from_glob_path and url_download.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path | str | list[str] | Path(s) to the video file(s) which allows wildcards. | required |
image_height | int | Height to which each frame will be resized. | required |
image_width | int | Width to which each frame will be resized. | required |
is_key_frame | bool | None | If True, only include key frames; if False, only non-key frames; if None, include all frames. | None |
sample_interval_seconds | float | None | If provided and > 0, sample frames at approximately this time interval in seconds based on | None |
io_config | IOConfig | None | Optional IOConfig. | None |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | dataframe of images. |
Examples:
1 2 3 4 | |
Sample approximately one frame per second:
1 2 3 | |
Sample approximately one frame every 5 seconds:
1 2 3 | |
Combine with key frame filtering:
1 2 3 | |
Source code in daft/io/av/__init__.py
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 | |
read_warc #
read_warc(path: str | list[str], io_config: IOConfig | None = None, file_path_column: str | None = None, _multithreaded_io: bool | None = None, checkpoint: CheckpointConfig | None = None) -> DataFrame
Creates a DataFrame from WARC or gzipped WARC file(s). This is an experimental feature and the API may change in the future.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path | Union[str, List[str]] | Path to WARC file (allows for wildcards; supports remote URLs to object stores such as | required |
io_config | Optional[IOConfig] | Config to be used with the native downloader | None |
file_path_column | Optional[str] | Include the source path(s) as a column with this name. Defaults to None. | None |
_multithreaded_io | Optional[bool] | Whether to use multithreading for IO threads. Setting this to False can be helpful in reducing the amount of system resources (number of connections and thread contention) when running in the Ray runner. Defaults to None, which will let Daft decide based on the runner it is currently using. | None |
checkpoint | CheckpointConfig | None | Optional :class: | None |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | parsed DataFrame with mandatory metadata columns ("WARC-Record-ID", "WARC-Type", "WARC-Date", "Content-Length"), one optional metadata column ("WARC-Identified-Payload-Type"), one column "warc_content" with the raw byte content of the WARC record, and one column "warc_headers" with the remaining headers of the WARC record stored as a JSON string. |
Examples:
Read a WARC file from a local path:
1 2 3 | |
Read a WARC file from a public S3 bucket:
1 2 3 4 | |
Source code in daft/io/_warc.py
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 | |
read_webdataset #
read_webdataset(path: str | list[str], io_config: IOConfig | None = None, batch_size: int = 1000) -> DataFrame
Read one or more WebDataset TAR shards.
Consecutive TAR members with the same filename prefix are grouped into one row. The member suffix becomes the column name, following the WebDataset convention. Image, audio, video, and other binary members are represented by lazy :class:daft.File references into the TAR archive. JSON, text, and class/index sidecars are decoded eagerly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path | str | list[str] | An uncompressed TAR file, directory, glob, or list of paths. Directories are searched recursively for | required |
io_config | IOConfig | None | Configuration for local or remote storage. | None |
batch_size | int | Maximum number of samples yielded per record batch. | 1000 |
Returns:
| Type | Description |
|---|---|
DataFrame | A DataFrame containing |
DataFrame | suffix discovered during schema inference. |
Note
Compressed TAR archives are not supported because member byte offsets cannot be used for lazy range-backed file references. Sparse TAR members are not supported because their logical contents are not stored as contiguous byte ranges. Member suffixes and JSON shapes must be consistent across shards. The schema is inferred from the first five samples of the first shard, and later incompatibilities raise an error instead of discarding data.
Examples:
1 2 | |
Source code in daft/io/webdataset/_webdataset.py
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 | |
read_huggingface #
read_huggingface(repo: str, io_config: IOConfig | None = None, format: Literal['parquet', 'webdataset'] | None = None) -> DataFrame
Create a DataFrame from a Hugging Face dataset.
Currently supports all public datasets, private Parquet datasets, and repositories stored as WebDataset TAR shards. See the Hugging Face dataset docs for more details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo | str | repository to read in the form | required |
io_config | IOConfig | Config to use when reading data | None |
format | Literal['parquet', 'webdataset'] | None | Dataset storage format. If | None |
Source code in daft/io/huggingface/__init__.py
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 | |
sql #
Run a SQL query, returning the results as a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sql | str | SQL query to execute | required |
register_globals | bool | Whether to incorporate global variables into the supplied catalog, in which case a copy of the catalog will be made and the original not modified. Defaults to True. | True |
**bindings | DataFrame | (DataFrame): Additional DataFrame bindings (CTEs) to use for this query. | {} |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | Dataframe containing the results of the query |
Warning
This features is early in development and will likely experience API changes.
Examples:
A simple example joining 2 dataframes together using a SQL statement, relying on Daft to detect the names of SQL tables using their corresponding Python variable names.
1 2 3 4 5 6 7 8 | |
╭───────┬────────┬────────╮
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ Int64 ┆ String ┆ String │
╞═══════╪════════╪════════╡
│ 1 ┆ foo ┆ daft │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
│ 2 ┆ bar ┆ None │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
│ 3 ┆ baz ┆ None │
╰───────┴────────┴────────╯
(Showing first 3 of 3 rows) A more complex example using CTE bindings to create a named subquery (DataFrame) called "my_df", which can then be referenced from inside your SQL statement.
1 2 3 4 5 6 7 8 | |
╭───────╮
│ a │
│ --- │
│ Int64 │
╞═══════╡
│ 1 │
├╌╌╌╌╌╌╌┤
│ 2 │
├╌╌╌╌╌╌╌┤
│ 3 │
╰───────╯
(Showing first 3 of 3 rows) Source code in daft/sql/sql.py
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 | |
Output#
write_csv #
write_csv(root_dir: str | Path, write_mode: Literal['append', 'overwrite', 'overwrite-partitions'] = 'append', partition_cols: list[ColumnInputType] | None = None, io_config: IOConfig | None = None, delimiter: str | None = None, quote: str | None = None, escape: str | None = None, header: bool | None = True, date_format: str | None = None, timestamp_format: str | None = None) -> DataFrame
Writes the DataFrame as CSV files, returning a new DataFrame with paths to the files that were written.
Files will be written to <root_dir>/* with randomly generated UUIDs as the file names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root_dir | str | root file path to write CSV files to. | required |
write_mode | str | Operation mode of the write. | 'append' |
partition_cols | Optional[List[ColumnInputType]] | How to subpartition each partition further. Defaults to None. | None |
io_config | Optional[IOConfig] | configurations to use when interacting with remote storage. | None |
delimiter | Optional[str] | Single-character field delimiter (default | None |
quote | Optional[str] | Single-character quote used around fields containing delimiters default | None |
escape | Optional[str] | Single-character escape for special characters default | None |
header | Optional[bool] | Whether to write a header row with column names, default True. | True |
date_format | Optional[str] | Format string for date columns. Uses chrono strftime format (e.g., "%Y-%m-%d", "%d/%m/%Y"). Defaults to None (ISO 8601 format). | None |
timestamp_format | Optional[str] | Format string for timestamp columns. Uses chrono strftime format (e.g., "%Y-%m-%d %H:%M:%S", "%+"). Defaults to None (ISO 8601 format). | None |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | The filenames that were written out as strings. |
Note
This call is blocking and will execute the DataFrame when called
Timezone handling: For timezone-aware timestamp columns, the timestamps are converted to the target timezone before formatting. For example, a timestamp stored as UTC but with timezone "America/New_York" will be formatted in Eastern Time, not UTC. If the timezone string is invalid, an error will be raised.
Examples:
Basic usage:
1 2 3 | |
Custom date format (e.g., DD/MM/YYYY):
1 2 3 | |
# Output: 15/01/2024 Custom timestamp format:
1 2 | |
# Output: 2024-01-15 10:30:45 ISO 8601 / RFC 3339 timestamp format:
1 | |
# Output: 2024-01-15T10:30:45+00:00 Tip
See also df.write_parquet() and df.write_json() other formats for writing DataFrames
Source code in daft/dataframe/dataframe.py
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 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 | |
write_json #
write_json(root_dir: str | Path, write_mode: Literal['append', 'overwrite', 'overwrite-partitions'] = 'append', partition_cols: list[ColumnInputType] | None = None, io_config: IOConfig | None = None, ignore_null_fields: bool | None = False, date_format: str | None = None, timestamp_format: str | None = None) -> DataFrame
Writes the DataFrame as JSON files, returning a new DataFrame with paths to the files that were written.
Files will be written to <root_dir>/* with randomly generated UUIDs as the file names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root_dir | str | root file path to write JSON files to. | required |
write_mode | str | Operation mode of the write. | 'append' |
partition_cols | Optional[List[ColumnInputType]] | How to subpartition each partition further. Defaults to None. | None |
io_config | Optional[IOConfig] | configurations to use when interacting with remote storage. | None |
ignore_null_fields | Optional[bool] | Whether to ignore fields with null values when writing JSON. Defaults to False. | False |
date_format | Optional[str] | Format string for date columns. Uses chrono strftime format (e.g., "%Y-%m-%d", "%d/%m/%Y"). Defaults to None (ISO 8601 format). | None |
timestamp_format | Optional[str] | Format string for timestamp columns. Uses chrono strftime format (e.g., "%Y-%m-%d %H:%M:%S", "%+"). Defaults to None (ISO 8601 format). | None |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | The filenames that were written out as strings. |
Note
This call is blocking and will execute the DataFrame when called
Timezone handling: For timezone-aware timestamp columns, the timestamps are converted to the target timezone before formatting. For example, a timestamp stored as UTC but with timezone "America/New_York" will be formatted in Eastern Time, not UTC. If the timezone string is invalid, an error will be raised.
Examples:
Basic usage:
1 2 3 | |
Custom date format (e.g., DD/MM/YYYY):
1 2 3 | |
# Output: "15/01/2024" Custom timestamp format:
1 2 | |
# Output: "2024-01-15 10:30:45" ISO 8601 / RFC 3339 timestamp format:
1 | |
# Output: "2024-01-15T10:30:45+00:00" Source code in daft/dataframe/dataframe.py
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 1300 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 | |
write_parquet #
write_parquet(root_dir: str | Path, compression: str = 'snappy', write_mode: Literal['append', 'overwrite', 'overwrite-partitions'] = 'append', write_success_file: bool = False, partition_cols: list[ColumnInputType] | None = None, io_config: IOConfig | None = None, column_compression: dict[str, str] | None = None, single_file: bool = False) -> DataFrame
Writes the DataFrame as parquet files, returning a new DataFrame with paths to the files that were written.
Files will be written to <root_dir>/* with randomly generated UUIDs as the file names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root_dir | str | root file path to write parquet files to. When | required |
compression | str | default compression codec applied to every column. Defaults to "snappy". Accepts "snappy", "gzip", "zstd", "lz4", "lz4_raw", "brotli", "uncompressed", or "none" (case-insensitive). | 'snappy' |
write_mode | str | Operation mode of the write. | 'append' |
write_success_file | bool | Whether to write a | False |
partition_cols | Optional[List[ColumnInputType]] | How to subpartition each partition further. Defaults to None. | None |
io_config | Optional[IOConfig] | configurations to use when interacting with remote storage. | None |
column_compression | Optional[Dict[str, str]] | per-column compression overrides. Keys are dot-separated column paths (e.g. | None |
single_file | bool | If True, coalesce all data into a single parquet file at | False |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | The filenames that were written out as strings. |
Note
This call is blocking and will execute the DataFrame when called
Examples:
1 2 3 4 | |
Tip
See also df.write_csv() and df.write_json() Other formats for writing DataFrames
Source code in daft/dataframe/dataframe.py
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 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 | |
write_deltalake #
write_deltalake(table: Union[str, Path, DeltaTable, UnityCatalogTable], partition_cols: list[str] | None = None, mode: Literal['append', 'overwrite', 'error', 'ignore'] = 'append', schema_mode: Literal['merge', 'overwrite'] | None = None, name: str | None = None, description: str | None = None, configuration: Mapping[str, str | None] | None = None, custom_metadata: dict[str, str] | None = None, dynamo_table_name: str | None = None, allow_unsafe_rename: bool = False, io_config: IOConfig | None = None, checkpoint: IdempotentCommit | None = None) -> DataFrame
Writes the DataFrame to a Delta Lake table, returning a new DataFrame with the operations that occurred.
write_deltalake supports checkpointing via the checkpoint= parameter. For the conceptual overview, see the Checkpointing guide.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table | Union[str, Path, DeltaTable, UnityCatalogTable] | Destination Delta Lake Table or table URI to write dataframe to. | required |
partition_cols | List[str] | How to subpartition each partition further. If table exists, expected to match table's existing partitioning scheme, otherwise creates the table with specified partition columns. Defaults to None. | None |
mode | str | Operation mode of the write. | 'append' |
schema_mode | str | Schema mode of the write. If set to | None |
name | str | User-provided identifier for this table. | None |
description | str | User-provided description for this table. | None |
configuration | Mapping[str, Optional[str]] | A map containing configuration options for the metadata action. | None |
custom_metadata | Dict[str, str] | Custom metadata to add to the commit info. Keys with prefix | None |
dynamo_table_name | str | Name of the DynamoDB table to use when explicitly opting into DynamoDB locking for S3 writes. Modern supported | None |
allow_unsafe_rename | bool | Whether to explicitly allow unsafe rename when writing to S3 or local disk. Defaults to False. | False |
io_config | IOConfig | configurations to use when interacting with remote storage. | None |
checkpoint | IdempotentCommit | Bundled checkpoint store + idempotence key for an idempotent commit. When provided, the Delta commit's | None |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | The operations that occurred with this write. |
Note
This call is blocking and will execute the DataFrame when called.
When checkpoint is provided and write_deltalake raises after the Delta commit landed (e.g. a transient failure during the post-commit mark_committed bookkeeping), the user data is already durable in Delta. The next call with the same IdempotentCommit (same idempotence key) will detect the commit via its marker, finish the bookkeeping, and exit cleanly without producing a duplicate commit.
The returned DataFrame reflects only this call's writes — empty (0 rows) on a recovery short-circuit, populated when a new commit lands. Useful for run-to-run diffing.
Idempotence-key contract — read carefully:
- Same key + different inputs → silent no-op (data loss). The destination already has a commit tagged with the key, so nothing new is written.
- Different key + same retry → duplicate commit. The destination won't recognize the prior attempt and will commit again. Idempotence is broken.
The orchestrator pattern (run-id supplied from upstream DAG context) avoids both naturally.
Crashed runs leave orphan data files at the table location. Delta writes parquet files before the commit, so files from crashed attempts are not referenced by any commit but the bytes remain on disk.
Examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
Source code in daft/dataframe/dataframe.py
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 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 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 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 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 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 | |
write_iceberg #
write_iceberg(table: Table, mode: str = 'append', io_config: IOConfig | None = None, snapshot_properties: dict[str, str] | None = None, checkpoint: IdempotentCommit | None = None, overwrite_filter: str | Expression | None = None, validate_overwrite_filter: bool = True) -> DataFrame
Writes the DataFrame to an Iceberg table, returning a new DataFrame with the operations that occurred.
Can be run in either append or overwrite mode which will either appends the rows in the DataFrame or will delete the existing rows and then append the DataFrame rows respectively.
In overwrite mode, overwrite_filter restricts the delete to the rows matching a predicate, which is how a static partition overwrite is expressed: pass a predicate over the partition columns (e.g. "dt = '2024-01-01'") to replace only the matching partitions.
write_iceberg supports checkpointing via the checkpoint= parameter. For the conceptual overview, see the Checkpointing guide.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table | Table | Destination PyIceberg Table to write dataframe to. | required |
mode | str | Operation mode of the write. | 'append' |
io_config | IOConfig | A custom IOConfig to use when accessing Iceberg object storage data. If provided, configurations set in | None |
snapshot_properties | dict[str, str] | Optional snapshot properties to set while writing to the table. Keys with prefix | None |
checkpoint | IdempotentCommit | Bundled checkpoint store + idempotence key for an idempotent commit. When provided, the snapshot summary is tagged with | None |
overwrite_filter | str | Expression | Only valid with | None |
validate_overwrite_filter | bool | Only used alongside | True |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | The operations that occurred with this write. |
Note
This call is blocking and will execute the DataFrame when called.
overwrite_filter behavior:
- The filter selects which rows are deleted. By default the rows being written must match it as well, so an overwrite cannot leave behind rows its delete did not cover. Pass
validate_overwrite_filter=Falseto skip that check, matching PyIceberg'sTable.overwrite. - The check reads the written files' partition values and column statistics, not the rows. Statistics only ever widen, so it may reject a write it cannot prove but never accepts an unmatched row. Equality over a non-partition column whose values exceed the bounds truncation length (16 bytes by default), or over a column with statistics disabled, is not provable.
- The check runs before the commit, so a rejected write leaves the table unchanged. The staged data files stay at the warehouse location.
- A filter aligned with partition boundaries is a metadata-only delete. Anything finer makes PyIceberg fall back to copy-on-write and rewrite the partially matched data files.
DELETErows in the returned DataFrame are the data files overlapping the filter in the pre-write snapshot. A partially matched file is rewritten rather than removed.
When checkpoint is provided and write_iceberg raises after the catalog commit landed (e.g. a transient failure during the post-commit mark_committed bookkeeping), the user data is already durable in Iceberg. The next call with the same IdempotentCommit (same idempotence key) will detect the snapshot via its marker, finish the bookkeeping, and exit cleanly without producing a duplicate snapshot.
The returned DataFrame reflects only this call's writes — empty (0 rows) on a recovery short-circuit, populated when a new snapshot lands. Useful for run-to-run diffing.
Idempotence-key contract — read carefully:
- Same key + different inputs → silent no-op (data loss). The destination already has a snapshot tagged with the key, so nothing new is written.
- Different key + same retry → duplicate snapshot. The destination won't recognize the prior attempt and will commit again. Idempotence is broken.
The orchestrator pattern (run-id supplied from upstream DAG context) avoids both naturally.
Crashed runs leave orphan data files at the warehouse location. Iceberg writes stage data files before the snapshot commit, so files from crashed attempts are not referenced by any snapshot but the bytes remain on disk.
Examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
Source code in daft/dataframe/dataframe.py
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 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 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 | |
write_lance #
write_lance(uri: str | Path | None = None, mode: Literal['create', 'append', 'overwrite', 'insert_overwrite', 'merge'] = 'create', io_config: IOConfig | None = None, schema: Union[Schema, Schema] | None = None, left_on: str | None = None, right_on: str | None = None, *, overwrite_where: str | None = None, table_id: list[str] | None = None, namespace_impl: str | None = None, namespace_properties: dict[str, str] | None = None, **kwargs: Any) -> DataFrame
Writes the DataFrame to a Lance table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri | str | Path | None | The URI of the Lance table to write to. Accepts a local path or an object-store URI like "s3://bucket/path". Mutually exclusive with the namespace parameters. | None |
mode | Literal['create', 'append', 'overwrite', 'insert_overwrite', 'merge'] | The write mode. One of "create", "append", "overwrite", or "insert_overwrite". | 'create' |
io_config | IOConfig | configurations to use when interacting with remote storage. | None |
schema | Schema | Schema | Desired schema to enforce during write. - If omitted, Daft will use the DataFrame's current schema. - If a pyarrow.Schema is provided, Daft will enforce the field order, types, and nullability by casting the data to the provided schema prior to write. Table-level (dataset) metadata present on the pyarrow schema is preserved during create/overwrite. - If the target Lance dataset already exists, the data will be cast to the existing table schema to ensure compatibility unless | None |
left_on/right_on | Deprecated with | required | |
overwrite_where | str | None | SQL predicate selecting rows to replace. Required only for | None |
table_id | list[str] | None | Table identifier within a Lance Namespace, e.g. | None |
namespace_impl | str | None | Lance Namespace implementation, such as | None |
namespace_properties | dict[str, str] | None | Properties for connecting to the namespace. | None |
**kwargs | Any | Additional keyword arguments to pass to the Lance writer. daft-lance validates these against a fixed set; an unrecognized argument raises | {} |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | A DataFrame containing metadata about the written Lance table, such as number of fragments, number of deleted rows, number of small files, and version. |
Raises:
| Type | Description |
|---|---|
TypeError | If |
ValueError | When appending and the data schema cannot be cast to the existing table schema |
Examples:
1 2 3 4 5 6 | |
╭───────────────┬──────────────────┬─────────────────┬─────────╮
│ num_fragments ┆ num_deleted_rows ┆ num_small_files ┆ version │
│ --- ┆ --- ┆ --- ┆ --- │
│ Int64 ┆ Int64 ┆ Int64 ┆ Int64 │
╞═══════════════╪══════════════════╪═════════════════╪═════════╡
│ 1 ┆ 0 ┆ 1 ┆ 1 │
╰───────────────┴──────────────────┴─────────────────┴─────────╯
(Showing first 1 of 1 rows)
╭───────╮
│ a │
│ --- │
│ Int64 │
╞═══════╡
│ 1 │
├╌╌╌╌╌╌╌┤
│ 2 │
├╌╌╌╌╌╌╌┤
│ 3 │
├╌╌╌╌╌╌╌┤
│ 4 │
╰───────╯
(Showing first 4 of 4 rows)
╭───────────────┬──────────────────┬─────────────────┬─────────╮
│ num_fragments ┆ num_deleted_rows ┆ num_small_files ┆ version │
│ --- ┆ --- ┆ --- ┆ --- │
│ Int64 ┆ Int64 ┆ Int64 ┆ Int64 │
╞═══════════════╪══════════════════╪═════════════════╪═════════╡
│ 1 ┆ 0 ┆ 1 ┆ 2 │
╰───────────────┴──────────────────┴─────────────────┴─────────╯
(Showing first 1 of 1 rows) Source code in daft/dataframe/dataframe.py
2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 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 2551 2552 2553 2554 2555 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 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 | |
write_sql #
write_sql(table_name: str, conn: str | Callable[[], Connection], write_mode: Literal['append', 'overwrite', 'fail'] = 'append', column_types: dict[str, Any] | None = None, non_primitive_handling: Literal['bytes', 'str', 'error'] | None = None) -> DataFrame
Write the DataFrame to a SQL database and return write metrics.
The write is executed via :meth:daft.DataFrame.write_sink using an internal :class:daft.io._sql.SQLDataSink.
Primitive columns (ints, floats, bools, strings, binary, dates, timestamps) are written by converting to a pandas DataFrame and calling :meth:pandas.DataFrame.to_sql, letting SQLAlchemy or column_types choose concrete SQL types.
Non-primitive columns (lists, structs, maps, tensors, images, embeddings, python objects, etc.) are normalized according to non_primitive_handling (default None behaves like "str"): "str" serializes values to text (JSON for arrays/maps and other containers, str(..) otherwise), "bytes" writes UTF-8 bytes of that text, and "error" fails if such columns are present.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table_name | str | Name of the table to write to. | required |
conn | str | Callable[[], Connection] | Connection string or factory. | required |
write_mode | str | Mode to write to the table. "append", "overwrite", or "fail". Defaults to "append". | 'append' |
column_types | Optional[Dict[str, Any]] | Optional mapping from column names to SQLAlchemy types to use when creating the table or casting columns. Passed through to the underlying SQL engine when creating or writing the table. | None |
non_primitive_handling | Literal['bytes', 'str', 'error'] | None | Controls how non-primitive columns are normalized before reaching SQL; default | None |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | A single-row DataFrame containing aggregate write metrics with columns |
Warning
This features is early in development and will likely experience API changes.
Note
Primitive columns still rely on pandas/SQLAlchemy (or column_types) for concrete SQL types, while non-primitive columns are pre-normalized in Python according to non_primitive_handling before reaching the SQL driver.
Examples:
Write to a SQL table using a database URL and explicit SQLAlchemy dtypes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
Write to a SQL table using a SQLAlchemy connection factory and dtypes:
1 2 3 4 | |
Write to a SQL table using a database URL with column_types=None to rely on inferred types:
1 2 | |
Source code in daft/dataframe/dataframe.py
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 | |
write_bigtable #
write_bigtable(project_id: str, instance_id: str, table_id: str, row_key_column: str, column_family_mappings: dict[str, str], client_kwargs: dict[str, Any] | None = None, write_kwargs: dict[str, Any] | None = None, serialize_incompatible_types: bool = True) -> DataFrame
Write a DataFrame into a Google Cloud Bigtable table.
Bigtable only accepts datatypes that can be converted to bytes in cells (for more details, please consult the Bigtable documentation: https://cloud.google.com/bigtable/docs/overview#data-types). By default, write_bigtable automatically serializes incompatible types to JSON. This can be disabled by setting auto_convert=False.
This data sink transforms each row of the dataframe into Bigtable rows. A row key is always required. The row_key_column parameter can be used to specify the column name to use for the row key.
Every column must also belong to a column family. The column_family_mappings parameter can be used to specify the column family to use for each column. For example, if you have a column "name" and a column "age", you can specify a "user_data" column family by passing a dictionary like {"name": "user_data", "age": "user_data"}.
EXPERIMENTAL: This features is early in development and will change.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
project_id | str | The Google Cloud project ID. | required |
instance_id | str | The Bigtable instance ID. | required |
table_id | str | The table to write to. | required |
row_key_column | str | Column name for the row key. | required |
column_family_mappings | dict[str, str] | Mapping of column names to column families. | required |
client_kwargs | dict[str, Any] | None | Optional dictionary of arguments to pass to the Bigtable Client constructor. | None |
write_kwargs | dict[str, Any] | None | Optional dictionary of arguments to pass to the Bigtable MutationsBatcher. | None |
serialize_incompatible_types | bool | Whether to automatically convert non-bytes/int values to Bigtable-compatible formats. If False, will raise an error for unsupported types. Defaults to True. | True |
Source code in daft/dataframe/dataframe.py
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 2835 | |
write_clickhouse #
write_clickhouse(table: str, *, host: str, port: int | None = None, user: str | None = None, password: str | None = None, database: str | None = None, client_kwargs: dict[str, Any] | None = None, write_kwargs: dict[str, Any] | None = None) -> DataFrame
Writes the DataFrame to a ClickHouse table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table | str | Name of the ClickHouse table to write to. | required |
host | str | ClickHouse host. | required |
port | int | None | ClickHouse port. | None |
user | str | None | ClickHouse user. | None |
password | str | None | ClickHouse password. | None |
database | str | None | ClickHouse database. | None |
client_kwargs | dict[str, Any] | None | Optional dictionary of arguments to pass to the ClickHouse client constructor. | None |
write_kwargs | dict[str, Any] | None | Optional dictionary of arguments to pass to the ClickHouse write() method. | None |
Examples:
1 2 3 | |
╭────────────────────┬─────────────────────╮
│ total_written_rows ┆ total_written_bytes │
│ --- ┆ --- │
│ Int64 ┆ Int64 │
╞════════════════════╪═════════════════════╡
│ 4 ┆ 32 │
╰────────────────────┴─────────────────────╯ Source code in daft/dataframe/dataframe.py
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 2749 2750 2751 2752 2753 2754 2755 2756 2757 | |
write_huggingface #
write_huggingface(repo: str, split: str = 'train', data_dir: str = 'data', revision: str = 'main', overwrite: bool = False, commit_message: str = 'Upload dataset using Daft', commit_description: str | None = None, io_config: IOConfig | None = None) -> DataFrame
Write a DataFrame into a Hugging Face dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo | str | The ID of the repository to push to in the following format: | required |
split | str | The name of the split that will be given to that dataset. | 'train' |
data_dir | str | Directory of the uploaded data files. | 'data' |
revision | str | Branch to push the uploaded files to. | 'main' |
overwrite | bool | Whether to overwrite or append. | False |
commit_message | str | Message to commit while pushing. | 'Upload dataset using Daft' |
commit_description | str | None | Description of the commit that will be created. | None |
io_config | IOConfig | None | Configurations to use when interacting with remote storage. | None |
Source code in daft/dataframe/dataframe.py
2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 | |
write_turbopuffer #
write_turbopuffer(namespace: str | Expression, api_key: str | None = None, region: str | None = None, distance_metric: Literal['cosine_distance', 'euclidean_squared'] | None = None, schema: dict[str, Any] | None = None, id_column: str | None = None, vector_column: str | None = None, client_kwargs: dict[str, Any] | None = None, write_kwargs: dict[str, Any] | None = None) -> DataFrame
Writes the DataFrame to a Turbopuffer namespace.
This method transforms each row of the dataframe into a turbopuffer document. This means that an id column is always required. Optionally, the id_column parameter can be used to specify the column name to used for the id column. Note that the column with the name specified by id_column will be renamed to "id" when written to turbopuffer.
A vector column is required if the namespace has a vector index. Optionally, the vector_column parameter can be used to specify the column name to used for the vector index. Note that the column with the name specified by vector_column will be renamed to "vector" when written to turbopuffer.
All other columns become attributes.
The namespace parameter can be either a string (for a single namespace) or an expression (for multiple namespaces). When using an expression, the data will be partitioned by the computed namespace values and written to each namespace separately.
For more details on parameters, please see the turbopuffer documentation: https://turbopuffer.com/docs/write
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace | str | Expression | The namespace to write to. Can be a string for a single namespace or an expression for multiple namespaces. | required |
api_key | str | None | Turbopuffer API key. | None |
region | str | None | Turbopuffer region. | None |
distance_metric | Literal['cosine_distance', 'euclidean_squared'] | None | Distance metric for vector similarity ("cosine_distance", "euclidean_squared"). | None |
schema | dict[str, Any] | None | Optional manual schema specification. | None |
id_column | str | None | Optional column name for the id column. The data sink will automatically rename the column to "id" for the id column. | None |
vector_column | str | None | Optional column name for the vector index column. The data sink will automatically rename the column to "vector" for the vector index. | None |
client_kwargs | dict[str, Any] | None | Optional dictionary of arguments to pass to the Turbopuffer client constructor. Explicit arguments (api_key, region) will be merged into client_kwargs. | None |
write_kwargs | dict[str, Any] | None | Optional dictionary of arguments to pass to the namespace.write() method. Explicit arguments (distance_metric, schema) will be merged into write_kwargs. | None |
Source code in daft/dataframe/dataframe.py
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 | |
write_sink #
Writes the DataFrame to the given DataSink.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sink | DataSink[WriteResultType] | The DataSink to write to. | required |
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | DataFrame | A dataframe from the micropartition returned by the DataSink's |
Note
This call is blocking and will execute the DataFrame when called
Source code in daft/dataframe/dataframe.py
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 | |
User-Defined#
Daft supports diverse input sources and output sinks, this section covers lower-level APIs which we are evolving for more advanced usage.
Warning
These APIs are considered experimental.
DataSource #
DataSource is a low-level interface for reading data into DataFrames.
When a DataSource is read, it is split into multiple tasks which can be distributed for parallel processing. Each task is responsible for reading a specific portion of the data (e.g., a file partition, a range of rows, or a subset of a database table) and converting it into RecordBatches. Implementations should ensure that tasks are appropriately sized to balance parallelism.
Warning
This API is early in its development and is subject to change.
Methods:
| Name | Description |
|---|---|
get_clustering_keys | Declares how this source's output is distributed at execution time. |
get_partition_fields | Returns the partitioning fields for this data source. |
get_tasks | Yields tasks as they are discovered. Called during execution, not planning. |
read | Reads a DataSource as a DataFrame. |
supports_count_pushdown | Returns true if this source can absorb a count aggregation pushdown. |
Attributes:
| Name | Type | Description |
|---|---|---|
name | str | Returns the source name which is useful for debugging. |
schema | Schema | Returns the schema shared by each task's record batches. |
get_clustering_keys #
get_clustering_keys() -> ClusteringKeys | None
Declares how this source's output is distributed at execution time.
Returning None (the default) means the source makes no clustering guarantee, so downstream operators will shuffle as usual. Override this to return :class:~daft.io.clustering.ClusteringKeys when the source can make one of the following guarantees:
- :meth:
~daft.io.clustering.ClusteringKeys.hash— when the source knows its output is already hash-partitioned — e.g. when eachDataSourceTaskcorresponds to exactly one(producer, hour)group - allows the optimizer to skip hash shuffles - :meth:
~daft.io.clustering.ClusteringKeys.range— when each task covers a non-overlapping range of values for the declared keys. Passdescending=Trueif partition order is high-to-low. Allows the optimizer to skip range shuffles.
Note that this is distinct from :meth:get_partition_fields, which describes on-disk storage layout for per-row value injection, not execution-time clustering.
Warning
This API is early in its development and is subject to change.
Source code in daft/io/source.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | |
get_partition_fields #
get_partition_fields() -> list[PartitionField]
Returns the partitioning fields for this data source.
Source code in daft/io/source.py
50 51 52 | |
get_tasks #
get_tasks(pushdowns: Pushdowns) -> AsyncIterator[DataSourceTask]
Yields tasks as they are discovered. Called during execution, not planning.
Source code in daft/io/source.py
93 94 95 96 97 98 99 | |
read #
read() -> DataFrame
Reads a DataSource as a DataFrame.
Source code in daft/io/source.py
101 102 103 104 105 106 107 108 109 | |
supports_count_pushdown #
supports_count_pushdown() -> bool
Returns true if this source can absorb a count aggregation pushdown.
When true, the optimizer may replace a full scan + count with a single task whose pushdowns carry the count aggregation; get_tasks is then responsible for producing the count result (e.g. from catalog metadata) instead of scanning data files.
A source that returns true must honor the rest of the pushdowns when it produces that count. In particular partition_filters may be set while filters is None, since the optimizer moves predicates it resolved against partition values alone out of filters; counting without applying them reports rows the query excluded.
Source code in daft/io/source.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | |
DataSourceTask #
DataSourceTask represents a partition of data that can be processed independently.
Warning
This API is early in its development and is subject to change.
Methods:
| Name | Description |
|---|---|
mcap | Create a task that reads an MCAP file using the native reader. |
parquet | Create a task that reads a Parquet file using the native reader. |
read | Yields record batches. Called from an async execution context. |
Attributes:
| Name | Type | Description |
|---|---|---|
schema | Schema | Returns the schema of the record batches produced by this task. |
mcap #
mcap(path: str, schema: Schema, *, mcap_config: McapSourceConfig | None = None, pushdowns: Pushdowns | None = None, num_rows: int | None = None, size_bytes: int | None = None, stats: RecordBatch | None = None, storage_config: StorageConfig | None = None) -> DataSourceTask
Create a task that reads an MCAP file using the native reader.
Source code in daft/io/source.py
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 | |
parquet #
parquet(path: str, schema: Schema, *, parquet_config: ParquetSourceConfig | None = None, pushdowns: Pushdowns | None = None, num_rows: int | None = None, size_bytes: int | None = None, partition_values: RecordBatch | None = None, stats: RecordBatch | None = None, storage_config: StorageConfig | None = None, iceberg_delete_files: list[str] | None = None) -> DataSourceTask
Create a task that reads a Parquet file using the native reader.
This is the recommended way to create scan tasks for Parquet files when building custom DataSource implementations (e.g., catalog connectors like Iceberg or Paimon).
Partition pruning is the DataSource's responsibility — decide which files to yield in get_tasks rather than relying on the task factory to filter them out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path | str | Path or URI of the Parquet file (e.g., | required |
schema | Schema | Schema to read the file with. | required |
parquet_config | ParquetSourceConfig | None | Optional Parquet reader configuration. Defaults to :class: | None |
pushdowns | Pushdowns | None | Query pushdowns (filters, column projection, limit). Pass through the pushdowns received by DataSource.get_tasks. | None |
num_rows | int | None | Exact row count, if known. Enables metadata-only optimizations. | None |
size_bytes | int | None | On-disk file size in bytes. Used for task coalescing heuristics. | None |
partition_values | RecordBatch | None | Single-row RecordBatch of partition column values to inject. | None |
stats | RecordBatch | None | Column statistics as a RecordBatch for predicate pushdown evaluation. | None |
storage_config | StorageConfig | None | Optional StorageConfig for IO credentials/settings. Defaults to | None |
iceberg_delete_files | list[str] | None | Optional list of Iceberg positional delete file paths to apply to this file, per the Iceberg spec (https://iceberg.apache.org/spec/#position-delete-files). | None |
Example
class MyCatalogSource(DataSource): async def get_tasks(self, pushdowns): for file in self.list_files(): yield DataSourceTask.parquet( path=file.uri, schema=self.schema, pushdowns=pushdowns, num_rows=file.row_count, size_bytes=file.size_bytes, )
Returns:
| Type | Description |
|---|---|
DataSourceTask | A DataSourceTask executed by the native Parquet reader. |
Source code in daft/io/source.py
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 | |
read #
read() -> AsyncIterator[RecordBatch]
Yields record batches. Called from an async execution context.
Subclasses must override this method. Each yielded batch must match :attr:schema.
Source code in daft/io/source.py
125 126 127 128 129 130 131 132 133 134 | |
DataSink #
Interface for writing data to a sink that is not built-in.
When a DataFrame is written using the .write_sink() method, the following sequence occurs:
- The sink's
.start()method is called once on the driver at the beginning of the write process, before the sink is serialized to worker tasks. - The DataFrame is executed, and its output is split into micropartitions.
- The sink's
.write()method is invoked on each micropartition, potentially in parallel and distributed across multiple tasks or workers. - After all writes complete, the resulting
WriteOutputobjects are gathered on a single node. - The
.finalize()method is then called with all write outputs to produce a finalMicroPartition.
Warning
This API is early in its development and is subject to change.
Methods:
| Name | Description |
|---|---|
finalize | Finalizes the write process and returns a resulting micropartition. |
name | Optional custom sink name. |
safe_write | This method wraps the abstract |
schema | The expected schema for the micropartition returned by the |
start | Optional callback for when a write operation begins. |
write | Writes a stream of micropartitions to the sink. |
finalize #
finalize(write_results: list[WriteResult[WriteResultType]]) -> MicroPartition
Finalizes the write process and returns a resulting micropartition.
For example, this can be used to merge, summarize, or commit the results of individual writes into a single output micropartition.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
write_results | list[WriteResult[WriteResultType]] | The list of results from the calls to | required |
Returns:
| Name | Type | Description |
|---|---|---|
MicroPartition | MicroPartition | A final, single micropartition representing the result of all writes. |
Source code in daft/io/sink.py
99 100 101 102 103 104 105 106 107 108 109 110 111 112 | |
name #
name() -> str
Optional custom sink name.
Source code in daft/io/sink.py
48 49 50 | |
safe_write #
safe_write(micropartitions: Iterator[MicroPartition]) -> Iterator[WriteResult[WriteResultType]]
This method wraps the abstract write() method with a try block to reraise potentially unserializable exceptions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
micropartitions | Iterator[MicroPartition] | An iterator of micropartitions to be written. | required |
Returns:
| Type | Description |
|---|---|
Iterator[WriteResult[WriteResultType]] | Iterator[WriteResult[WriteResultType]]: An iterator of write results wrapped in a WriteOutput. |
Raises:
| Type | Description |
|---|---|
Exception | Any exception that occurs during the write operation. |
Source code in daft/io/sink.py
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | |
schema #
schema() -> Schema
The expected schema for the micropartition returned by the .finalize() method of this DataSink.
If this given schema does not match the actual schema of the micropartition at runtime, we throw an error.
Source code in daft/io/sink.py
52 53 54 55 56 57 58 | |
start #
start() -> None
Optional callback for when a write operation begins.
For example, this can be used to initialize resources, open connections, start a transaction etc. The default implementation does nothing.
Source code in daft/io/sink.py
60 61 62 63 64 65 | |
write #
write(micropartitions: Iterator[MicroPartition]) -> Iterator[WriteResult[WriteResultType]]
Writes a stream of micropartitions to the sink.
This method should handle the ingestion of each micropartition and yield a result (e.g. metadata) for each successful write.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
micropartitions | Iterator[MicroPartition] | An iterator of micropartitions to be written. | required |
Returns:
| Type | Description |
|---|---|
Iterator[WriteResult[WriteResultType]] | Iterator[WriteResult[WriteResultType]]: An iterator of write results wrapped in a WriteOutput. |
Source code in daft/io/sink.py
67 68 69 70 71 72 73 74 75 76 77 78 79 80 | |
WriteResult #
WriteResult(result: WriteResultType, bytes_written: int, rows_written: int)
Wrapper for result of the DataSink's .write() method.
Attributes:
| Name | Type | Description |
|---|---|---|
result | WriteResultType | The result from the write operation |
bytes_written | int | Size of the written data in bytes |
rows_written | int | Number of rows written |
Pushdowns#
Daft supports predicate, projection, and limit pushdowns.
Pushdowns #
Pushdowns(filters: Expression | None = None, partition_filters: Expression | None = None, columns: list[str] | None = None, limit: int | None = None, aggregation: Expression | None = None)
Pushdowns are sent to scan sources during query planning.
Attributes:
| Name | Type | Description |
|---|---|---|
filters | Expression | None | Optional filter predicate to apply to rows. |
partition_filters | Expression | None | Optional partition filter predicate to apply to partitions or files. |
columns | list[str] | None | Optional list of column names to project. |
limit | int | None | Optional limit on the number of rows to return. |
aggregation | Expression | None | Optional aggregation expression for count pushdown. |
Methods:
| Name | Description |
|---|---|
empty | |
filter_required_column_names | Returns a set of field names that are required by the filter predicate. |
empty #
empty() -> Pushdowns
Source code in daft/io/pushdowns.py
59 60 61 | |
filter_required_column_names #
filter_required_column_names() -> set[str]
Returns a set of field names that are required by the filter predicate.
Source code in daft/io/pushdowns.py
55 56 57 | |
ScanOperator #
ScanOperator is the legacy python DataSource ABC and is being migrated to daft.io.source.DataSource.
In Daft 0.5.0 we will change the pushdown parameter from daft.daft.Pushdowns to daft.io.Pushdowns. For now, please use Pushdowns._from_pypushdowns(py_pushdowns) to convert the rust expressions to this python pushdowns class.
Methods:
| Name | Description |
|---|---|
as_pushdown_filter | Returns this scan operator as a SupportsPushdownFilters if it supports pushdown filters. |
can_absorb_filter | Returns true if this scan can accept predicate pushdowns. |
can_absorb_limit | Returns true if this scan can accept limit pushdowns. |
can_absorb_select | Returns true if this scan can accept projection pushdowns. |
display_name | Returns a human-readable name for this scan operator. |
multiline_display | Returns a multi-line string representation of this scan operator. |
partitioning_keys | Returns the partitioning keys for this data source. |
schema | Returns the schema of the data source. |
supports_count_pushdown | Returns true if this scan can accept count pushdowns. |
to_scan_tasks | Converts this scan operator into scan tasks with the given pushdowns. |
as_pushdown_filter #
as_pushdown_filter() -> SupportsPushdownFilters | None
Returns this scan operator as a SupportsPushdownFilters if it supports pushdown filters.
Source code in daft/io/scan.py
79 80 81 | |
can_absorb_filter #
can_absorb_filter() -> bool
Returns true if this scan can accept predicate pushdowns.
Source code in daft/io/scan.py
54 55 56 57 | |
can_absorb_limit #
can_absorb_limit() -> bool
Returns true if this scan can accept limit pushdowns.
Source code in daft/io/scan.py
59 60 61 62 | |
can_absorb_select #
can_absorb_select() -> bool
Returns true if this scan can accept projection pushdowns.
Source code in daft/io/scan.py
64 65 66 67 | |
display_name #
display_name() -> str
Returns a human-readable name for this scan operator.
Source code in daft/io/scan.py
44 45 46 47 | |
multiline_display #
multiline_display() -> list[str]
Returns a multi-line string representation of this scan operator.
Source code in daft/io/scan.py
69 70 71 72 | |
partitioning_keys #
partitioning_keys() -> list[PyPartitionField]
Returns the partitioning keys for this data source.
Source code in daft/io/scan.py
49 50 51 52 | |
schema #
schema() -> Schema
Returns the schema of the data source.
Source code in daft/io/scan.py
39 40 41 42 | |
supports_count_pushdown #
supports_count_pushdown() -> bool
Returns true if this scan can accept count pushdowns.
Source code in daft/io/scan.py
83 84 85 | |
to_scan_tasks #
to_scan_tasks(pushdowns: PyPushdowns) -> Iterator[ScanTask]
Converts this scan operator into scan tasks with the given pushdowns.
Source code in daft/io/scan.py
74 75 76 77 | |