Skip to content
Open
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
56 changes: 36 additions & 20 deletions pyiceberg/io/pyarrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -2833,36 +2833,52 @@ def parquet_path_to_id_mapping(
return result


def _nan_value_counts_from_arrow(table: pa.Table, stats_columns: dict[int, StatisticsCollector]) -> dict[int, int]:
"""Count the non-null NaN values of the top-level float and double columns.
def _nan_value_counts_from_arrow(
table: pa.Table, schema: Schema, stats_columns: dict[int, StatisticsCollector]
) -> dict[int, int]:
"""Count the non-null NaN values of the float and double columns, including nested fields.

PyArrow does not expose the NaN count of a Parquet column statistic, so the counts are taken
from the data before it is written. Columns that cannot be counted are left out, which only
means the file cannot be pruned on NaN counts.
from the data before it is written. Float and double fields inside structs, list elements,
and map keys and values are counted as well. Columns that cannot be counted are left out,
which only means the file cannot be pruned on NaN counts.

Args:
table (pyarrow.Table): The data that is written to the file.
schema (Schema): The Iceberg schema of the file.
stats_columns (dict[int, StatisticsCollector]): The statistics gathering plan.

Returns:
A mapping of Iceberg field ID to the number of non-null NaN values.
"""
nan_field_ids = {
field_id
for field_id, stats_col in stats_columns.items()
if isinstance(stats_col.iceberg_type, (FloatType, DoubleType)) and stats_col.mode != MetricsMode(MetricModeTypes.NONE)
}
nan_value_counts: dict[int, int] = {}
for pos, arrow_field in enumerate(table.schema):
if (field_id := _get_field_id(arrow_field)) is None:
continue

stats_col = stats_columns.get(field_id)
if stats_col is None:
continue

if stats_col.mode == MetricsMode(MetricModeTypes.NONE):
continue

if not isinstance(stats_col.iceberg_type, (FloatType, DoubleType)):
continue

nan_value_counts[field_id] = pc.sum(pc.is_nan(table.column(pos)), min_count=0).as_py()
if not nan_field_ids:
return nan_value_counts

def count(field_id: int, field_type: IcebergType, array: pa.Array) -> None:
if isinstance(field_type, StructType):
for nested_field in field_type.fields:
if array.type.get_field_index(nested_field.name) >= 0:
# struct_field also applies the validity of the parent struct
count(nested_field.field_id, nested_field.field_type, pc.struct_field(array, nested_field.name))
elif isinstance(field_type, ListType):
count(field_type.element_id, field_type.element_type, array.flatten())
elif isinstance(field_type, MapType):
entries = array.cast(pa.list_(pa.struct([array.type.key_field, array.type.item_field]))).flatten()
count(field_type.key_id, field_type.key_type, entries.field(0))
count(field_type.value_id, field_type.value_type, entries.field(1))
elif field_id in nan_field_ids and pa.types.is_floating(array.type):
nan_value_counts[field_id] = nan_value_counts.get(field_id, 0) + pc.sum(pc.is_nan(array), min_count=0).as_py()

for field in schema.fields:
if table.schema.get_field_index(field.name) >= 0:
for chunk in table.column(field.name).chunks:
count(field.field_id, field.field_type, chunk)

return nan_value_counts

Expand Down Expand Up @@ -3042,7 +3058,7 @@ def write(self, table: pa.Table) -> None:
raise
self._fos = fos
self._writer.write(table, row_group_size=self._row_group_size)
for field_id, count in _nan_value_counts_from_arrow(table, self._stats_columns).items():
for field_id, count in _nan_value_counts_from_arrow(table, self._file_schema, self._stats_columns).items():
self._nan_value_counts[field_id] = self._nan_value_counts.get(field_id, 0) + count

def close(self) -> DataFileStatistics:
Expand Down
21 changes: 21 additions & 0 deletions tests/catalog/test_catalog_behaviors.py
Original file line number Diff line number Diff line change
Expand Up @@ -1661,6 +1661,27 @@ def test_replace_files_in_nan_identity_partition(catalog: Catalog) -> None:
assert sorted(tbl.scan(row_filter="value is nan").to_arrow()["id"].to_pylist()) == expected_nan_ids, name


def test_delete_keeps_nan_rows_that_do_not_match_the_filter(catalog: Catalog) -> None:
catalog.create_namespace("default")
identifier = f"default.delete_keeps_nan_rows_{catalog.name}"
iceberg_schema = Schema(
NestedField(1, "id", IntegerType(), required=False),
NestedField(2, "value", DoubleType(), required=False),
)
tbl = catalog.create_table(identifier=identifier, schema=iceberg_schema)
tbl.append(
pa.Table.from_pydict(
{"id": [1, 2], "value": [1.0, float("nan")]},
schema=schema_to_pyarrow(iceberg_schema),
)
)

# NaN < 5.0 is false, so the NaN row must survive and the file cannot be dropped as a whole
tbl.delete("value < 5.0")

assert tbl.scan().to_arrow()["id"].to_pylist() == [2]


def test_scan_integer_column_with_decimal_literal(catalog: Catalog) -> None:
catalog.create_namespace("default")
identifier = f"default.scan_integer_decimal_literal_{catalog.name}"
Expand Down
36 changes: 35 additions & 1 deletion tests/io/test_format_writers.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
from pyiceberg.io.pyarrow import ParquetFormatModel, PyArrowFileIO, schema_to_pyarrow
from pyiceberg.manifest import FileFormat
from pyiceberg.schema import Schema
from pyiceberg.types import DoubleType, FloatType, LongType, NestedField
from pyiceberg.types import DoubleType, FloatType, ListType, LongType, MapType, NestedField, StringType, StructType


@pytest.fixture(params=FileFormatFactory.available_formats(), ids=lambda f: f.name.lower())
Expand Down Expand Up @@ -73,6 +73,40 @@ def test_null_handling(format_model: FileFormatModel, table_schema_simple: Schem
assert stats.null_value_counts.get(1) == 1


def test_nan_value_counts(format_model: FileFormatModel, tmp_path: Path) -> None:
"""Float and double columns produce nan_value_counts, including nested and empty counts."""
nan = float("nan")
schema = Schema(
NestedField(1, "id", LongType(), required=False),
NestedField(2, "f", FloatType(), required=False),
NestedField(3, "d", DoubleType(), required=False),
NestedField(4, "no_nans", DoubleType(), required=False),
NestedField(5, "s", StructType(NestedField(6, "x", DoubleType(), required=False)), required=False),
NestedField(7, "l", ListType(element_id=8, element_type=DoubleType(), element_required=False), required=False),
NestedField(
9,
"m",
MapType(key_id=10, key_type=StringType(), value_id=11, value_type=DoubleType(), value_required=False),
required=False,
),
)
table = pa.Table.from_pylist(
[
{"id": 1, "f": nan, "d": nan, "no_nans": 1.0, "s": {"x": nan}, "l": [nan, 1.0], "m": {"a": nan}},
{"id": 2, "f": 1.0, "d": nan, "no_nans": None, "s": None, "l": None, "m": None},
{"id": 3, "f": None, "d": 2.0, "no_nans": 2.0, "s": {"x": 1.0}, "l": [nan, nan], "m": {"b": 1.0, "c": nan}},
],
schema=schema_to_pyarrow(schema),
)
file_path = str(tmp_path / f"test.{format_model.file_extension()}")
writer = format_model.create_writer(PyArrowFileIO().new_output(file_path), schema, {})
writer.write(table)
writer.write(table.slice(0, 1))
stats = writer.close()

assert stats.nan_value_counts == {2: 2, 3: 3, 4: 0, 6: 2, 8: 4, 11: 3}


def test_context_manager_caches_result(
format_model: FileFormatModel, table_schema_simple: Schema, arrow_table_simple: pa.Table, tmp_path: Path
) -> None:
Expand Down
Loading