Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@
*/
package org.apache.parquet.avro;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.avro.AvroRuntimeException;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.hadoop.conf.Configuration;
Expand All @@ -35,7 +38,9 @@
import org.apache.parquet.schema.GroupType;
import org.apache.parquet.schema.LogicalTypeAnnotation;
import org.apache.parquet.schema.MessageType;
import org.apache.parquet.schema.PrimitiveType;
import org.apache.parquet.schema.Type;
import org.apache.parquet.schema.Types;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -140,8 +145,22 @@ public ReadContext init(
String requestedProjectionString = configuration.get(AVRO_REQUESTED_PROJECTION);
if (requestedProjectionString != null) {
Schema avroRequestedProjection = new Schema.Parser().parse(requestedProjectionString);
projection = new AvroSchemaConverter(getDerivedListEncodingConf(configuration, fileSchema))
.convert(avroRequestedProjection);
ParquetConfiguration listEncodingConf = getDerivedListEncodingConf(configuration, fileSchema);
projection = new AvroSchemaConverter(listEncodingConf).convert(avroRequestedProjection);
Schema materializedSchema = materializedSchema(configuration, keyValueMetaData);
if (materializedSchema == null) {
// Without a read schema or an Avro schema in the file, read with the schema converted from the
// projection, as before. Converting the aligned projection instead could give its lists another
// shape, such as records for the wrappers of their elements.
materializedSchema = new AvroSchemaConverter(listEncodingConf).convert(projection);
metadata.put(AVRO_READ_SCHEMA_METADATA_KEY, materializedSchema.toString());
}
boolean oldListStructure = listEncodingConf.getBoolean(
AvroWriteSupport.WRITE_OLD_LIST_STRUCTURE, AvroWriteSupport.WRITE_OLD_LIST_STRUCTURE_DEFAULT);
projection = new MessageType(
projection.getName(),
alignListStructures(
projection, fileSchema, avroRequestedProjection, materializedSchema, oldListStructure));
}

String avroReadSchema = configuration.get(AVRO_READ_SCHEMA);
Expand Down Expand Up @@ -269,6 +288,289 @@ private static ParquetConfiguration getDerivedListEncodingConf(
return copiedConfiguration;
}

// The projection converted from the Avro schema writes every list with the same structure, so it
// only selects a list's columns if the file wrote the list that way too. Use the repeated and
// element names of each list in the file instead; the converters read all the
// backward-compatible list structures.
private static List<Type> alignListStructures(
GroupType projected, GroupType file, Schema record, Schema readRecord, boolean oldListStructure) {
List<Type> fields = new ArrayList<>(projected.getFieldCount());
for (Type field : projected.getFields()) {
Schema.Field avroField = record.getField(field.getName());
// A LIST field of a record must not be repeated; only the element of a two-level list can be
if (avroField != null
&& file.containsField(field.getName())
&& !isRepeatedList(file.getType(field.getName()))) {
fields.add(alignListStructures(
field,
file.getType(field.getName()),
avroField.schema(),
readField(readRecord, field.getName()),
oldListStructure));
} else {
fields.add(field);
}
}
return fields;
}

private static Type alignListStructures(
Type projected, Type file, Schema schema, Schema readSchema, boolean oldListStructure) {
if (projected.isPrimitive() || file.isPrimitive()) {
return projected;
}
GroupType projectedGroup = projected.asGroupType();
GroupType fileGroup = file.asGroupType();
Schema nonNullSchema = AvroSchemaConverter.getNonNull(schema);
switch (nonNullSchema.getType()) {
case RECORD:
return projectedGroup.withNewFields(
alignListStructures(projectedGroup, fileGroup, nonNullSchema, readSchema, oldListStructure));
case ARRAY:
return alignList(
projectedGroup,
fileGroup,
nonNullSchema.getElementType(),
readChild(readSchema, Schema.Type.ARRAY),
oldListStructure);
case MAP:
return alignMap(
projectedGroup,
fileGroup,
nonNullSchema.getValueType(),
readChild(readSchema, Schema.Type.MAP),
oldListStructure);
default:
return projected;
}
}

private static Type alignList(
GroupType projected,
GroupType file,
Schema elementSchema,
Schema readElementSchema,
boolean oldListStructure) {
// The list itself may be repeated, as the element of a two-level list
if (!(projected.getLogicalTypeAnnotation() instanceof LogicalTypeAnnotation.ListLogicalTypeAnnotation)
|| !(file.getLogicalTypeAnnotation() instanceof LogicalTypeAnnotation.ListLogicalTypeAnnotation)
|| file.getFieldCount() != 1
|| !file.getType(0).isRepetition(Type.Repetition.REPEATED)) {
return projected;
}
Type projectedRepeated = projected.getType(0);
Type projectedElement = oldListStructure
? projectedRepeated
: projectedRepeated.asGroupType().getType(0);
Type fileRepeated = file.getType(0);
Schema readElement = readElementSchema == null ? null : AvroSchemaConverter.getNonNull(readElementSchema);
// Decide which field is the element the same way AvroCollectionConverter does, with the schema it
// reads with. Its structural rules don't depend on the projection, so check them first, and align
// the repeated field as a wrapper only if they don't decide.
Type alignedRepeated;
boolean repeatedIsElement;
if (AvroRecordConverter.isElementType(fileRepeated, null)) {
repeatedIsElement = true;
alignedRepeated =
alignElement(projectedElement, fileRepeated, elementSchema, readElementSchema, oldListStructure);
} else {
// A group with one field that isn't repeated: the group is the element if the element is a record
// that it matches, such as points_tuple { x } for a list of records with x, and otherwise it
// wraps the element. The checks convert the repeated field to Avro, so give them only the
// projected columns: a column the projection doesn't select, such as a MAP with integer keys, can
// have a type that Avro can not represent.
GroupType fileRepeatedGroup = fileRepeated.asGroupType();
Type direct = null;
if (readElement != null
&& readElement.getType() == Schema.Type.RECORD
&& !projectedElement.isPrimitive()
&& hasFields(fileRepeatedGroup, projectedElement.asGroupType())) {
direct = alignElement(
projectedElement, fileRepeated, elementSchema, readElementSchema, oldListStructure);
}
Boolean directIsElement = direct == null ? Boolean.FALSE : isElementType(direct, readElement);
if (directIsElement == null) {
return projected;
} else if (directIsElement) {
repeatedIsElement = true;
alignedRepeated = direct;
} else {
repeatedIsElement = false;
Type wrappedElement = alignElement(
projectedElement,
fileRepeatedGroup.getType(0),
elementSchema,
readElementSchema,
oldListStructure);
alignedRepeated = wrappedElement == null ? null : fileRepeatedGroup.withNewFields(wrappedElement);
}
}
if (alignedRepeated == null) {
return projected;
}
// The converter decides again on the aligned repeated field. Pruning a group element can change that
// decision, for example when the read schema requires a field the projection leaves out, so keep the
// converted projection rather than misread the list.
if (!Boolean.valueOf(repeatedIsElement).equals(isElementType(alignedRepeated, readElement))) {
return projected;
}
return projected.withNewFields(alignedRepeated);
}

private static Type alignMap(
GroupType projected, GroupType file, Schema valueSchema, Schema readValueSchema, boolean oldListStructure) {
// Only a MAP in the file: a list of key-value records would lose the entries that repeat a key
if (!isMap(file)) {
return projected;
}
if (projected.getFieldCount() != 1
Comment thread
shivadarshan-devadiga marked this conversation as resolved.
Resolved
|| file.getFieldCount() != 1
|| file.getType(0).isPrimitive()
|| !file.getType(0).isRepetition(Type.Repetition.REPEATED)) {
return projected;
}
GroupType projectedKeyValue = projected.getType(0).asGroupType();
GroupType fileKeyValue = file.getType(0).asGroupType();
if (projectedKeyValue.getFieldCount() != 2 || fileKeyValue.getFieldCount() != 2) {
return projected;
}
// Keep the projected key type, so the requested string key is still checked against the file
Type alignedKey = alignElement(
projectedKeyValue.getType(0),
fileKeyValue.getType(0),
Schema.create(Schema.Type.STRING),
null,
oldListStructure);
Type alignedValue = alignElement(
projectedKeyValue.getType(1), fileKeyValue.getType(1), valueSchema, readValueSchema, oldListStructure);
return alignedKey == null || alignedValue == null
? projected
: projected.withNewFields(fileKeyValue.withNewFields(alignedKey, alignedValue));
}

// Returns the projected element under the name of the file's element, or null if one of them is a
// group and the other is not. The type stays the projected one, so the requested schema is still
// checked against the file. The repetition is the one the converted projection gives the element:
// repeated if the file's repeated field is the element, otherwise optional only if the Avro schema
// allows null.
private static Type alignElement(
Type projected, Type file, Schema schema, Schema readSchema, boolean oldListStructure) {
if (projected.isPrimitive() != file.isPrimitive()
|| (!projected.isPrimitive() && !sameKind(projected.asGroupType(), file.asGroupType()))) {
return null;
}
Type.Repetition repetition;
if (file.isRepetition(Type.Repetition.REPEATED)) {
repetition = Type.Repetition.REPEATED;
} else if (isNullable(schema)) {
repetition = Type.Repetition.OPTIONAL;
} else {
repetition = Type.Repetition.REQUIRED;
}
if (file.isPrimitive()) {
PrimitiveType primitive = projected.asPrimitiveType();
Types.PrimitiveBuilder<PrimitiveType> builder = Types.primitive(
primitive.getPrimitiveTypeName(), repetition)
.as(primitive.getLogicalTypeAnnotation());
if (primitive.getPrimitiveTypeName() == PrimitiveType.PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY) {
builder = builder.length(primitive.getTypeLength());
}
return builder.named(file.getName());
}
GroupType aligned = alignListStructures(projected, file, schema, readSchema, oldListStructure)
.asGroupType();
return Types.buildGroup(repetition)
Comment thread
shivadarshan-devadiga marked this conversation as resolved.
Resolved
.as(aligned.getLogicalTypeAnnotation())
.addFields(aligned.getFields().toArray(new Type[0]))
.named(file.getName());
}

// isElementType, or null if it can't convert the repeated field to Avro, such as a group with a record
// element whose name, for example string, isn't a valid name of an Avro record
private static Boolean isElementType(Type repeated, Schema elementSchema) {
try {
return AvroRecordConverter.isElementType(repeated, elementSchema);
} catch (AvroRuntimeException e) {
return null;
}
}

// Whether the group has a field for each field of the projected group
private static boolean hasFields(GroupType group, GroupType projected) {
return projected.getFields().stream().allMatch(field -> group.containsField(field.getName()));
}

// Whether the groups are both LISTs, both MAPs, or neither
private static boolean sameKind(GroupType projected, GroupType file) {
boolean projectedList =
projected.getLogicalTypeAnnotation() instanceof LogicalTypeAnnotation.ListLogicalTypeAnnotation;
boolean fileList = file.getLogicalTypeAnnotation() instanceof LogicalTypeAnnotation.ListLogicalTypeAnnotation;
return projectedList == fileList && isMap(projected) == isMap(file);
}

private static boolean isRepeatedList(Type type) {
return type.isRepetition(Type.Repetition.REPEATED)
&& type.getLogicalTypeAnnotation() instanceof LogicalTypeAnnotation.ListLogicalTypeAnnotation;
}

// Whether the group is a MAP in the file, also with the MAP_KEY_VALUE annotation older writers use
private static boolean isMap(GroupType group) {
LogicalTypeAnnotation annotation = group.getLogicalTypeAnnotation();
return annotation instanceof LogicalTypeAnnotation.MapLogicalTypeAnnotation
|| annotation instanceof LogicalTypeAnnotation.MapKeyValueTypeAnnotation
|| (group.getFieldCount() == 1
&& group.getType(0).getLogicalTypeAnnotation()
instanceof LogicalTypeAnnotation.MapKeyValueTypeAnnotation);
}

// The Avro schema the converters read with, as prepareForRead chooses it, or null if the file has
// none and the caller sets no read schema.
private static Schema materializedSchema(ParquetConfiguration configuration, Map<String, String> keyValueMetaData) {
String schema = configuration.get(AVRO_READ_SCHEMA);
if (schema == null) {
schema = keyValueMetaData.get(AVRO_SCHEMA_METADATA_KEY);
}
if (schema == null) {
schema = keyValueMetaData.get(OLD_AVRO_SCHEMA_METADATA_KEY);
}
return schema == null ? null : new Schema.Parser().parse(schema);
}

private static Schema readField(Schema readRecord, String name) {
if (readRecord == null) {
return null;
}
Schema record = AvroSchemaConverter.getNonNull(readRecord);
if (record.getType() != Schema.Type.RECORD) {
return null;
}
Schema.Field field = record.getField(name);
if (field == null) {
// The converters also match a field of the read schema by its aliases
field = record.getFields().stream()
.filter(f -> f.aliases().contains(name))
.findFirst()
.orElse(null);
}
return field == null ? null : field.schema();
}

private static Schema readChild(Schema readSchema, Schema.Type type) {
if (readSchema == null) {
return null;
}
Schema schema = AvroSchemaConverter.getNonNull(readSchema);
if (schema.getType() != type) {
return null;
}
return type == Schema.Type.ARRAY ? schema.getElementType() : schema.getValueType();
}

private static boolean isNullable(Schema schema) {
return schema.getType() == Schema.Type.UNION
&& schema.getTypes().stream().anyMatch(s -> s.getType() == Schema.Type.NULL);
}

private static boolean writesNewListStructure(MessageType schema) {
return Boolean.TRUE.equals(allListStructuresAreThreeLevel(schema));
}
Expand Down
Loading