dinoocch commented on code in PR #16678:
URL: https://github.com/apache/pinot/pull/16678#discussion_r2408265072


##########
pinot-core/src/main/java/org/apache/pinot/core/query/aggregation/function/AnyValueAggregationFunction.java:
##########
@@ -0,0 +1,394 @@
+/**
+ * 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.pinot.core.query.aggregation.function;
+
+import java.math.BigDecimal;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+import org.apache.pinot.common.CustomObject;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.utils.DataSchema.ColumnDataType;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.query.aggregation.AggregationResultHolder;
+import org.apache.pinot.core.query.aggregation.ObjectAggregationResultHolder;
+import org.apache.pinot.core.query.aggregation.groupby.GroupByResultHolder;
+import 
org.apache.pinot.core.query.aggregation.groupby.ObjectGroupByResultHolder;
+import org.apache.pinot.segment.spi.AggregationFunctionType;
+import org.apache.pinot.segment.spi.index.reader.Dictionary;
+import org.apache.pinot.spi.data.FieldSpec;
+
+
+/**
+ * AnyValue aggregation function returns any arbitrary NON-NULL value from the 
column for each group.
+ * <p>
+ * This is useful for GROUP BY queries where you want to include a column in 
SELECT that has a 1:1 mapping with the
+ * GROUP BY columns, avoiding the need to add it to GROUP BY clause. The 
implementation is null-aware and will scan
+ * only until it finds the first non-null value in the current batch for each 
group/key. This makes it O(n) over the
+ * input once per group until the first value is set, with early-exit fast 
paths when there are no nulls.
+ * </p>
+ * <p><strong>Example:</strong></p>
+ * <pre>{@code
+ * SELECT CustomerID,
+ *        ANY_VALUE(CustomerName),
+ *        SUM(OrderValue)
+ * FROM Orders
+ * GROUP BY CustomerID
+ * }</pre>
+ */
+public class AnyValueAggregationFunction extends 
NullableSingleInputAggregationFunction<Object, Comparable<?>> {
+  // Result type is determined at runtime based on input expression type
+  private ColumnDataType _resultType;
+
+  public AnyValueAggregationFunction(List<ExpressionContext> arguments, 
boolean nullHandlingEnabled) {
+    super(verifySingleArgument(arguments, "ANY_VALUE"), nullHandlingEnabled);
+    _resultType = null;
+  }
+
+  @Override
+  public AggregationFunctionType getType() {
+    return AggregationFunctionType.ANYVALUE;
+  }
+
+  @Override
+  public AggregationResultHolder createAggregationResultHolder() {
+    return new ObjectAggregationResultHolder();
+  }
+
+  @Override
+  public GroupByResultHolder createGroupByResultHolder(int initialCapacity, 
int maxCapacity) {
+    return new ObjectGroupByResultHolder(initialCapacity, maxCapacity);
+  }
+
+  @Override
+  public ColumnDataType getIntermediateResultColumnType() {
+    return _resultType != null ? _resultType : ColumnDataType.STRING;

Review Comment:
   If `_resultType` is null should we use `ColumnDataType.UNKNOWN`?



##########
pinot-core/src/main/java/org/apache/pinot/core/query/aggregation/function/AnyValueAggregationFunction.java:
##########
@@ -0,0 +1,394 @@
+/**
+ * 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.pinot.core.query.aggregation.function;
+
+import java.math.BigDecimal;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+import org.apache.pinot.common.CustomObject;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.utils.DataSchema.ColumnDataType;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.query.aggregation.AggregationResultHolder;
+import org.apache.pinot.core.query.aggregation.ObjectAggregationResultHolder;
+import org.apache.pinot.core.query.aggregation.groupby.GroupByResultHolder;
+import 
org.apache.pinot.core.query.aggregation.groupby.ObjectGroupByResultHolder;
+import org.apache.pinot.segment.spi.AggregationFunctionType;
+import org.apache.pinot.segment.spi.index.reader.Dictionary;
+import org.apache.pinot.spi.data.FieldSpec;
+
+
+/**
+ * AnyValue aggregation function returns any arbitrary NON-NULL value from the 
column for each group.
+ * <p>
+ * This is useful for GROUP BY queries where you want to include a column in 
SELECT that has a 1:1 mapping with the
+ * GROUP BY columns, avoiding the need to add it to GROUP BY clause. The 
implementation is null-aware and will scan
+ * only until it finds the first non-null value in the current batch for each 
group/key. This makes it O(n) over the
+ * input once per group until the first value is set, with early-exit fast 
paths when there are no nulls.
+ * </p>
+ * <p><strong>Example:</strong></p>
+ * <pre>{@code
+ * SELECT CustomerID,
+ *        ANY_VALUE(CustomerName),
+ *        SUM(OrderValue)
+ * FROM Orders
+ * GROUP BY CustomerID
+ * }</pre>
+ */
+public class AnyValueAggregationFunction extends 
NullableSingleInputAggregationFunction<Object, Comparable<?>> {
+  // Result type is determined at runtime based on input expression type
+  private ColumnDataType _resultType;
+
+  public AnyValueAggregationFunction(List<ExpressionContext> arguments, 
boolean nullHandlingEnabled) {
+    super(verifySingleArgument(arguments, "ANY_VALUE"), nullHandlingEnabled);
+    _resultType = null;
+  }
+
+  @Override
+  public AggregationFunctionType getType() {
+    return AggregationFunctionType.ANYVALUE;
+  }
+
+  @Override
+  public AggregationResultHolder createAggregationResultHolder() {
+    return new ObjectAggregationResultHolder();
+  }
+
+  @Override
+  public GroupByResultHolder createGroupByResultHolder(int initialCapacity, 
int maxCapacity) {
+    return new ObjectGroupByResultHolder(initialCapacity, maxCapacity);
+  }
+
+  @Override
+  public ColumnDataType getIntermediateResultColumnType() {
+    return _resultType != null ? _resultType : ColumnDataType.STRING;
+  }
+
+  @Override
+  public ColumnDataType getFinalResultColumnType() {
+    return _resultType != null ? _resultType : ColumnDataType.STRING;
+  }
+
+  @Override
+  public Object extractAggregationResult(AggregationResultHolder 
aggregationResultHolder) {
+    return aggregationResultHolder.getResult();
+  }
+
+  @Override
+  public Object extractGroupByResult(GroupByResultHolder groupByResultHolder, 
int groupKey) {
+    return groupByResultHolder.getResult(groupKey);
+  }
+
+  @Override
+  public Comparable<?> extractFinalResult(Object intermediateResult) {
+    return (Comparable<?>) intermediateResult;
+  }
+
+  @Override
+  public Object merge(Object left, Object right) {
+    // For ANY_VALUE, we just need any non-null value, so merge by returning 
the first non-null value
+    return left != null ? left : right;
+  }
+
+  @Override
+  public void aggregate(int length, AggregationResultHolder holder,
+                        Map<ExpressionContext, BlockValSet> blockValSetMap) {
+    if (holder.getResult() != null) {
+      return;
+    }
+    BlockValSet bvs = blockValSetMap.get(_expression);
+    ensureResultType(bvs);
+    aggregateHelper(length, bvs, (i, value) -> {
+      holder.setValue(value);
+      return true; // Stop after first value found
+    });
+  }
+
+  @Override
+  public void aggregateGroupBySV(int length, int[] groupKeys, 
GroupByResultHolder holder,
+                                 Map<ExpressionContext, BlockValSet> map) {
+    BlockValSet bvs = map.get(_expression);
+    ensureResultType(bvs);
+    aggregateHelper(length, bvs, (i, value) -> {
+      int g = groupKeys[i];
+      if (holder.getResult(g) == null) {
+        holder.setValueForKey(g, value);
+      }
+      return false; // Continue processing for other groups
+    });
+  }
+
+  @Override
+  public void aggregateGroupByMV(int length, int[][] groupKeysArray, 
GroupByResultHolder holder,
+                                 Map<ExpressionContext, BlockValSet> map) {
+    BlockValSet bvs = map.get(_expression);
+    ensureResultType(bvs);
+    aggregateHelper(length, bvs, (i, value) -> {
+      int[] keys = groupKeysArray[i];
+      for (int g : keys) {
+        if (holder.getResult(g) == null) {
+          holder.setValueForKey(g, value);
+        }
+      }
+      return false; // Continue processing for other groups
+    });
+  }
+
+  @Override
+  public SerializedIntermediateResult serializeIntermediateResult(Object 
value) {
+    if (value == null) {
+      return new SerializedIntermediateResult(0, new byte[0]);
+    }
+    byte[] bytes = serializeValue(value);
+    return new SerializedIntermediateResult(1, bytes);
+  }
+
+  @Override
+  public Object deserializeIntermediateResult(CustomObject customObject) {
+    if (customObject.getBuffer().remaining() == 0) {
+      return null;
+    }
+    return deserializeValue(customObject.getBuffer());
+  }
+
+  @FunctionalInterface
+  private interface ValueProcessor<T> {
+    boolean process(int index, T value); // Returns true to continue 
processing, false to stop
+  }
+
+  /**
+   * Generic helper for processing values with dictionary optimization for all 
supported data types
+   */
+  private void aggregateHelper(int length, BlockValSet bvs, 
ValueProcessor<Object> processor) {
+    // Use dictionary-based access for efficiency when available
+    if (bvs.getDictionary() != null) {
+      final int[] dictIds = bvs.getDictionaryIdsSV();
+      final Dictionary dict = bvs.getDictionary();
+
+      if (bvs.getNullBitmap() == null) {
+        for (int i = 0; i < length; i++) {
+          Object value = getDictionaryValue(dict, dictIds[i], 
bvs.getValueType().getStoredType());
+          if (processor.process(i, value)) {
+            break;
+          }
+        }
+      } else {

Review Comment:
   Can this be simplified in favor of just using `forEachNotNull`?



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to