Skip to content

Commit

Permalink
Support to field filtering of complex union type in Avro (#149)
Browse files Browse the repository at this point in the history
* Support to field filtering of complex union type in Avro
Co-authored-by: Yiqiang Ding <[email protected]>
  • Loading branch information
yiqiangin authored Jul 21, 2023
1 parent ca4f26b commit 3959284
Show file tree
Hide file tree
Showing 11 changed files with 625 additions and 44 deletions.
8 changes: 7 additions & 1 deletion core/src/main/java/org/apache/iceberg/avro/Avro.java
Original file line number Diff line number Diff line change
Expand Up @@ -385,12 +385,18 @@ public static class ReadBuilder {
};
private Long start = null;
private Long length = null;
private Schema fileSchema = null;

private ReadBuilder(InputFile file) {
Preconditions.checkNotNull(file, "Input file cannot be null");
this.file = file;
}

public ReadBuilder setFileSchema(Schema fileSchema) {
this.fileSchema = fileSchema;
return this;
}

public ReadBuilder createReaderFunc(Function<Schema, DatumReader<?>> readerFunction) {
Preconditions.checkState(createReaderBiFunc == null, "Cannot set multiple createReaderFunc");
this.createReaderFunc = readerFunction;
Expand Down Expand Up @@ -458,7 +464,7 @@ public <D> AvroIterable<D> build() {
}

return new AvroIterable<>(file,
new ProjectionDatumReader<>(readerFunc, schema, renames, nameMapping),
new ProjectionDatumReader<>(readerFunc, schema, renames, nameMapping, fileSchema),
start, length, reuseContainers);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,15 @@
import java.util.Deque;
import java.util.List;
import org.apache.avro.Schema;
import org.apache.iceberg.mapping.MappedFields;
import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
import org.apache.iceberg.relocated.com.google.common.collect.Lists;
import org.apache.iceberg.types.Type;
import org.apache.iceberg.types.Types;

public abstract class AvroSchemaWithTypeVisitor<T> {
private static final String UNION_TAG_FIELD_NAME = "tag";

public static <T> T visit(org.apache.iceberg.Schema iSchema, Schema schema, AvroSchemaWithTypeVisitor<T> visitor) {
return visit(iSchema.asStruct(), schema, visitor);
}
Expand Down Expand Up @@ -97,17 +100,92 @@ private static <T> T visitUnion(Type type, Schema union, AvroSchemaWithTypeVisit
options.add(visit(type, branch, visitor));
}
} else { // complex union case
int index = 1;
for (Schema branch : types) {
if (branch.getType() == Schema.Type.NULL) {
options.add(visit((Type) null, branch, visitor));
} else {
options.add(visit(type.asStructType().fields().get(index).type(), branch, visitor));
index += 1;
visitComplexUnion(type, union, visitor, options);
}
return visitor.union(type, union, options);
}

/*
A complex union with multiple types of Avro schema is converted into a struct with multiple fields of Iceberg schema.
Also an extra tag field is added into the struct of Iceberg schema during the conversion.
Given an example of complex union in both Avro and Iceberg:
Avro schema: {"name":"unionCol","type":["int","string"]}
Iceberg schema: struct<0: tag: required int, 1: field0: optional int, 2: field1: optional string>
The fields in the struct of Iceberg schema are expected to be stored in the same order
as the corresponding types in the union of Avro schema.
Except the tag field, the fields in the struct of Iceberg schema are the same as the types in the union of Avro schema
in the general case. In case of field projection, the fields in the struct of Iceberg schema only contains
the fields to be projected which equals to a subset of the types in the union of Avro schema.
Therefore, this function visits the complex union with the consideration of both cases.
*/
private static <T> void visitComplexUnion(Type type, Schema union,
AvroSchemaWithTypeVisitor<T> visitor, List<T> options) {
boolean nullTypeFound = false;
int typeIndex = 0;
int fieldIndexInStruct = 0;
while (typeIndex < union.getTypes().size()) {
Schema schema = union.getTypes().get(typeIndex);
// in some cases, a NULL type exists in the union of Avro schema besides the actual types,
// and it affects the index of the actual types of the order in the union
if (schema.getType() == Schema.Type.NULL) {
nullTypeFound = true;
options.add(visit((Type) null, schema, visitor));
} else {
boolean relatedFieldInStructFound = false;
Types.StructType struct = type.asStructType();
if (fieldIndexInStruct < struct.fields().size() &&
UNION_TAG_FIELD_NAME.equals(struct.fields().get(fieldIndexInStruct).name())) {
fieldIndexInStruct++;
}

if (fieldIndexInStruct < struct.fields().size()) {
// If a NULL type is found before current type, the type index is one larger than the actual type index which
// can be used to track the corresponding field in the struct of Iceberg schema.
int actualTypeIndex = nullTypeFound ? typeIndex - 1 : typeIndex;
String structFieldName = type.asStructType().fields().get(fieldIndexInStruct).name();
int indexFromStructFieldName = Integer.valueOf(structFieldName.substring(5));
if (actualTypeIndex == indexFromStructFieldName) {
relatedFieldInStructFound = true;
options.add(visit(type.asStructType().fields().get(fieldIndexInStruct).type(), schema, visitor));
fieldIndexInStruct++;
}
}

if (!relatedFieldInStructFound) {
visitNotProjectedTypeInComplexUnion(schema, visitor, options);
}
}
typeIndex++;
}
return visitor.union(type, union, options);
}

// If a field is not projected, a corresponding field in the struct of Iceberg schema cannot be found
// for current type of union in Avro schema, a reader for current type still needs to be created and
// used to make the reading of Avro file successfully. In this case, an pseudo Iceberg type is converted from
// the Avro schema and is used to create the option for the reader of the current type which still can
// read the corresponding content in Avro file successfully.
private static <T> void visitNotProjectedTypeInComplexUnion(Schema schema,
AvroSchemaWithTypeVisitor<T> visitor,
List<T> options) {
Type iType = AvroSchemaUtil.convert(schema);
if (schema.getType().equals(Schema.Type.RECORD)) {
// When the type of Avro schema is RECORD, the fields under it must have the property of "field-id".
// However, the "field-id" is not set in previous steps as the corresponding Iceberg type is not projected
// and no field id can be found for this field in Iceberg schema.
// Therefore, a name mapping is created based on the Avro schema and its corresponding Iceberg type.
// The field-id from the resulted name mapping is assigned as the property of "field-id" of each
// field under the Avro schema.
NameMappingWithAvroSchema nameMappingWithAvroSchema = new NameMappingWithAvroSchema();
MappedFields nameMapping = AvroWithPartnerByStructureVisitor.visit(
iType, schema, nameMappingWithAvroSchema);
for (Schema.Field field : schema.getFields()) {
if (!AvroSchemaUtil.hasFieldId(field)) {
int fieldId = nameMapping.id(field.name());
field.addProp(AvroSchemaUtil.FIELD_ID_PROP, fieldId);
}
}
}
options.add(visit(iType, schema, visitor));
}

private static <T> T visitArray(Type type, Schema array, AvroSchemaWithTypeVisitor<T> visitor) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import java.util.Deque;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.avro.Schema;
import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
import org.apache.iceberg.relocated.com.google.common.collect.Lists;
Expand Down Expand Up @@ -88,14 +89,22 @@ private static <P, T> T visitRecord(P struct, Schema record, AvroWithPartnerBySt

private static <P, T> T visitUnion(P type, Schema union, AvroWithPartnerByStructureVisitor<P, T> visitor) {
List<Schema> types = union.getTypes();
Preconditions.checkArgument(AvroSchemaUtil.isOptionSchema(union),
"Cannot visit non-option union: %s", union);
List<T> options = Lists.newArrayListWithExpectedSize(types.size());
for (Schema branch : types) {
if (branch.getType() == Schema.Type.NULL) {
options.add(visit(visitor.nullType(), branch, visitor));
} else {
options.add(visit(type, branch, visitor));
if (AvroSchemaUtil.isOptionSchema(union)) {
for (Schema branch : types) {
if (branch.getType() == Schema.Type.NULL) {
options.add(visit(visitor.nullType(), branch, visitor));
} else {
options.add(visit(type, branch, visitor));
}
}
} else {
List<Schema> nonNullTypes =
types.stream().filter(t -> t.getType() != Schema.Type.NULL).collect(Collectors.toList());
for (int i = 0; i < nonNullTypes.size(); i++) {
// In the case of complex union, the corresponding "type" is a struct. Non-null type i in
// the union maps to struct field i + 1 because the first struct field is the "tag".
options.add(visit(visitor.fieldNameAndType(type, i + 1).second(), nonNullTypes.get(i), visitor));
}
}
return visitor.union(type, union, options);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.apache.iceberg.avro;

import org.apache.iceberg.types.Type;
import org.apache.iceberg.types.Types;
import org.apache.iceberg.util.Pair;

/**
* This class extends {@link AvroWithPartnerByStructureVisitor} to override some functions
* related to some nested data types which help the generation of name mapping from Iceberg schema.
*
* @param <T> Return T.
*/
public class AvroWithTypeByStructureVisitor<T> extends AvroWithPartnerByStructureVisitor<Type, T> {
@Override
protected boolean isMapType(Type type) {
return type.isMapType();
}

@Override
protected boolean isStringType(Type type) {
return type.isPrimitiveType() && type.asPrimitiveType().typeId() == Type.TypeID.STRING;
}

@Override
protected Type arrayElementType(Type arrayType) {
return arrayType.asListType().elementType();
}

@Override
protected Type mapKeyType(Type mapType) {
return mapType.asMapType().keyType();
}

@Override
protected Type mapValueType(Type mapType) {
return mapType.asMapType().valueType();
}

@Override
protected Pair<String, Type> fieldNameAndType(Type structType, int pos) {
Types.NestedField field = structType.asStructType().fields().get(pos);
return Pair.of(field.name(), field.type());
}

@Override
protected Type nullType() {
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.apache.iceberg.avro;

import java.util.List;
import org.apache.avro.Schema;
import org.apache.iceberg.mapping.MappedField;
import org.apache.iceberg.mapping.MappedFields;
import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
import org.apache.iceberg.relocated.com.google.common.collect.Lists;
import org.apache.iceberg.types.Type;
import org.apache.iceberg.types.Types;

/**
* This class extends {@link AvroWithTypeByStructureVisitor} to generate the name mapping from
* Iceberg schema and the corresponding Avro schema.
*
* param Return MappedFields
*/
public class NameMappingWithAvroSchema extends AvroWithTypeByStructureVisitor<MappedFields> {
@Override
public MappedFields record(
Type struct, Schema record, List<String> names, List<MappedFields> fieldResults) {
List<MappedField> fields = Lists.newArrayListWithExpectedSize(fieldResults.size());

for (int i = 0; i < fieldResults.size(); i += 1) {
Types.NestedField field = struct.asStructType().fields().get(i);
MappedFields result = fieldResults.get(i);
fields.add(MappedField.of(field.fieldId(), field.name(), result));
}

return MappedFields.of(fields);
}

@Override
public MappedFields union(Type type, Schema union, List<MappedFields> optionResults) {
if (AvroSchemaUtil.isOptionSchema(union)) {
for (int i = 0; i < optionResults.size(); i += 1) {
if (union.getTypes().get(i).getType() != Schema.Type.NULL) {
return optionResults.get(i);
}
}
} else { // Complex union
Preconditions.checkArgument(
type instanceof Types.StructType,
"Cannot visit invalid Iceberg type: %s for Avro complex union type: %s",
type,
union);
Types.StructType struct = (Types.StructType) type;
List<MappedField> fields = Lists.newArrayListWithExpectedSize(optionResults.size());
int index = 0;
// Avro spec for union types states that unions may not contain more than one schema with the
// same type, except for the named types record, fixed and enum. For example, unions
// containing two array types or two map types are not permitted, but two types with different
// names are permitted.
// Therefore, for non-named types, use the Avro type toString() as the field mapping key. For
// named types, use the record name of the Avro type as the field mapping key.
for (Schema option : union.getTypes()) {
if (option.getType() != Schema.Type.NULL) {
// Check if current option is a named type, i.e., a RECORD, ENUM, or FIXED type. If so,
// use the record name of the Avro type as the field name. Otherwise, use the Avro
// type toString().
if (option.getType() == Schema.Type.RECORD ||
option.getType() == Schema.Type.ENUM ||
option.getType() == Schema.Type.FIXED) {
fields.add(
MappedField.of(
struct.fields().get(index).fieldId(),
option.getName(),
optionResults.get(index)));
} else {
fields.add(
MappedField.of(
struct.fields().get(index).fieldId(),
option.toString(),
optionResults.get(index)));
}

// Both iStruct and optionResults do not contain an entry for the NULL type, so we need to
// increment i only
// when we encounter a non-NULL type.
index++;
}
}
return MappedFields.of(fields);
}
return null;
}

@Override
public MappedFields array(Type list, Schema array, MappedFields elementResult) {
return MappedFields.of(MappedField.of(list.asListType().elementId(), "element", elementResult));
}

@Override
public MappedFields map(Type sMap, Schema map, MappedFields keyResult, MappedFields valueResult) {
return MappedFields.of(
MappedField.of(sMap.asMapType().keyId(), "key", keyResult),
MappedField.of(sMap.asMapType().valueId(), "value", valueResult));
}

@Override
public MappedFields map(Type sMap, Schema map, MappedFields valueResult) {
return MappedFields.of(
MappedField.of(sMap.asMapType().keyId(), "key", null),
MappedField.of(sMap.asMapType().valueId(), "value", valueResult));
}

@Override
public MappedFields primitive(Type type, Schema primitive) {
return null; // no mapping because primitives have no nested fields
}
}
Loading

0 comments on commit 3959284

Please sign in to comment.