Skip to content

[EXPERIMENTAL] Add general from_dataset API to DataFrame - #8944

Closed
rjzamora wants to merge 20 commits into
dask:mainfrom
rjzamora:engine-expansion
Closed

rjzamora wants to merge 20 commits into
dask:mainfrom
rjzamora:engine-expansion

Conversation

@rjzamora

Copy link
Copy Markdown
Member

WARNING: Very much a WIP - Do not merge!

This PR adds an experimental from_dataset API for reading general on-disk tabular data into a Dask-DataFrame collection. This PR only adds engines based on the pyarrow.dataset API, but they already support Parquet, ORC, Feather / Arrow IPC, and CSV (and other engines can certainly be added). My primary goal is to come up with a single scalable design for tabular data formats like Parquet. I am hoping to use this code base as a "sandbox" for exploring the best default settings and algorithms for reading formats like Parquet.

One possible (but far-off) outcome of this work is that the current read_parquet implementation could be refactored to simply call from_dataset. However, such a move would require us to (1) revise/simplify default arguments and features in read_parquet until they are aligned with those in from_dataset, and (2) ultimately deprecate the existing Engine classes used in dd.io.parquet (no small task).

So... Why not just explore defaults and algorithms in the existing read_parquet code?

The simple answer to this is that the current read_parquet design is no-longer well-suited for the Engine classes it is meant to support. When the "pluggable" Engine design was first implemented (nearly three years ago), there was no pyarrow.dataset API, and even cudf and fastparquet had very different features and limitations. For example, at the time, none of the Engines supported row-group or row-wise filtering, and so the engine-agnostic read_parquet code was written in a way that is inefficient when the engine actual can take care of file/row-group filtering. Another “pain point” is that requiring the Engine to expose multiple “static”/“class” methods requires a giant dictionary of options to be passed all over the code base (creating an apparent “spaghetti code” situation).

In contrast to the current read_parquet organization, I think it makes a lot more sense for the Engine to operate as an “object” (not as a class), and for the engine-agnostic code to simply ask the engine to return everything it needs to generate the new collection (an IO function, meta, a list of IO-function inputs, and divisions). This way, all engine-specific options can be clearly documented and validated at the engine level, and the engine can use temporary “state” to avoid passing around a laundry-list of options everywhere.

To clarify, I propose that the top-level function only support a very limited set of options. In fact, I don’t believe that the engine-agnostic code should do any path/filesystem handling at all. The top-level API should only include a minimum set of common options (and the engine can still raise an error for something like calculate_divisions=True for formats without min/max statistics support):



def from_dataset(
    path,
    columns=None,
    filters=None,
    index=None,
    calculate_divisions=False,  # To avoid the need for `gather_statistics`
    engine="pyarrow",
    **engine_options,  # ALL other options belong to the engine itself
):

For example, the current (still in flux) docstring is:

    """Create a Dask-DataFrame collection from a stored dataset

    WARNING: This API is completely unstable and experimental!!

    Parameters
    ----------
    path : str or list[str] or list[list[str]]
        Source directory for data, or path(s) to individual parquet files.
        Prefix with a protocol like ``s3://`` to read from alternative
        filesystems. To read from multiple files you can pass a list of paths,
        with the caveat that they must all have the same protocol. In order to
        directly map groups of files to output dataframe partitions, ``path``
        may also be a list of path lists. In this case, the paths within each
        inner list will be aggregated into the same output partition.
    columns : str or list, default None
        Field name(s) to read in as columns in the output. By default all
        non-index fields will be read (as determined by the pandas parquet
        metadata, if present). Provide a single field name instead of a list to
        read in the data as a Series.
    filters : Union[List[Tuple[str, str, Any]], List[List[Tuple[str, str, Any]]]], default None
        List of filters to apply, like ``[[('col1', '==', 0), ...], ...]``.
        Predicates should be expressed in disjunctive normal form (DNF). This
        means that the innermost tuple describes a single column predicate.
        These inner predicates are combined with an AND conjunction into a
        larger predicate. The outer-most list then combines all of the
        combined filters with an OR disjunction.
    index : str or False, default None
        Field name to use as the output frame index. By default, the index may
        be inferred from file metadata (if present). Use False to read all
        fields as columns.
    calculate_divisions : bool, default False
        Whether parquet metadata should be used to calculate output divisions.
        This argument will be ignored if there is no active index column.
        WARNING: Setting this option to True may be expensive for large datasets
        stored in remote storage!
    engine : str or DatasetEngine, default 'pyarrow'
        DatasetEngine class to use. Defaults to `ArrowDataset`, which supports
        “parquet”, “ipc”/”arrow”/”feather”, “csv”, and “orc” (the specific
        file format should be specified with the ``format=`` argument). For
        Parquet-formatted data, `engine="pyarrow-parquet"` is recommended
        (which is the same as `engine=ArrowParquetDataset`).
    **engine_options :
        Engine-specific options to use to initialize ``engine``.

    See Also
    --------
    dask.dataframe.io.dataset.arrow.ArrowDataset
    dask.dataframe.io.dataset.arrow.ArrowParquetDataset
    """

@rjzamora

Copy link
Copy Markdown
Member Author

cc @jcrist - Do you think it would be useful to use something like this to explore better defaults/algorithms for read_parquet?

@rjzamora

Copy link
Copy Markdown
Member Author

@jorisvandenbossche - It looks like there are two things missing from pyarrow.dataset for format="orc":

  1. To handle large orc files, we will need the ORC equivalent of fragment.split_by_row_group (perhaps split_by_stripe?)
  2. In order to avoid passing Fragment objects in the graph (which seems to make the graph much larger for big reads), we will need to have a access to a Fragment.path attributed or orc-backed data (in the same way we can use ParquetFileFragment.path for parquet).

Am I correct that these features are missing? If so, I can file issues in Jira

@jorisvandenbossche

Copy link
Copy Markdown
Member

To handle large orc files, we will need the ORC equivalent of fragment.split_by_row_group (perhaps split_by_stripe?)

I think we only discussed that previously on github (apache/arrow#10991 (comment)), but based on a quick search there isn't yet a JIRA about it (but it has been in the back of my head to try to plan this for the next release)

we will need to have a access to a Fragment.path attributed or orc-backed data (in the same way we can use ParquetFileFragment.path for parquet).

The path attribute is defined on the base FileFragment class, and not on the ParquetFileFragment subclass (in contrast to eg the split_by_row_group or subset methods). So ORC fragments should normally also have that attribute available. Did you observe otherwise?

@rjzamora

Copy link
Copy Markdown
Member Author

The path attribute is defined on the base FileFragment class, and not on the ParquetFileFragment subclass (in contrast to eg the split_by_row_group or subset methods). So ORC fragments should normally also have that attribute available. Did you observe otherwise?

Right - I don't get FileFragment objects (I get pyarrow._dataset.Fragment):

import pyarrow as pa
import pyarrow.dataset as ds
import pyarrow.orc as pa_orc

print("PyArrow Version:", pa.__version__)

table = pa.table([
    pa.array([1, 2]),
    pa.array(["a", "b"])
], names=["int", "str"])

path = "myfile.orc"
pa_orc.write_table(table, path)

dataset = ds.dataset(path, format="orc")
fragments = list(dataset.get_fragments())
fragments[0].path

Output:

PyArrow Version: 7.0.0
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [2], in <cell line: 17>()
     15 dataset = ds.dataset(path, format="orc")
     16 fragments = list(dataset.get_fragments())
---> 17 fragments[0].path

AttributeError: 'pyarrow._dataset.Fragment' object has no attribute 'path'

Should I be using a different API here?

@jorisvandenbossche

Copy link
Copy Markdown
Member

Ah, yes, that's a bug / oversight in the ORC dataset bindings, the fragments should also return FileFragments instead of the base class Fragments. Opened https://issues.apache.org/jira/browse/ARROW-16442 and apache/arrow#13052 PR to fix it.

@rjzamora

rjzamora commented May 3, 2022

Copy link
Copy Markdown
Member Author

@rjzamora rjzamora closed this Jun 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants