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
1 change: 1 addition & 0 deletions mkdocs/docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -1110,6 +1110,7 @@ Expert Iceberg users may choose to commit existing parquet files to the Iceberg
`add_files` can work with Parquet files both with and without field IDs in their metadata:
- **Files with field IDs**: When field IDs are present in the Parquet metadata, they must match the corresponding field IDs in the Iceberg table schema. This is common for files generated by tools like Spark or when using or other libraries with explicit field ID metadata.
- **Files without field IDs**: When field IDs are absent, the table must have a [Name Mapping](https://iceberg.apache.org/spec/?h=name+mapping#name-mapping-serialization) to map field names to Iceberg field IDs. `add_files` will automatically create a Name Mapping based on the table's current schema if one doesn't already exist.
- **Files with field IDs on only some columns**: `add_files` rejects these files, because the reader ignores columns without a field ID and would return null for them.

!!! note "Partitions"
`add_files` only requires the client to read the existing parquet files' metadata footer to infer the partition value of each file. This implementation also supports adding files to Iceberg tables with partition transforms like `MonthTransform`, and `TruncateTransform` which preserve the order of the values after the transformation (Any Transform that has the `preserves_order` property set to True is supported). Please note that if the column statistics of the `PartitionField`'s source column are not present in the parquet metadata, the partition value is inferred as `None`.
Expand Down
204 changes: 203 additions & 1 deletion pyiceberg/io/pyarrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -1297,7 +1297,27 @@ def pyarrow_to_schema(
name_mapping: NameMapping | None = None,
downcast_ns_timestamp_to_us: bool = False,
format_version: TableVersion = TableProperties.DEFAULT_FORMAT_VERSION,
prune_fields_without_ids: bool = False,
) -> Schema:
"""Convert a PyArrow schema to an Iceberg schema.

Args:
schema: The PyArrow schema to convert.
name_mapping: Used when the schema has no field IDs.
downcast_ns_timestamp_to_us: Downcast nanosecond timestamps to microseconds.
format_version: The Iceberg table format version.
prune_fields_without_ids: If some fields have field IDs, drop the ones that do not
(including lists whose element has no ID) instead of falling back to the name
mapping, like the Java Parquet reader does. A map is kept when either its key or
its value has an ID, and key and value are matched by position. Only meant for
reading data files. Writes keep the stricter check, so extra columns are rejected
instead of silently dropped.
"""
if prune_fields_without_ids:
# Prune before conversion, so an unsupported type in a column without an ID does not fail the read.
# Any field ID means the file is read by ID, even if every field ends up pruned.
if _has_any_field_ids(schema):
schema = _prune_fields_without_ids(schema)
has_ids = visit_pyarrow(schema, _HasIds())
if has_ids:
return visit_pyarrow(
Expand All @@ -1314,6 +1334,176 @@ def pyarrow_to_schema(
)


def _has_any_field_ids(schema: pa.Schema) -> bool:
"""Return whether any field in the schema, including nested ones, has a field ID."""
return any(_field_has_any_ids(field) for field in schema)


def _field_has_any_ids(field: pa.Field) -> bool:
if _get_field_id(field) is not None:
return True
arrow_type = field.type
if pa.types.is_struct(arrow_type):
return any(_field_has_any_ids(arrow_type.field(i)) for i in range(arrow_type.num_fields))
elif isinstance(arrow_type, (pa.ListType, pa.LargeListType, pa.FixedSizeListType)):
return _field_has_any_ids(arrow_type.value_field)
elif isinstance(arrow_type, pa.MapType):
return _field_has_any_ids(arrow_type.key_field) or _field_has_any_ids(arrow_type.item_field)
return False


def _prune_fields_without_ids(schema: pa.Schema) -> pa.Schema:
"""Drop fields without a field ID, so only the columns with IDs are read.

A list is dropped when its element has no ID. A map is kept when its key or
value has an ID, including when only one side has one, matching Java's
PruneColumns.map; key and value are later matched by position. A struct
whose children all get dropped is dropped as well.
"""
fields = [pruned for field in schema if (pruned := _prune_field_without_id(field)) is not None]
# Placeholders let _ConvertToIceberg convert a kept map whose key or value has no ID.
# Projection matches map key and value by position, not by these IDs.
ids = itertools.count(-1, -1)
fields = [_assign_missing_field_ids(field, ids) for field in fields]
return pa.schema(fields, metadata=schema.metadata)


def _prune_field_without_id(field: pa.Field) -> pa.Field | None:
if _get_field_id(field) is None:
return None
pruned_type = _prune_type_without_ids(field.type)
if pruned_type is None:
return None
return field.with_type(pruned_type)


def _prune_type_without_ids(arrow_type: pa.DataType) -> pa.DataType | None:
if pa.types.is_struct(arrow_type):
children = [arrow_type.field(i) for i in range(arrow_type.num_fields)]
pruned_children = [pruned for child in children if (pruned := _prune_field_without_id(child)) is not None]
return pa.struct(pruned_children) if pruned_children else None
elif isinstance(arrow_type, (pa.ListType, pa.LargeListType, pa.FixedSizeListType)):
element_field = _prune_field_without_id(arrow_type.value_field)
if element_field is None:
return None
if isinstance(arrow_type, pa.LargeListType):
return pa.large_list(element_field)
if isinstance(arrow_type, pa.FixedSizeListType):
return pa.list_(element_field, arrow_type.list_size)
return pa.list_(element_field)
elif isinstance(arrow_type, pa.MapType):
# Like Java's PruneColumns.map: keep the whole map when either child has any ID.
# TypeWithSchemaVisitor (and ArrowAccessor) later match key and value by position.
if not _field_has_any_ids(arrow_type.key_field) and not _field_has_any_ids(arrow_type.item_field):
return None
key_field = _keep_map_child(arrow_type.key_field)
value_field = _keep_map_child(arrow_type.item_field)
return pa.map_(key_field, value_field, keys_sorted=arrow_type.keys_sorted)
return arrow_type


def _keep_map_child(field: pa.Field) -> pa.Field:
"""Keep a map key or value so the map can be matched by position.

If this side has an ID, still prune nested fields without one. If pruning
would drop the type, or this side itself has no ID, leave the field as-is;
missing IDs are filled in after the map is kept.
"""
if _get_field_id(field) is None:
return field
pruned_type = _prune_type_without_ids(field.type)
if pruned_type is None:
return field
return field.with_type(pruned_type)


def _assign_missing_field_ids(field: pa.Field, ids: Iterator[int]) -> pa.Field:
"""Assign placeholder field IDs to any field that does not already have one."""
metadata = dict(field.metadata or {})
if _get_field_id(field) is None:
metadata[PYARROW_PARQUET_FIELD_ID_KEY] = str(next(ids)).encode()
new_type = _assign_missing_type_ids(field.type, ids)
return pa.field(field.name, new_type, nullable=field.nullable, metadata=metadata or None)


def _assign_missing_type_ids(arrow_type: pa.DataType, ids: Iterator[int]) -> pa.DataType:
if pa.types.is_struct(arrow_type):
children = [_assign_missing_field_ids(arrow_type.field(i), ids) for i in range(arrow_type.num_fields)]
return pa.struct(children)
elif isinstance(arrow_type, (pa.ListType, pa.LargeListType, pa.FixedSizeListType)):
element_field = _assign_missing_field_ids(arrow_type.value_field, ids)
if isinstance(arrow_type, pa.LargeListType):
return pa.large_list(element_field)
if isinstance(arrow_type, pa.FixedSizeListType):
return pa.list_(element_field, arrow_type.list_size)
return pa.list_(element_field)
elif isinstance(arrow_type, pa.MapType):
key_field = _assign_missing_field_ids(arrow_type.key_field, ids)
value_field = _assign_missing_field_ids(arrow_type.item_field, ids)
return pa.map_(key_field, value_field, keys_sorted=arrow_type.keys_sorted)
return arrow_type


def _align_map_key_value_ids(file_schema: Schema, table_schema: Schema) -> Schema:
"""Match file map key/value IDs to the table schema by position.

Java's TypeWithSchemaVisitor pairs a file map's key and value with the table
map's key and value by position, not by field ID. After pruning, a file map
may have a placeholder ID on the side that had no field ID; rewriting those
IDs here lets projection and filters find the table fields on the file schema.
"""
aligned = _align_iceberg_type(file_schema.as_struct(), table_schema.as_struct())
if not isinstance(aligned, StructType) or aligned == file_schema.as_struct():
return file_schema
return Schema(
*aligned.fields,
schema_id=file_schema.schema_id,
identifier_field_ids=list(file_schema.identifier_field_ids),
)


def _align_iceberg_type(file_type: IcebergType, table_type: IcebergType) -> IcebergType:
if isinstance(file_type, MapType) and isinstance(table_type, MapType):
return MapType(
key_id=table_type.key_id,
key_type=_align_iceberg_type(file_type.key_type, table_type.key_type),
value_id=table_type.value_id,
value_type=_align_iceberg_type(file_type.value_type, table_type.value_type),
value_required=file_type.value_required,
)
if isinstance(file_type, ListType) and isinstance(table_type, ListType):
return ListType(
element_id=file_type.element_id,
element_type=_align_iceberg_type(file_type.element_type, table_type.element_type),
element_required=file_type.element_required,
)
if isinstance(file_type, StructType) and isinstance(table_type, StructType):
table_fields = {field.field_id: field for field in table_type.fields}
fields: list[NestedField] = []
changed = False
for field in file_type.fields:
table_field = table_fields.get(field.field_id)
if table_field is None:
fields.append(field)
continue
new_type = _align_iceberg_type(field.field_type, table_field.field_type)
if new_type is field.field_type or new_type == field.field_type:
fields.append(field)
else:
changed = True
fields.append(
NestedField(
field_id=field.field_id,
name=field.name,
field_type=new_type,
required=field.required,
doc=field.doc,
)
)
return StructType(*fields) if changed else file_type
return file_type


def _pyarrow_to_schema_without_ids(
schema: pa.Schema,
downcast_ns_timestamp_to_us: bool = False,
Expand Down Expand Up @@ -1884,8 +2074,13 @@ def _task_to_record_batches(
downcast_ns_timestamp_to_us if downcast_ns_timestamp_to_us is not None else format_version <= 2
)
file_schema = pyarrow_to_schema(
physical_schema, name_mapping, downcast_ns_timestamp_to_us=downcast_ns_timestamp_to_us, format_version=format_version
physical_schema,
name_mapping,
downcast_ns_timestamp_to_us=downcast_ns_timestamp_to_us,
format_version=format_version,
prune_fields_without_ids=True,
)
file_schema = _align_map_key_value_ids(file_schema, table_schema)

# Apply column projection rules: https://iceberg.apache.org/spec/#column-projection
projected_missing_fields = _get_column_projection_values(
Expand Down Expand Up @@ -3306,6 +3501,13 @@ def parquet_file_to_data_file(io: FileIO, table_metadata: TableMetadata, file_pa

arrow_schema = parquet_metadata.schema.to_arrow_schema()

if _has_any_field_ids(arrow_schema) and not visit_pyarrow(arrow_schema, _HasIds()):
# The reader only reads the columns with field IDs, so the others would silently be read as null
raise ValueError(
f"Cannot add file {file_path}: it has field IDs on only some of its columns. "
"Columns without a field ID would be read as null."
)

schema = table_metadata.schema()
_check_pyarrow_schema_compatible(schema, arrow_schema, format_version=table_metadata.format_version)

Expand Down
Loading