diff --git a/CHANGES.md b/CHANGES.md index a3adbb3d7af9..02ad2acf0e09 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -167,6 +167,7 @@ ## Bugfixes +* (Java) `DropFields` no longer moves the remaining fields of a nested row to the top level when some of its fields are dropped. For example, dropping `nested.a` from a row with fields `nested.a` and `nested.b` now yields a row with field `nested.b` instead of `b`. This changes the output schema of pipelines that drop nested fields ([#21640](https://github.com/apache/beam/issues/21640)). * (Python) Fixed RunInference failing with `TypeError: cannot create weak reference to 'dict' object` when `ModelHandler.load_model()` returns a model that can't be weakly referenced, such as a `dict` or `list` ([#41351](https://github.com/apache/beam/issues/41351)). * (Java) Flink `OrderedListState` now preserves multiple values with the same timestamp when reading state or clearing a different timestamp range ([#39782](https://github.com/apache/beam/issues/39782)). * (Python) Fixed Vertex AI embedding transforms ignoring `project`, `location` and `credentials` on remote workers ([#41957](https://github.com/apache/beam/pull/41957)). diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/DropFields.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/DropFields.java index c3dc18f1cdd5..e17aa830aebb 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/DropFields.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/DropFields.java @@ -18,19 +18,25 @@ package org.apache.beam.sdk.schemas.transforms; import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkArgument; -import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Lists.newArrayList; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.beam.sdk.schemas.FieldAccessDescriptor; +import org.apache.beam.sdk.schemas.FieldAccessDescriptor.FieldDescriptor; +import org.apache.beam.sdk.schemas.FieldAccessDescriptor.FieldDescriptor.Qualifier; import org.apache.beam.sdk.schemas.Schema; import org.apache.beam.sdk.schemas.Schema.Field; import org.apache.beam.sdk.schemas.Schema.FieldType; +import org.apache.beam.sdk.schemas.Schema.TypeName; +import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.PTransform; +import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.Row; -import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Maps; +import org.checkerframework.checker.nullness.qual.Nullable; /** * A transform to drop fields from a schema. @@ -83,66 +89,182 @@ private Inner(FieldAccessDescriptor fieldsToDrop) { this.fieldsToDrop = fieldsToDrop; } - FieldAccessDescriptor complement(Schema inputSchema, FieldAccessDescriptor input) { - // Create a FieldAccessDescriptor that select all fields _not_ selected in the input - // descriptor. Maintain the original order of the schema. - List fieldNamesToSelect = newArrayList(); - Map nestedFieldsToSelect = - Maps.newHashMap(); - for (int i = 0; i < inputSchema.getFieldCount(); ++i) { - if (input.fieldIdsAccessed().contains(i)) { - // This field is selected, so exclude it from the complement. - continue; - } - Field field = inputSchema.getField(i); - Map nestedFields = - input.getNestedFieldsAccessed().keySet().stream() - .collect(Collectors.toMap(k -> k.getFieldId(), k -> k)); - - FieldAccessDescriptor.FieldDescriptor fieldDescriptor = nestedFields.get(i); - if (fieldDescriptor != null) { - // Some subfields are selected, so recursively calculate the complementary subfields to - // select. - FieldType fieldType = inputSchema.getField(i).getType(); - for (FieldAccessDescriptor.FieldDescriptor.Qualifier qualifier : - fieldDescriptor.getQualifiers()) { - switch (qualifier.getKind()) { - case LIST: - fieldType = fieldType.getCollectionElementType(); - break; - case MAP: - fieldType = fieldType.getMapValueType(); - break; - default: - throw new RuntimeException("Unexpected field descriptor type."); - } - } - checkArgument(fieldType.getTypeName().isCompositeType()); - FieldAccessDescriptor nestedDescriptor = - input.getNestedFieldsAccessed().get(fieldDescriptor); - nestedFieldsToSelect.put( - fieldDescriptor, complement(fieldType.getRowSchema(), nestedDescriptor)); - } else { - // Neither the field nor the subfield is selected. This means we should select it. - fieldNamesToSelect.add(field.getName()); - } + @Override + public PCollection expand(PCollection input) { + Schema inputSchema = input.getSchema(); + FieldAccessDescriptor resolved = fieldsToDrop.resolve(inputSchema); + Schema outputSchema = dropFields(inputSchema, resolved); + + return input + .apply(ParDo.of(new DropFieldsDoFn<>(resolved, outputSchema))) + .setRowSchema(outputSchema); + } + } + + private static class DropFieldsDoFn extends DoFn { + private final FieldAccessDescriptor fieldsToDrop; + private final Schema outputSchema; + + @SuppressWarnings("unused") + @FieldAccess("allFields") + final FieldAccessDescriptor fieldAccess = FieldAccessDescriptor.withAllFields(); + + DropFieldsDoFn(FieldAccessDescriptor fieldsToDrop, Schema outputSchema) { + this.fieldsToDrop = fieldsToDrop; + this.outputSchema = outputSchema; + } + + @ProcessElement + public void process(@FieldAccess("allFields") @Element Row row, OutputReceiver o) { + o.output(dropFields(row, outputSchema, fieldsToDrop)); + } + } + + /** + * Returns the schema with the given fields removed. Rows that only have some of their fields + * dropped keep their position and nesting in the schema. + */ + private static Schema dropFields(Schema schema, FieldAccessDescriptor fieldsToDrop) { + Map nestedFieldsToDrop = nestedFieldsById(fieldsToDrop); + Schema.Builder builder = Schema.builder().setOptions(schema.getOptions()); + for (int i = 0; i < schema.getFieldCount(); ++i) { + if (fieldsToDrop.fieldIdsAccessed().contains(i)) { + continue; } + Field field = schema.getField(i); + FieldDescriptor nestedField = nestedFieldsToDrop.get(i); + if (nestedField != null) { + field = + field.withType( + dropFields( + field.getType(), + nestedField.getQualifiers(), + 0, + fieldsToDrop.getNestedFieldsAccessed().get(nestedField))); + } + builder.addField(field); + } + return builder.build(); + } - FieldAccessDescriptor fieldAccess = FieldAccessDescriptor.withFieldNames(fieldNamesToSelect); - for (Map.Entry entry : - nestedFieldsToSelect.entrySet()) { - fieldAccess = fieldAccess.withNestedField(entry.getKey(), entry.getValue()); + private static FieldType dropFields( + FieldType fieldType, + List qualifiers, + int qualifierIndex, + FieldAccessDescriptor fieldsToDrop) { + FieldType newType; + if (qualifierIndex == qualifiers.size()) { + checkArgument( + fieldType.getTypeName().isCompositeType(), + "Cannot drop subfields of a field of type %s", + fieldType); + newType = FieldType.row(dropFields(fieldType.getRowSchema(), fieldsToDrop)); + } else { + switch (qualifiers.get(qualifierIndex).getKind()) { + case LIST: + FieldType elementType = + dropFields( + fieldType.getCollectionElementType(), + qualifiers, + qualifierIndex + 1, + fieldsToDrop); + newType = + fieldType.getTypeName() == TypeName.ITERABLE + ? FieldType.iterable(elementType) + : FieldType.array(elementType); + break; + case MAP: + newType = + FieldType.map( + fieldType.getMapKeyType(), + dropFields( + fieldType.getMapValueType(), qualifiers, qualifierIndex + 1, fieldsToDrop)); + break; + default: + throw new IllegalArgumentException( + "Unexpected qualifier " + qualifiers.get(qualifierIndex).getKind()); } - return fieldAccess.resolve(inputSchema); } + return newType.withNullable(fieldType.getNullable()).withMetadata(fieldType.getAllMetadata()); + } - @Override - public PCollection expand(PCollection input) { - Schema inputSchema = input.getSchema(); - FieldAccessDescriptor selectDescriptor = - complement(inputSchema, fieldsToDrop.resolve(inputSchema)); + /** Returns the row with the given fields removed, matching {@code outputSchema}. */ + private static @Nullable Row dropFields( + @Nullable Row row, Schema outputSchema, FieldAccessDescriptor fieldsToDrop) { + if (row == null) { + return null; + } + Map nestedFieldsToDrop = nestedFieldsById(fieldsToDrop); + List<@Nullable Object> values = new ArrayList<>(outputSchema.getFieldCount()); + int outputFieldIndex = 0; + for (int i = 0; i < row.getFieldCount(); ++i) { + if (fieldsToDrop.fieldIdsAccessed().contains(i)) { + continue; + } + Object value = row.getValue(i); + FieldDescriptor nestedField = nestedFieldsToDrop.get(i); + if (nestedField != null) { + value = + dropFields( + value, + outputSchema.getField(outputFieldIndex).getType(), + nestedField.getQualifiers(), + 0, + fieldsToDrop.getNestedFieldsAccessed().get(nestedField)); + } + values.add(value); + ++outputFieldIndex; + } + return Row.withSchema(outputSchema).addValues(values).build(); + } - return input.apply(Select.fieldAccess(selectDescriptor)); + private static @Nullable Object dropFields( + @Nullable Object value, + FieldType outputType, + List qualifiers, + int qualifierIndex, + FieldAccessDescriptor fieldsToDrop) { + if (value == null) { + return null; } + if (qualifierIndex == qualifiers.size()) { + return dropFields((Row) value, outputType.getRowSchema(), fieldsToDrop); + } + switch (qualifiers.get(qualifierIndex).getKind()) { + case LIST: + List<@Nullable Object> list = new ArrayList<>(); + for (Object element : (Iterable) value) { + list.add( + dropFields( + element, + outputType.getCollectionElementType(), + qualifiers, + qualifierIndex + 1, + fieldsToDrop)); + } + return list; + case MAP: + Map map = new HashMap<>(); + for (Map.Entry entry : ((Map) value).entrySet()) { + map.put( + entry.getKey(), + dropFields( + entry.getValue(), + outputType.getMapValueType(), + qualifiers, + qualifierIndex + 1, + fieldsToDrop)); + } + return map; + default: + throw new IllegalArgumentException( + "Unexpected qualifier " + qualifiers.get(qualifierIndex).getKind()); + } + } + + private static Map nestedFieldsById( + FieldAccessDescriptor fieldsToDrop) { + return fieldsToDrop.getNestedFieldsAccessed().keySet().stream() + .collect(Collectors.toMap(FieldDescriptor::getFieldId, f -> f)); } } diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/DropFieldsTest.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/DropFieldsTest.java index eb08f168c35f..358713844283 100644 --- a/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/DropFieldsTest.java +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/schemas/transforms/DropFieldsTest.java @@ -31,6 +31,7 @@ import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.Row; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Lists; import org.junit.Rule; import org.junit.Test; @@ -96,11 +97,17 @@ public void testDropTopLevelField() { pipeline.run(); } + private static final Schema FIELD2_SCHEMA = Schema.builder().addStringField("field2").build(); + + private static Row field2Row(String field2) { + return Row.withSchema(FIELD2_SCHEMA).addValue(field2).build(); + } + @Test @Category(NeedsRunner.class) public void testDropNestedField() { Schema expectedSchema = - Schema.builder().addStringField("string").addStringField("field2").build(); + Schema.builder().addRowField("nested", FIELD2_SCHEMA).addStringField("string").build(); PCollection result = pipeline @@ -115,9 +122,9 @@ public void testDropNestedField() { List expectedRows = Lists.newArrayList( - Row.withSchema(expectedSchema).addValues("foo", "one").build(), - Row.withSchema(expectedSchema).addValues("foo", "two").build(), - Row.withSchema(expectedSchema).addValues("foo", "three").build()); + Row.withSchema(expectedSchema).addValues(field2Row("one"), "foo").build(), + Row.withSchema(expectedSchema).addValues(field2Row("two"), "foo").build(), + Row.withSchema(expectedSchema).addValues(field2Row("three"), "foo").build()); PAssert.that(result).containsInAnyOrder(expectedRows); pipeline.run(); @@ -126,7 +133,7 @@ public void testDropNestedField() { @Test @Category(NeedsRunner.class) public void testDropNestedFieldKeepingOnlyNested() { - Schema expectedSchema = Schema.builder().addStringField("field2").build(); + Schema expectedSchema = Schema.builder().addRowField("nested", FIELD2_SCHEMA).build(); PCollection result = pipeline @@ -141,19 +148,59 @@ public void testDropNestedFieldKeepingOnlyNested() { List expectedRows = Lists.newArrayList( - Row.withSchema(expectedSchema).addValue("one").build(), - Row.withSchema(expectedSchema).addValue("two").build(), - Row.withSchema(expectedSchema).addValue("three").build()); + Row.withSchema(expectedSchema).addValue(field2Row("one")).build(), + Row.withSchema(expectedSchema).addValue(field2Row("two")).build(), + Row.withSchema(expectedSchema).addValue(field2Row("three")).build()); PAssert.that(result).containsInAnyOrder(expectedRows); pipeline.run(); } - // drop making sure a nested field remains. + @Test + @Category(NeedsRunner.class) + public void testDropNestedFieldKeepsOtherNestedRows() { + Schema inputSchema = + Schema.builder() + .addRowField("a", SIMPLE_SCHEMA) + .addRowField("b", SIMPLE_SCHEMA) + .addNullableField("c", FieldType.row(SIMPLE_SCHEMA)) + .build(); + Schema expectedSchema = + Schema.builder() + .addRowField("a", FIELD2_SCHEMA) + .addRowField("b", SIMPLE_SCHEMA) + .addNullableField("c", FieldType.row(FIELD2_SCHEMA)) + .build(); + + PCollection result = + pipeline + .apply( + Create.of( + Row.withSchema(inputSchema) + .addValues(simpleRow(1, "a1"), simpleRow(2, "b2"), simpleRow(3, "c3")) + .build(), + Row.withSchema(inputSchema) + .addValues(simpleRow(4, "a4"), simpleRow(5, "b5"), null) + .build()) + .withRowSchema(inputSchema)) + .apply(DropFields.fields("a.field1", "c.field1")); + assertEquals(expectedSchema, result.getSchema()); + + PAssert.that(result) + .containsInAnyOrder( + Row.withSchema(expectedSchema) + .addValues(field2Row("a1"), simpleRow(2, "b2"), field2Row("c3")) + .build(), + Row.withSchema(expectedSchema) + .addValues(field2Row("a4"), simpleRow(5, "b5"), null) + .build()); + pipeline.run(); + } @Test @Category(NeedsRunner.class) public void testDropNestedArrayField() { - Schema expectedSchema = Schema.builder().addArrayField("field2", FieldType.STRING).build(); + Schema expectedSchema = + Schema.builder().addArrayField("array", FieldType.row(FIELD2_SCHEMA)).build(); PCollection result = pipeline @@ -168,13 +215,44 @@ public void testDropNestedArrayField() { List expectedRows = Lists.newArrayList( - Row.withSchema(expectedSchema).addArray("one1", "one2").build(), - Row.withSchema(expectedSchema).addArray("two1", "two2").build(), - Row.withSchema(expectedSchema).addArray("three1", "three2").build()); + Row.withSchema(expectedSchema).addArray(field2Row("one1"), field2Row("one2")).build(), + Row.withSchema(expectedSchema).addArray(field2Row("two1"), field2Row("two2")).build(), + Row.withSchema(expectedSchema) + .addArray(field2Row("three1"), field2Row("three2")) + .build()); PAssert.that(result).containsInAnyOrder(expectedRows); pipeline.run(); } + @Test + @Category(NeedsRunner.class) + public void testDropNestedMapField() { + Schema inputSchema = + Schema.builder().addMapField("map", FieldType.STRING, FieldType.row(SIMPLE_SCHEMA)).build(); + Schema expectedSchema = + Schema.builder().addMapField("map", FieldType.STRING, FieldType.row(FIELD2_SCHEMA)).build(); + + PCollection result = + pipeline + .apply( + Create.of( + Row.withSchema(inputSchema) + .addValue( + ImmutableMap.of( + "k1", simpleRow(1, "one"), "k2", simpleRow(2, "two"))) + .build()) + .withRowSchema(inputSchema)) + .apply(DropFields.fields("map{}.field1")); + assertEquals(expectedSchema, result.getSchema()); + + PAssert.that(result) + .containsInAnyOrder( + Row.withSchema(expectedSchema) + .addValue(ImmutableMap.of("k1", field2Row("one"), "k2", field2Row("two"))) + .build()); + pipeline.run(); + } + @Test @Category(NeedsRunner.class) public void testMaintainsOriginalSchemaOrder() {