Repository navigation
Description
When writing partitoned Datasets to parquet files, and it so happens that there are is a partition where one column has no values, inconsistent schemas are written to the parquet file so that reading is prevented later:
import dask as da
import dask.dataframe as dd
import pandas as pd
import numpy as np
import os
import shutil
PATH_DASK = '/tmp/dask.pa'
if os.path.exists(PATH_DASK):
shutil.rmtree(PATH_DASK)
arrays = np.array([np.array([0, 1, 2]), np.array([3, 4]), np.nan, np.nan])
strings = np.array(['a', 'b', np.nan, np.nan])
df = pd.DataFrame([0, 0, 1, 1], columns=['partition_column'])
df['arrays'] = pd.Series(arrays)
df['strings'] = pd.Series(strings)
da_df = dd.from_pandas(df, npartitions=2)
da_df.to_parquet(PATH_DASK, partition_on=['partition_column'])
dd.read_parquet(PATH_DASK)Fails with:
ValueError: Schema in partition[partition_column=1] /tmp/dask.pa/partition_column=1/4cd3552267d84d66a5ec8764f869a13b.parquet was different.
arrays: null
strings: string
__index_level_0__: int64
metadata
--------
...
vs
arrays: list<item: int64>
child 0, item: int64
strings: string
__index_level_0__: int64
metadata
--------
I found #3454 relating to https://issues.apache.org/jira/browse/ARROW-2860. However the Pyarrow Issue only relates to reading files with different schemas. However Pyarrow in it self doesn't even suffer this Bug, as Pyarrow itself would't even write those different schemas in the first place:
import pyarrow as pa
import pyarrow.parquet as pq
import pandas as pd
import os
import shutil
PATH_PYARROW = '/tmp/pyarrow.pa'
if os.path.exists(PATH_PYARROW):
shutil.rmtree(PATH_PYARROW)
arrays = np.array([np.array([0, 1, 2]), np.array([3, 4]), np.nan, np.nan])
strings = np.array([np.nan, np.nan, 'a', 'b'])
df = pd.DataFrame([0, 0, 1, 1], columns=['partition_column'])
df['arrays'] = pd.Series(arrays)
df['strings'] = pd.Series(strings)
table = pa.Table.from_pandas(df)
pq.write_to_dataset(table, root_path=PATH_PYARROW, partition_cols=['partition_column'])
dataset = pq.ParquetDataset(PATH_PYARROW)
df_read = dataset.read().to_pandas()
df_readWorks perfectly fine. Even reading the Pyarrow Files with Dask now works perfectly fine:
dd.read_parquet(PATH_PYARROW).compute()
This is simply due to the reason that Pyarrow still uses the same schema accross partitions even if ther is missing data:
import os
files = [val for sublist in [[os.path.join(i[0], j) for j in i[2]] for i in os.walk(PATH_PYARROW)] for val in sublist]
for file in files:
dataset_part = pq.ParquetDataset(file)
print(file)
print(dataset_part.schema)
print(dataset_part.read().to_pandas())Outputs:
/tmp/pyarrow.pa/partition_column=0/f32bf0bfedcc4312829e7c4371e544e6.parquet
<pyarrow._parquet.ParquetSchema object at 0x7fdd1c103eb8>
arrays.list.item: INT64
strings: BYTE_ARRAY UTF8
__index_level_0__: INT64
arrays strings
0 [0, 1, 2] nan
1 [3, 4] nan
/tmp/pyarrow.pa/partition_column=1/044dd125e0b5472db23bff9a954a1bff.parquet
<pyarrow._parquet.ParquetSchema object at 0x7fdd1c1034e0>
arrays.list.item: INT64
strings: BYTE_ARRAY UTF8
__index_level_0__: INT64
arrays strings
2 None a
3 None bSo summing it up: In Pyarrow the pyarrow.parquet.write_to_dataset wrapper around pyarrow.parquet.write_table takes care that the schema in individual files doesn't get screwed up. Dask blindly uses pyarrow.parquet.write_table on each partition and hence ends up with a wrong schema.
This means that even if https://issues.apache.org/jira/browse/ARROW-2860 is fixed, loading of these wrong schemas might work, but they are still written wrongly to the file in the first place.
I believe that fixing this in dask is probably going to be hard but might still be worth a try. Maybe one simple but not ideal solution would be to to stick to the schema the first written partition produces and raise an error otherwise. At least we should make sure, that after all partitions are written to file, the schemas match. Otherwise people will save their files without an error raised and notice later on that opening is no longer possible.
Activity
mrocklin commentedon Nov 9, 2018
cc @xhochy @pitrou thoughts on the best way to handle this?
pitrou commentedon Nov 9, 2018
I'm not a Parquet expert so it's hard to say for sure. Intuitively, I'd say all files in a Parquet partition had better have the same schema, but perhaps there's a specification somewhere that spells it out?
pitrou commentedon Nov 9, 2018
To answer a bit more concretely, ideally you may use the Array.cast method to homogenize datatypes accross columns.
However, it doesn't support all types (yet?):
martindurant commentedon Nov 9, 2018
It is certainly much much better to have the same schema throughout. In some circumstances and some parquet frameworks, schema evolution is allowed, but that is not in the official spec.
pitrou commentedon Nov 9, 2018
That said, we could add such a facility in PyArrow. Homogenizing arrays may be needed for other purposes at some point. @wesm
wesm commentedon Nov 9, 2018
We've already had several bug reports about this, here is one:
https://issues.apache.org/jira/browse/ARROW-2860
Here is my comment from 15th September
In general, we need more help on Parquet support in Apache Arrow. I think this issue can be completely solved in Python code without touching any C++
wesm commentedon Nov 9, 2018
That being said, we should probably implement concatenation with schema normalization in C++ so it doesn't have to be redone for R and Ruby. Ruby already has Parquet support and R is not far behind
rafonseca commentedon Feb 1, 2019
I've just run into the same problem. I understand that I can use pyarrow.parquet.write_to_dataset as a workaround, right?
But I would like to do it properly using dask API. Is someone working in this issue? Can I help?
mmccarty commentedon Mar 25, 2019
@mrocklin @wesm Any movement on this issue? We are running into it as well. Please let me know if you need help.
wesm commentedon Mar 25, 2019
Not yet. It would be great if someone could write a patch for this or contact me about paying for development work on the project. Absent these things I don't know when it will get fixed
birdsarah commentedon Apr 20, 2019
I was having this problem too and the following, not very elegant, patch fixes it for my data:
I then manually create a pyarrow schema and pass it in:
mmccarty commentedon Apr 20, 2019
Thanks @birdsarah ! This isn't too terrible. Do others think it would be reasonable fix this in Dask until we can get a solution at the lower level?
Wes, I'm working on making open source contributions possible for my team. Unfortunately, it is an uphill battle, however I am making progress. Stay tuned! I have folks, including myself, that would love to help out!
martindurant commentedon Apr 22, 2019
Probably the thing to do is produce the pyarrow schema from the meta? Or does that not produce a useful schema for an empty dataframe, is that the problem?
Being allowed to explicitly specify the schema does seem like a useful option in any case.
birdsarah commentedon Apr 22, 2019
@martindurant I think that sounds right.
I'm not having an empty dataframe problem so I can't speak to that. The problem I'm having is that the schema is inferrred each time from each partition of data and attempts to specify the meta have been ignored. I have a string field that's sometimes all null for a given partition, then my individual partitions are written with different schemas and I can't read back.
I was surprised to see the meta not being used, but I also didn't know how to make a pyarrow schema from the meta data, which is why i'm hard coding the pyarrow schema. I'm already making the meta data schema and I'd prefer to not make the schema twice.
That said, I had specified the meta data. Are there were cases where you'd get to line ~1000 above and the df would not have _meta on it.
martindurant commentedon Apr 22, 2019
So although a dataframe should always have one, the meta is usually empty, so calling pyarrow on it directly to make a schema would produce exactly the wrong thing :| I suppose you could always make the schema from a partition of the data that you know to be sound.
fastparquet has this problem too, and you need to, in the general case, specify how you want to interpret object columns.
19 remaining items
martindurant commentedon Apr 30, 2019
I guess make a dask dataframe with a zoned datetime column and no rows (or only NaT) in one partition.
birdsarah commentedon Apr 30, 2019
The original issue here has nothing to do with datetime. That whole discussion only arised out of trying to build a shortcut and i would say it's separate if we're not going to try and infer the pyarrow schema from the already provided data to meta.
martindurant commentedon Apr 30, 2019
OK, just thought datetime was the most complex case; the simplest case (int?) would do.
Right, so it seems this isn't as simple to do as I had originally hoped. It it were straight-forward, no extra options would be needed.
birdsarah commentedon Apr 30, 2019
There's also array cases and other datatypes which i feel like i don't know enough about pyarrow to make sure are properly covered. Providing your own pyarrow schema bypasses any attempts to be clever that could fail.
jorisvandenbossche commentedon May 2, 2019
So trying to summarize the different threads from the discussion above:
schema=keyword toto_parquetfor the pyarrow branch as one of the arbitrary kwargs that gets passed to the partition-writing tasks (and we might want to do something similar in pandas'to_parquet).This can be used as a work-around to ensure consistent schema's across partitions / multiple writes.
metadataframe alone is not enough to reliably create a schema):object_encodingkeyword, to specify how to interpret object dtype columns (as all other column dtypes can faithfully be mapped to arrow / parquet types)Does that sound correct? Other items?
martindurant commentedon May 2, 2019
That sounds like a fair summary to me. The first point should not be required if we can tackle the third (or ameliorated by the second), although maybe it's possible to get such inconsistent schemas from elsewhere.
mmccarty commentedon May 20, 2019
I can take a stab at the Dask related parts summarized above, but I wanted to check first. Is anyone else working on this?
birdsarah commentedon May 20, 2019
I'm not. I don't currently have time, but would LOVE to see this happen. Thanks!
iyawnis commentedon Oct 14, 2019
I have this issue with dask==2.5.2, pyarrow==0.15.0. Fastparquet does not have this problem, although I am guessing its down to the way it handles partitions.
Is there anything more clever / reliable to do than manually mapping numpy.dtypes to pa DataTypes like the following?:
TomAugspurger commentedon Oct 14, 2019
@latusaki you could likely construct / extract a DataFrame with the correct schema and make a pyarrow.Table from that.
iyawnis commentedon Oct 15, 2019
@TomAugspurger sadly enough, table.head() and table.tail() have different schema on my example dataframe that reproduces this issue
ldacey commentedon Apr 2, 2020
I have something similar @latusaki. I needed to also fix my category columns and I wanted dates to be saved as pa.date32()
How can I save this to a file or something though? I want to reuse it when I read in a new file every day without reading a 'correct' version of the file first (ideally). The function above returns:
Can I save this to a file or print it out in a format like this which I can save in my script and edit if needed? There are a few columns I need to change (they are double instead of string, or string instead of date32[day].
jrbourbeau commentedon Apr 2, 2020
@ldacey I would suggest looking through the pyarrow documentation to see if there's a supported API for saving
schemaobjectsldacey commentedon Apr 2, 2020
FYI, thanks @jorisvandenbossche for pointing out that we can use .set() to change the data type of a field. Here is a working example:
I'll probably just tweak that to work based off of a dictionary of columns which might need to be changed instead of changing them one by one.
I think this suffices for now but it would be nice to be able to generate a dict or list of
column: pyarrow_typethat could be saved externally: