Repository navigation
Preserve DataFrame divisions when reading from parquet using pyarrow - #3387
Conversation
…0.9.0 pyarrow tests currently pass for <0.9.0 and fail for >=0.9.0
|
A couple of notes on the "tangentially related issues" I mentioned above.
There are also failures in |
It's not the logic of calculating the divisions, it's the possibility that we would need to read data from many files on a remote store, and that this might take up a significant amount of time. If PyArrow isn't writing a metadata file then my understanding is that we'll have to read a bit of data from each of the parquet files in the dataset, which in practice gets into the thousands (or so I believe). What is the cost for each remote access in this case? I would not be surprised to learn that it was in the hundreds of milliseconds, which means that the
For the arrow and divisions logic we might also ping @xhochy here in case he has time. |
|
I won't have time to fully review this until tomorrow, but I just want to respond to:
Currently when reading parquet with pyarrow, the schema is grabbed from every file. This could be turned off by passing The statistics information is also available at known byte offsets in the files, and so may also be efficiently read in for filesystems that support efficient random access (hdfs, local, not sure about others). A single metadata file would certainly be more efficient (https://issues.apache.org/jira/browse/ARROW-1983) but I'm not sure if pulling the stats from every file would be bad enough to warrant an api change. Benchmarking needed. |
|
Does anyone know the rationale for not writing metadata files? Is it a problem of a blocking finalizer task following parallel writing? For example, spark used to, but no longer does by default. |
|
Another observation:
Here's an example from inside This seems unintuitive to me. Is this the expected behavior? If so, determining divisions accuratley will involve sorting the partitions by their But, even apart from the divisions issue, the fact that pyarrow doesn't return pieces ordered by part number suggests that the order of the partitions in the resulting dask dataframe won't necessarily match the order in which they were written. |
|
After poking around at the parquet datasets created by I also tried using the |
But getting tests to pass required multiplying int64 time by 1000 and I'm not sure why.
If your Parquet dataset is not the result from a single job but will get appended on e.g. a daily basis updating the But the actual lack of writing |
|
|
||
| # Handle converting divisions to timestamps | ||
| if divisions[0] is not None and meta.index.dtype.kind == 'M': | ||
| # Why is this factor of 1000 needed??? |
There was a problem hiding this comment.
This could be also a factor of 1M or 1 depending on the precision of the time. Pandas uses nanoseconds by default whereas we use the Parquet preferred default of microsecond precision in Parquet. But as Parquet supports many precisions and Pandas only a single one, you will have to look at the actual Parquet schema to infer the scaling factor, the meta object will not have sufficient information to determine it.
There was a problem hiding this comment.
Thanks for the help on this one!
|
@xhochy Thanks for your feedback. If you can spare another moment, do you any perspective/guidance on the following remaining issues?
|
…andas Refactor division logic into a new method and base it entirely on the pyarrow schema (not the pandas metadata)
|
Test failure notes: pf = piece.get_metadata(pq.ParquetFile)
rg = pf.row_group(0)
col_meta = rg.column(divisions_col_index) # SIGSEGV hereAt this point And the schema looks like this. And, interestingly, calling Update: |
…ith 'pyarrow' This was causing a SIGSEGV error and the comments already state that fastparquet doesn't write column_names
| # Handle encoding of bytes string | ||
| if index_field.type == pa.string(): | ||
| # Is this always true? Is the string encoding specified in the parquet metadata somewhere? | ||
| encoding = 'utf-8' |
There was a problem hiding this comment.
All parquet strings are UTF8, there is no option to set any other encoding.
There was a problem hiding this comment.
Great! I'll remove the question and update the comment
…ather than on the schema. These differ in the case of partitioned datasets
|
I made a few more changes and now there are only 2 failing tests cases, summarized below.
I think this is as far as I can take this without some help from the pyarrow side. Anyone available/willing to take a look? |
I guess not only is min truncated but max is probably then also truncated?
This is the expected behaviour as an empty string column in Pandas is simply an empty column of type |
|
The code looks good. I'm worried a bit that it might be costly due to a lot of I/O. |
This seems unintuitive at best to me. An empty object column in pandas is treated differently in many operations than an empty float64 column (
Upon further thought, I am too. I think we should provide a kwarg to turn this behavior on/off. Proposed semantics: """
...
infer_divisions : bool or None (default).
By default divisions are inferred only if a global `_metadata` file
is found for the dataset. Set to ``True`` to force divisions to be
inferred in all cases. Note that without a `_metadata` file, this
requires reading metadata from each file in the dataset, which may be
expensive. Set to ``False`` to never infer divisions.
""" |
We should probably use another method than We also store the original dtype in the Pandas metadata that is used for the actual DataFrame reconstruction later on. If we would also pick up the metadata when it was written, we should be able to correctly reconstruct the dtype. |
|
Thanks for the feedback @xhochy , I'll switch to looking directly at the pandas metadata. If I recall correctly this did have the
That's correct, @jcrist The option you describes sounds reasonable. So setting this to I'll take a stab at updating the Assuming this doesn't uncover any other fundamental issues, I think the last remaining blocker is the If we knew how this truncation works, we might be able to add a little padding to each division to account for it. But I fear this could also produce unexpected results in cases where the truncation isn't neccessary. Thoughts? |
Correct. That part should be fairly easy to add. Adding the |
|
If I recall correctly, it looked like So raising a |
|
Ok, I think this might be just about good to go (and CI tests as passing). @jcrist @xhochy @mrocklin Summary of updates
With this change,
Note: We're no longer hitting the |
mrocklin
left a comment
There was a problem hiding this comment.
In general this seems fine to me. It seems safe given that it's off by default and that it escapes early if divisions are not sorted.
I can't say much about the accuracy of actual parquet code. It would be good if someone else is able to look things over as well.
| def to_sort_tuple(piece): | ||
| return [int(s) if s.isdigit() else s for s in re.split('(\d+)', piece.path)] | ||
|
|
||
| return sorted(pieces, key=to_sort_tuple) |
There was a problem hiding this comment.
This will maybe be useful elsewhere? I suggest that we make this non-parquet specific and throw it in dask/utils.py. Perhaps it should consume a sequence of filenames?
There was a problem hiding this comment.
I moved the core of this to dask.utils as nat_sort_key
| if divisions_col_index is None: | ||
| rg_paths = [rg.column(i).path_in_schema for i in range(rg.num_columns)] | ||
| try: | ||
| divisions_col_index = rg_paths.index(divisions_name) |
There was a problem hiding this comment.
Will this be the same for all of the pa_pieces?
There was a problem hiding this comment.
Good question. This assumption might be violated if someone passed in a list of paths to parquet datasets where some of the datasets are partitioned and others aren't. Since I'm not confident, I switched back to computing this for each piece.
| else: | ||
| # Divisions not valid | ||
| min_maxs = None | ||
| break |
There was a problem hiding this comment.
I like the early break here. Thanks!
This ensures that we're testing natural sorting
- Move nat_sort_key into dask.utils - Natural sort paths resulting from globstring patterns before passing lists of paths to the engines - Only natural sort pyarrow parquet pieces if a single input path resulted in multiple pieces
# Conflicts: # docs/source/changelog.rst
|
Thanks for the comments @mrocklin, I pushed some updates in response I also made some updates to the parquet test suite to make sure that we hit the situation more frequently where we have more than 10 parquet pieces (in which case the natural sorting distinction is important). Let me know if there's anything else you'd like to see here @mrocklin @jcrist |
jcrist
left a comment
There was a problem hiding this comment.
Overall this looks good to me. I didn't read too much into how you're getting the divisions, but the tests look good and if they pass that's fine. I left a couple stylistic, linting comments.
| pf = fastparquet.ParquetFile(paths[0], open_with=fs.open, sep=fs.sep) | ||
|
|
||
| # Validate infer_divisions | ||
| if not pf.fn.endswith('/_metadata') and infer_divisions is True: |
There was a problem hiding this comment.
This is specific to unix-like filesystems. Perhaps os.path.split(pf.fn).endswith('_metadata').
| def test_to_parquet_lazy(tmpdir, get): | ||
| def test_to_parquet_lazy(tmpdir, get, engine): | ||
| check_fastparquet() | ||
| check_pyarrow() |
There was a problem hiding this comment.
No need for check_fastparquet/check_pyarrow here with the addition of the engine fixture, as that handles this automatically.
| factor = 1 | ||
| else: | ||
| raise ValueError("Unsupported time unit '{unit}'" | ||
| .format(unit=unit)) |
There was a problem hiding this comment.
Would prefer a lookup table here. Perhaps:
try:
factor = {'s': 1e9, 'ms': 1e6, 'us': 1e3, 'ns': 1}.get(unit)
except KeyError:
raise ValueError("Unsupported time unit '{unit}'".format(unit=unit))
return val * int(factor)
| import pyarrow as pa | ||
| import pyarrow.parquet as pq | ||
|
|
||
| if infer_divisions is True and pa.__version__ < distutils.version.LooseVersion('0.9.0'): |
There was a problem hiding this comment.
Would prefer LooseVersion imported at top-level. Shorter lines, and it's used elsewhere.
| try: | ||
| import pyarrow.parquet as pq | ||
| except ImportError: | ||
| check_pa_divs = False |
There was a problem hiding this comment.
I may be wrong, but I believe this line is unnecessary.
| check_pa_divs = False | ||
|
|
||
|
|
||
| def check_divs(engine): |
There was a problem hiding this comment.
Since this doesn't actually check divs, would prefer a better name. Perhaps should_check_divs.
| hasattr(x, 'dtype')) | ||
|
|
||
|
|
||
| def nat_sort_key(s): |
There was a problem hiding this comment.
Would prefer natural_sort_key instead of nat_sort_key, as I read nat as NaT (not a time). It's also not clear to me what natural means in this case, but I struggle to think of a better name.
|
Thanks for the comments and for helping me make this better @jcrist I believe I've incorporated all of your suggestions. |
|
Looks like you have failures on python 2. |
|
Thanks, @jcrist, I think I found the culprit. |
|
Looks good to me. Thanks @jmmease! Merging. |
Implementation of #3383.
I updated a bunch of tests in
test_parquet.pyto check theread_parquetdask DataFrame against the expected dask DataFrame, rather than the expected pandas DataFrame. I onlycheck_divisionswhen the reader isfastparquetorpyarrow >= '0.9.0'. This has the added benefit of checking theread_parquetdivisions logic for the fastparquet path, which I don't think was really verified previously.I added a bit of logic to
_read_pyarrowto use pyarrow's column metadata stats to compute the min/max of each row group and the use these pairs to build the divisions. It's rough, but it works in many cases.I ran into a handful of tangentially related issues during a couple of hours of working through the failing tests. I'm not sure if I'll be able to see this through the the finish, but I wanted to at least share my progress.
@jcrist Is this division calculation logic the kind of approach you had in mind in #3383?
@mrocklin Does this division calculation logic give you pause performance-wise?
flake8 dask