rdblue commented on code in PR #12496:
URL: https://github.com/apache/iceberg/pull/12496#discussion_r2007936907


##########
parquet/src/main/java/org/apache/iceberg/parquet/ParquetMetrics.java:
##########
@@ -0,0 +1,613 @@
+/*
+ *
+ *  * 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.parquet;
+
+import java.nio.ByteBuffer;
+import java.util.Comparator;
+import java.util.Deque;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.apache.iceberg.FieldMetrics;
+import org.apache.iceberg.Metrics;
+import org.apache.iceberg.MetricsConfig;
+import org.apache.iceberg.MetricsModes;
+import org.apache.iceberg.MetricsUtil;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Multimap;
+import org.apache.iceberg.relocated.com.google.common.collect.Multimaps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.relocated.com.google.common.collect.Streams;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.Conversions;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.NaNUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.iceberg.variants.PhysicalType;
+import org.apache.iceberg.variants.ShreddedObject;
+import org.apache.iceberg.variants.VariantMetadata;
+import org.apache.iceberg.variants.VariantValue;
+import org.apache.iceberg.variants.Variants;
+import org.apache.parquet.column.statistics.Statistics;
+import org.apache.parquet.hadoop.metadata.BlockMetaData;
+import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData;
+import org.apache.parquet.hadoop.metadata.ColumnPath;
+import org.apache.parquet.hadoop.metadata.ParquetMetadata;
+import org.apache.parquet.schema.GroupType;
+import org.apache.parquet.schema.MessageType;
+import org.apache.parquet.schema.PrimitiveType;
+import org.apache.parquet.schema.Type;
+
+class ParquetMetrics {
+  private ParquetMetrics() {}
+
+  static Metrics metrics(
+      Schema schema,
+      MessageType type,
+      MetricsConfig metricsConfig,
+      ParquetMetadata metadata,
+      Stream<FieldMetrics<?>> fields) {
+    long rowCount = 0L;
+    Map<Integer, Long> columnSizes = Maps.newHashMap();
+    Multimap<ColumnPath, ColumnChunkMetaData> columns =
+        Multimaps.newMultimap(Maps.newHashMap(), Lists::newArrayList);
+    for (BlockMetaData block : metadata.getBlocks()) {
+      rowCount += block.getRowCount();
+      for (ColumnChunkMetaData column : block.getColumns()) {
+        Type.ID id =
+            
type.getColumnDescription(column.getPath().toArray()).getPrimitiveType().getId();
+        if (null == id) {
+          continue;
+        }
+
+        int fieldId = id.intValue();
+        MetricsModes.MetricsMode mode = MetricsUtil.metricsMode(schema, 
metricsConfig, fieldId);
+        if (mode != MetricsModes.None.get()) {
+          columns.put(column.getPath(), column);
+          columnSizes.put(fieldId, columnSizes.getOrDefault(fieldId, 0L) + 
column.getTotalSize());
+        }
+      }
+    }
+
+    Map<Integer, FieldMetrics<?>> metricsById =
+        fields.collect(Collectors.toMap(FieldMetrics::id, 
Function.identity()));
+
+    Iterable<FieldMetrics<ByteBuffer>> results =
+        TypeWithSchemaVisitor.visit(
+            schema.asStruct(),
+            type,
+            new MetricsVisitor(schema, metricsConfig, metricsById, columns));
+
+    Map<Integer, Long> valueCounts = Maps.newHashMap();
+    Map<Integer, Long> nullValueCounts = Maps.newHashMap();
+    Map<Integer, Long> nanValueCounts = Maps.newHashMap();
+    Map<Integer, ByteBuffer> lowerBounds = Maps.newHashMap();
+    Map<Integer, ByteBuffer> upperBounds = Maps.newHashMap();
+
+    for (FieldMetrics<ByteBuffer> metrics : results) {
+      int id = metrics.id();
+      if (metrics.valueCount() >= 0) {
+        valueCounts.put(id, metrics.valueCount());
+      }
+
+      if (metrics.nullValueCount() >= 0) {
+        nullValueCounts.put(id, metrics.nullValueCount());
+      }
+
+      if (metrics.nanValueCount() >= 0) {
+        nanValueCounts.put(id, metrics.nanValueCount());
+      }
+
+      if (metrics.hasBounds()) {
+        lowerBounds.put(id, metrics.lowerBound());
+        upperBounds.put(id, metrics.upperBound());
+      }
+    }
+
+    return new Metrics(
+        rowCount,
+        columnSizes,
+        valueCounts,
+        nullValueCounts,
+        nanValueCounts,
+        lowerBounds,
+        upperBounds);
+  }
+
+  private static class MetricsVisitor
+      extends TypeWithSchemaVisitor<Iterable<FieldMetrics<ByteBuffer>>> {
+    private final Schema schema;
+    private final MetricsConfig metricsConfig;
+    private final Map<Integer, FieldMetrics<?>> metricsById;
+    private final Multimap<ColumnPath, ColumnChunkMetaData> columns;
+
+    private MetricsVisitor(
+        Schema schema,
+        MetricsConfig metricsConfig,
+        Map<Integer, FieldMetrics<?>> metricsById,
+        Multimap<ColumnPath, ColumnChunkMetaData> columns) {
+      this.schema = schema;
+      this.metricsConfig = metricsConfig;
+      this.metricsById = metricsById;
+      this.columns = columns;
+    }
+
+    @Override
+    public Iterable<FieldMetrics<ByteBuffer>> message(
+        Types.StructType iStruct,
+        MessageType message,
+        List<Iterable<FieldMetrics<ByteBuffer>>> fieldResults) {
+      return Iterables.concat(fieldResults);
+    }
+
+    @Override
+    public Iterable<FieldMetrics<ByteBuffer>> struct(
+        Types.StructType iStruct,
+        GroupType struct,
+        List<Iterable<FieldMetrics<ByteBuffer>>> fieldResults) {
+      return Iterables.concat(fieldResults);
+    }
+
+    @Override
+    public Iterable<FieldMetrics<ByteBuffer>> list(
+        Types.ListType iList, GroupType array, 
Iterable<FieldMetrics<ByteBuffer>> elementResults) {
+      // remove lower and upper bounds for repeated fields
+      return ImmutableList.of();
+    }
+
+    @Override
+    public Iterable<FieldMetrics<ByteBuffer>> map(
+        Types.MapType iMap,
+        GroupType map,
+        Iterable<FieldMetrics<ByteBuffer>> keyResults,
+        Iterable<FieldMetrics<ByteBuffer>> valueResults) {
+      // repeated fields are not currently supported
+      return ImmutableList.of();
+    }
+
+    @Override
+    public Iterable<FieldMetrics<ByteBuffer>> primitive(
+        org.apache.iceberg.types.Type.PrimitiveType iPrimitive, PrimitiveType 
primitive) {
+      Type.ID id = primitive.getId();
+      if (null == id) {
+        return ImmutableList.of();
+      }
+      int fieldId = id.intValue();
+
+      MetricsModes.MetricsMode mode = MetricsUtil.metricsMode(schema, 
metricsConfig, fieldId);
+      if (mode == MetricsModes.None.get()) {
+        return ImmutableList.of();
+      }
+
+      int length = truncateLength(mode);
+
+      FieldMetrics<ByteBuffer> metrics = metricsFromFieldMetrics(fieldId, 
iPrimitive, length);
+      if (metrics != null) {
+        return ImmutableList.of(metrics);
+      }
+
+      metrics = metricsFromFooter(fieldId, iPrimitive, primitive, length);
+      if (metrics != null) {
+        return ImmutableList.of(metrics);
+      }
+
+      return ImmutableList.of();
+    }
+
+    private FieldMetrics<ByteBuffer> metricsFromFieldMetrics(
+        int fieldId, org.apache.iceberg.types.Type.PrimitiveType icebergType, 
int truncateLength) {
+      FieldMetrics<?> fieldMetrics = metricsById.get(fieldId);
+      if (null == fieldMetrics) {
+        return null;
+      } else if (truncateLength <= 0) {
+        return new FieldMetrics<>(
+            fieldMetrics.id(),
+            fieldMetrics.valueCount(),
+            fieldMetrics.nullValueCount(),
+            fieldMetrics.nanValueCount());
+      } else {
+        Object lowerBound =
+            truncateLowerBound(icebergType, fieldMetrics.lowerBound(), 
truncateLength);
+        Object upperBound =
+            truncateUpperBound(icebergType, fieldMetrics.upperBound(), 
truncateLength);
+        ByteBuffer lower = Conversions.toByteBuffer(icebergType, lowerBound);
+        ByteBuffer upper = Conversions.toByteBuffer(icebergType, upperBound);
+        return new FieldMetrics<>(
+            fieldMetrics.id(),
+            fieldMetrics.valueCount(),
+            fieldMetrics.nullValueCount(),
+            fieldMetrics.nanValueCount(),
+            lower,
+            upper);
+      }
+    }
+
+    private FieldMetrics<ByteBuffer> metricsFromFooter(
+        int fieldId,
+        org.apache.iceberg.types.Type.PrimitiveType icebergType,
+        PrimitiveType primitive,
+        int truncateLength) {
+      if (primitive.getPrimitiveTypeName() == 
PrimitiveType.PrimitiveTypeName.INT96) {
+        return null;
+      } else if (truncateLength <= 0) {
+        return counts(fieldId);
+      } else {
+        return bounds(fieldId, icebergType, primitive, truncateLength);
+      }
+    }
+
+    private FieldMetrics<ByteBuffer> counts(int fieldId) {
+      ColumnPath path = ColumnPath.get(currentPath());
+      long valueCount = 0;
+      long nullCount = 0;
+
+      for (ColumnChunkMetaData column : columns.get(path)) {
+        Statistics<?> stats = column.getStatistics();
+        if (stats == null || stats.isEmpty()) {
+          return null;
+        }
+
+        nullCount += stats.getNumNulls();
+        valueCount += column.getValueCount();
+      }
+
+      return new FieldMetrics<>(fieldId, valueCount, nullCount);
+    }
+
+    private <T> FieldMetrics<ByteBuffer> bounds(
+        int fieldId,
+        org.apache.iceberg.types.Type.PrimitiveType icebergType,
+        PrimitiveType primitive,
+        int truncateLength) {
+      if (icebergType == null) {
+        return null;
+      }
+
+      ColumnPath path = ColumnPath.get(currentPath());
+      Comparator<T> comparator = Comparators.forType(icebergType);
+      long valueCount = 0;
+      long nullCount = 0;
+      T lowerBound = null;
+      T upperBound = null;
+
+      for (ColumnChunkMetaData column : columns.get(path)) {
+        Statistics<?> stats = column.getStatistics();
+        if (stats == null || stats.isEmpty()) {
+          return null;
+        }
+
+        nullCount += stats.getNumNulls();
+        valueCount += column.getValueCount();
+
+        if (stats.hasNonNullValue()) {
+          T chunkMin =
+              ParquetConversions.convertValue(icebergType, primitive, 
stats.genericGetMin());
+          if (lowerBound == null || comparator.compare(chunkMin, lowerBound) < 
0) {
+            lowerBound = chunkMin;
+          }
+
+          T chunkMax =
+              ParquetConversions.convertValue(icebergType, primitive, 
stats.genericGetMax());
+          if (upperBound == null || comparator.compare(chunkMax, upperBound) > 
0) {
+            upperBound = chunkMax;
+          }
+        }
+      }
+
+      if (NaNUtil.isNaN(lowerBound) || NaNUtil.isNaN(upperBound)) {
+        return new FieldMetrics<>(fieldId, valueCount, nullCount);
+      }
+
+      lowerBound = truncateLowerBound(icebergType, lowerBound, truncateLength);
+      upperBound = truncateUpperBound(icebergType, upperBound, truncateLength);
+
+      ByteBuffer lower = Conversions.toByteBuffer(icebergType, lowerBound);
+      ByteBuffer upper = Conversions.toByteBuffer(icebergType, upperBound);
+
+      return new FieldMetrics<>(fieldId, valueCount, nullCount, lower, upper);
+    }
+
+    @Override
+    public Iterable<FieldMetrics<ByteBuffer>> variant(
+        Types.VariantType iVariant, GroupType variant, 
Iterable<FieldMetrics<ByteBuffer>> ignored) {
+      Type.ID id = variant.getId();
+      if (null == id) {
+        return ImmutableList.of();
+      }
+      int fieldId = id.intValue();
+
+      MetricsModes.MetricsMode mode = MetricsUtil.metricsMode(schema, 
metricsConfig, fieldId);
+      if (mode == MetricsModes.None.get()) {
+        return ImmutableList.of();
+      }
+
+      List<ParquetVariantUtil.VariantMetrics> results =
+          Lists.newArrayList(
+              ParquetVariantVisitor.visit(variant, new 
MetricsVariantVisitor(currentPath())));
+
+      if (results.size() <= 1) {
+        return ImmutableList.of();
+      }
+
+      ParquetVariantUtil.VariantMetrics metadataCounts = results.get(0);
+      if (mode == MetricsModes.Counts.get()) {
+        return ImmutableList.of(
+            new FieldMetrics<>(fieldId, metadataCounts.valueCount(), 
metadataCounts.nullCount()));
+      }
+
+      Set<String> fieldNames = Sets.newTreeSet();
+      for (ParquetVariantUtil.VariantMetrics result : results.subList(1, 
results.size())) {
+        fieldNames.add(result.fieldName());
+      }
+
+      VariantMetadata metadata = Variants.metadata(fieldNames);
+      ShreddedObject lowerBounds = Variants.object(metadata);
+      ShreddedObject upperBounds = Variants.object(metadata);
+      for (ParquetVariantUtil.VariantMetrics result : results.subList(1, 
results.size())) {
+        String fieldName = result.fieldName();
+        lowerBounds.put(fieldName, result.lowerBound());
+        upperBounds.put(fieldName, result.upperBound());
+      }
+
+      return ImmutableList.of(
+          new FieldMetrics<>(

Review Comment:
   Right now, I just wanted to get the basics working so I went with the 
simplest implementation. We should definitely revisit this and discuss how to 
configure metrics collection.
   
   That said, I think the mode isn't the right problem to solve. For the mode, 
we don't keep counts other than the top-level value and null count for the 
variant itself. That leaves only how to handle lower and upper bounds, where we 
know that `truncate` is the right config and 16 is a reasonable length default. 
At that point, the only question is whether we want to hard-code it, pass 
through the mode for the variant column to use a configurable length for all 
sub-fields, or if we want to have a truncate length for each field individually.
   
   The bigger problem is which fields to collect metrics for. Restricting the 
fields to just the ones that are shredded is a good heuristic because we don't 
expect types to be uniform for other fields, and a value of another type will 
prevent the field's bounds from being stored. Even then, there could be quite a 
few fields and that will make the lower and upper bound payloads large. We may 
want to further restrict the number of fields, but for now I think the 
reasonable path forward is to use the shredded fields. Then we can see if we 
want to change it once we tackle the problem of how we determine the fields to 
shred.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org
For additional commands, e-mail: issues-h...@iceberg.apache.org

Reply via email to