Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 63 additions & 4 deletions dask/dataframe/io/parquet/arrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from ..utils import _get_pyarrow_dtypes, _meta_from_dtypes
from ...utils import clear_known_categories
from ....core import flatten
from dask import delayed

from .utils import (
_parse_pandas_metadata,
Expand All @@ -20,13 +21,28 @@
)

preserve_ind_supported = pa.__version__ >= LooseVersion("0.15.0")
schema_field_supported = pa.__version__ >= LooseVersion("0.15.0")


#
# Private Helper Functions
#


def _append_row_groups(metadata, md):
try:
metadata.append_row_groups(md)
except RuntimeError as err:
if "requires equal schemas" in str(err):
raise RuntimeError(
"Schemas are inconsistent, try using "
'`to_parquet(..., schema="infer")`, or pass an explicit '
"pyarrow schema."
)
else:
raise err


def _write_partitioned(
table, root_path, filename, partition_cols, fs, index_cols=(), **kwargs
):
Expand Down Expand Up @@ -239,7 +255,7 @@ def _gather_metadata(
elif fn:
md.set_file_path(fn)
if metadata:
metadata.append_row_groups(md)
_append_row_groups(metadata, md)
else:
metadata = md
return (
Expand Down Expand Up @@ -821,8 +837,51 @@ def initialize_write(
partition_on=None,
ignore_divisions=False,
division_info=None,
schema=None,
index_cols=None,
**kwargs,
):
# Infer schema if "infer"
# (also start with inferred schema if user passes a dict)
if schema == "infer" or isinstance(schema, dict):

# Start with schema from _meta_nonempty
_schema = pa.Schema.from_pandas(
df._meta_nonempty.set_index(index_cols)
if index_cols
else df._meta_nonempty
)

# Use dict to update our inferred schema
if isinstance(schema, dict):
schema = pa.schema(schema)
for name in schema.names:
i = _schema.get_field_index(name)
j = schema.get_field_index(name)
_schema = _schema.set(i, schema.field(j))

# If we have object columns, we need to sample partitions
# until we find non-null data for each column in `sample`
sample = [col for col in df.columns if df[col].dtype == "object"]
if schema_field_supported and sample and schema == "infer":
delayed_schema_from_pandas = delayed(pa.Schema.from_pandas)
for i in range(df.npartitions):
# Keep data on worker
_s = delayed_schema_from_pandas(
df[sample].to_delayed()[i]
).compute()
for name, typ in zip(_s.names, _s.types):
if typ != "null":
i = _schema.get_field_index(name)
j = _s.get_field_index(name)
_schema = _schema.set(i, _s.field(j))
sample.remove(name)
if not sample:
break

# Final (inferred) schema
schema = _schema

dataset = fmd = None
i_offset = 0
if append and division_info is None:
Expand Down Expand Up @@ -906,7 +965,7 @@ def initialize_write(
"Previous: {} | New: {}".format(old_end, divisions[0])
)

return fmd, i_offset
return fmd, schema, i_offset

@staticmethod
def write_partition(
Expand Down Expand Up @@ -937,7 +996,7 @@ def write_partition(
if md_list:
_meta = md_list[0]
for i in range(1, len(md_list)):
_meta.append_row_groups(md_list[i])
_append_row_groups(_meta, md_list[i])
else:
md_list = []
with fs.open(fs.sep.join([path, filename]), "wb") as fil:
Expand Down Expand Up @@ -977,6 +1036,6 @@ def write_metadata(parts, fmd, fs, path, append=False, **kwargs):
_meta = parts[0][0]["meta"]
i_start = 1
for i in range(i_start, len(parts)):
_meta.append_row_groups(parts[i][0]["meta"])
_append_row_groups(_meta, parts[i][0]["meta"])
with fs.open(metadata_path, "wb") as fil:
_meta.write_metadata_file(fil)
37 changes: 30 additions & 7 deletions dask/dataframe/io/parquet/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def read_parquet(
gather_statistics=None,
split_row_groups=None,
chunksize=None,
**kwargs
**kwargs,
):
"""
Read a Parquet file into a Dask DataFrame
Expand Down Expand Up @@ -236,7 +236,7 @@ def read_parquet(
gather_statistics=gather_statistics,
filters=filters,
split_row_groups=split_row_groups,
**kwargs
**kwargs,
)

# Parse dataset statistics from metadata (if available)
Expand Down Expand Up @@ -301,7 +301,8 @@ def to_parquet(
write_metadata_file=True,
compute=True,
compute_kwargs=None,
**kwargs
schema=None,
**kwargs,
):
"""Store Dask.dataframe to Parquet files

Expand Down Expand Up @@ -345,6 +346,16 @@ def to_parquet(
then a ``dask.delayed`` object is returned for future computation.
compute_kwargs : dict, optional
Options to be passed in to the compute method
schema : Schema object, dict, or {"infer", None}, optional
Global schema to use for the output dataset. Alternatively, a `dict`
of pyarrow types can be specified (e.g. `schema={"id": pa.string()}`).
For this case, fields excluded from the dictionary will be inferred
from `_meta_nonempty`. If "infer", the first non-empty and non-null
partition will be used to infer the type for "object" columns. If
None (default), we let the backend infer the schema for each distinct
output partition. If the partitions produce inconsistent schemas,
pyarrow will throw an error when writing the shared _metadata file.
Note that this argument is ignored by the "fastparquet" engine.
**kwargs :
Extra options to be passed on to the specific backend.

Expand Down Expand Up @@ -404,6 +415,14 @@ def to_parquet(
"will be set to the index (and renamed to None)."
)

# There are some "resrved" names that may be used as the default column
# name after resetting the index. However, we don't want to treat it as
# a "special" name if the string is already used as a "real" column name.
reserved_names = []
for name in ["index", "level_0"]:
if name not in df.columns:
reserved_names.append(name)

# If write_index==True (default), reset the index and record the
# name of the original index in `index_cols` (we will set the name
# to the NONE_LABEL constant if it is originally `None`).
Expand All @@ -418,7 +437,9 @@ def to_parquet(
none_index = list(df._meta.index.names) == [None]
df = df.reset_index()
if none_index:
df.columns = [c if c != "index" else NONE_LABEL for c in df.columns]
df.columns = [
c if c not in reserved_names else NONE_LABEL for c in df.columns
]
index_cols = [c for c in set(df.columns).difference(real_cols)]
else:
# Not writing index - might as well drop it
Expand All @@ -439,7 +460,7 @@ def to_parquet(

# Engine-specific initialization steps to write the dataset.
# Possibly create parquet metadata, and load existing stuff if appending
meta, i_offset = engine.initialize_write(
meta, schema, i_offset = engine.initialize_write(
df,
fs,
path,
Expand All @@ -448,7 +469,8 @@ def to_parquet(
partition_on=partition_on,
division_info=division_info,
index_cols=index_cols,
**kwargs_pass
schema=schema,
**kwargs_pass,
)

# Use i_offset and df.npartitions to define file-name list
Expand All @@ -467,7 +489,8 @@ def to_parquet(
fmd=meta,
compression=compression,
index_cols=index_cols,
**kwargs_pass
schema=schema,
**kwargs_pass,
)
for d, filename in zip(df.to_delayed(), filenames)
]
Expand Down
4 changes: 3 additions & 1 deletion dask/dataframe/io/parquet/fastparquet.py
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,7 @@ def initialize_write(
partition_on=None,
ignore_divisions=False,
division_info=None,
schema=None,
**kwargs
):
if append and division_info is None:
Expand Down Expand Up @@ -579,7 +580,8 @@ def initialize_write(
)
i_offset = 0

return (fmd, i_offset)
schema = None # ArrowEngine compatibility
return (fmd, schema, i_offset)

@classmethod
def write_partition(
Expand Down
70 changes: 65 additions & 5 deletions dask/dataframe/io/tests/test_parquet.py
Original file line number Diff line number Diff line change
Expand Up @@ -960,12 +960,15 @@ def test_to_parquet_pyarrow_w_inconsistent_schema_by_partition_fails_by_default(
)

ddf = dd.from_pandas(df, npartitions=2)
# Note: `append_row_groups` will fail with pyarrow>17.1 for _metadata write
# In order to allow pyarrow to write an inconsistent schema,
# we need to avoid writing the _metadata file (will fail >0.17.1)
# and need to avoid schema inference (i.e. use `schema=None`)
ddf.to_parquet(
str(tmpdir),
engine="pyarrow",
partition_on=["partition_column"],
write_metadata_file=False,
schema=None,
)

# Test that read fails because of default behavior when schema not provided
Expand Down Expand Up @@ -1069,6 +1072,53 @@ def test_to_parquet_pyarrow_w_inconsistent_schema_by_partition_succeeds_w_manual
assert np.array_equal(ddf_after_write.partition_column, df.partition_column)


@pytest.mark.parametrize("index", [False, True])
@pytest.mark.parametrize(
"schema", ["infer", {"index": pa.string(), "amount": pa.int64()}]
)
def test_pyarrow_schema_inference(tmpdir, index, engine, schema):

check_pyarrow()
if pa.__version__ < LooseVersion("0.15.0"):
pytest.skip("PyArrow>=0.15 Required.")

tmpdir = str(tmpdir)
df = pd.DataFrame(
{
"index": ["1", "2", "3", "2", "3", "1", "4"],
"date": pd.to_datetime(
[
"2017-01-01",
"2017-01-01",
"2017-01-01",
"2017-01-02",
"2017-01-02",
"2017-01-06",
"2017-01-09",
]
),
"amount": [100, 200, 300, 400, 500, 600, 700],
},
index=range(7, 14),
)
if index:
df = dd.from_pandas(df, npartitions=2).set_index("index")
else:
df = dd.from_pandas(df, npartitions=2)

df.to_parquet(tmpdir, engine="pyarrow", schema=schema, compute=False).compute(
scheduler="synchronous"
)
df_out = dd.read_parquet(tmpdir, engine=engine)

if index and engine == "fastparquet":
# Fastparquet not handling divisions for
# pyarrow-written dataset with string index
assert_eq(df, df_out, check_divisions=False)
else:
assert_eq(df, df_out)


def test_partition_on(tmpdir, engine):
tmpdir = str(tmpdir)
df = pd.DataFrame(
Expand Down Expand Up @@ -2029,7 +2079,16 @@ def test_read_dir_nometa(tmpdir, write_engine, read_engine, statistics, remove_c
assert_eq(ddf, ddf2, check_divisions=False)


def test_timeseries_nulls_in_schema(tmpdir, engine):
@pytest.mark.parametrize("schema", ["infer", None])
def test_timeseries_nulls_in_schema(tmpdir, engine, schema):

if (
schema == "infer"
and engine == "pyarrow"
and pa.__version__ < LooseVersion("0.15.0")
):
pytest.skip("PyArrow>=0.15 Required.")

# GH#5608: relative path failing _metadata/_common_metadata detection.
tmp_path = str(tmpdir.mkdir("files"))
tmp_path = os.path.join(tmp_path, "../", "files")
Expand All @@ -2043,16 +2102,17 @@ def test_timeseries_nulls_in_schema(tmpdir, engine):
ddf2.name = ddf2.name.where(ddf2.timestamp == "2000-01-01", None)

# Note: `append_row_groups` will fail with pyarrow>0.17.1 for _metadata write
ddf2.to_parquet(tmp_path, engine=engine, write_metadata_file=False)
ddf2.to_parquet(tmp_path, engine=engine, write_metadata_file=False, schema=schema)
ddf_read = dd.read_parquet(
tmp_path, engine=engine, dataset={"validate_schema": False}
)

assert_eq(ddf_read, ddf2, check_divisions=False, check_index=False)

# Can force schema validation on each partition in pyarrow
if engine == "pyarrow":
# The schema mismatch should raise an error
if engine == "pyarrow" and schema is None:
# The schema mismatch should raise an error if the
# dataset was written with `schema=None` (no inference)
with pytest.raises(ValueError):
ddf_read = dd.read_parquet(
tmp_path, dataset={"validate_schema": True}, engine=engine
Expand Down