You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@druid.apache.org by GitBox <gi...@apache.org> on 2021/05/12 11:51:40 UTC

[GitHub] [druid] clintropolis opened a new pull request #11241: STRING_AGG SQL aggregator function

clintropolis opened a new pull request #11241:
URL: https://github.com/apache/druid/pull/11241


   ### Description
   This PR adds `STRING_AGG`, which is sort of like `ARRAY_AGG` added in #11157 but it ignores null values, with an `ARRAY_TO_STRING` function on the output array to turn it into a string value.
   
   example:
   ```sql
   SELECT STRING_AGG(l1, '-'), STRING_AGG(DISTINCT l1, ',') FROM numfoo
   ```
   output:
   ```
   ["7-325323-0-0-0-0", "0,7,325323"]
   ```
   
   |Function|Notes|Default|
   |--------|-----|-------|
   |`STRING_AGG(expr, separator, [size])`|Collects all values of `expr` into a single STRING, ignoring null values. Each value is joined by the `separator` which must be a literal STRING. An optional `size` in bytes can be supplied to limit aggregation size (default of 1024 bytes). If the aggregated string grows larger than the maximum size in bytes, the query will fail. Use of `ORDER BY` within the `STRING_AGG` expression is not currently supported, and the ordering of results within the output string may vary depending on processing order.|`null` if `druid.generic.useDefaultValueForNull=false`, otherwise `''`|
   |`STRING_AGG(DISTINCT expr, separator, [size])`|Collects all distinct values of `expr` into a single STRING, ignoring null values. Each value is joined by the `separator` which must be a literal STRING. An optional `size` in bytes can be supplied to limit aggregation size (default of 1024 bytes). If the aggregated string grows larger than the maximum size in bytes, the query will fail. Use of `ORDER BY` within the `STRING_AGG` expression is not currently supported, and the ordering of results within the output string may vary depending on processing order.|`null` if `druid.generic.useDefaultValueForNull=false`, otherwise `''`|
   
   Like `ARRAY_AGG` this is an expression aggregator, so is not well optimized, but will fill in the gaps for now.
   
   This PR has:
   - [ ] been self-reviewed.
      - [ ] using the [concurrency checklist](https://github.com/apache/druid/blob/master/dev/code-review/concurrency.md) (Remove this item if the PR doesn't have any relation to concurrency.)
   - [ ] added documentation for new or modified features or behaviors.
   - [ ] added Javadocs for most classes and all non-trivial methods. Linked related entities via Javadoc links.
   - [ ] added or updated version, license, or notice information in [licenses.yaml](https://github.com/apache/druid/blob/master/dev/license.md)
   - [ ] added comments explaining the "why" and the intent of the code wherever would not be obvious for an unfamiliar reader.
   - [ ] added unit tests or modified existing tests to cover new code paths, ensuring the threshold for [code coverage](https://github.com/apache/druid/blob/master/dev/code-review/code-coverage.md) is met.
   - [ ] added integration tests.
   - [ ] been tested in a test Druid cluster.
   


-- 
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.

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



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] rohangarg commented on a change in pull request #11241: STRING_AGG SQL aggregator function

Posted by GitBox <gi...@apache.org>.
rohangarg commented on a change in pull request #11241:
URL: https://github.com/apache/druid/pull/11241#discussion_r643770224



##########
File path: processing/src/main/java/org/apache/druid/query/aggregation/ExpressionLambdaAggregatorFactory.java
##########
@@ -65,7 +65,7 @@
   // minimum permitted agg size is 10 bytes so it is at least large enough to hold primitive numerics (long, double)
   // | expression type byte | is_null byte | primitive value (8 bytes) |
   private static final int MIN_SIZE_BYTES = 10;
-  private static final HumanReadableBytes DEFAULT_MAX_SIZE_BYTES = new HumanReadableBytes(1L << 10);
+  public static final HumanReadableBytes DEFAULT_MAX_SIZE_BYTES = new HumanReadableBytes(1L << 10);

Review comment:
       looks like an extra change - can't find its usage




-- 
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.

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



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] clintropolis commented on a change in pull request #11241: STRING_AGG SQL aggregator function

Posted by GitBox <gi...@apache.org>.
clintropolis commented on a change in pull request #11241:
URL: https://github.com/apache/druid/pull/11241#discussion_r647996132



##########
File path: sql/src/main/java/org/apache/druid/sql/calcite/aggregation/builtin/StringSqlAggregator.java
##########
@@ -0,0 +1,219 @@
+/*
+ * 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.druid.sql.calcite.aggregation.builtin;
+
+import com.google.common.collect.ImmutableSet;
+import org.apache.calcite.rel.core.AggregateCall;
+import org.apache.calcite.rel.core.Project;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.sql.SqlAggFunction;
+import org.apache.calcite.sql.SqlFunctionCategory;
+import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.sql.type.InferTypes;
+import org.apache.calcite.sql.type.OperandTypes;
+import org.apache.calcite.sql.type.SqlTypeFamily;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.calcite.util.Optionality;
+import org.apache.druid.java.util.common.HumanReadableBytes;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.math.expr.ExprMacroTable;
+import org.apache.druid.query.aggregation.ExpressionLambdaAggregatorFactory;
+import org.apache.druid.query.aggregation.FilteredAggregatorFactory;
+import org.apache.druid.query.filter.NotDimFilter;
+import org.apache.druid.query.filter.SelectorDimFilter;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.column.ValueType;
+import org.apache.druid.sql.calcite.aggregation.Aggregation;
+import org.apache.druid.sql.calcite.aggregation.SqlAggregator;
+import org.apache.druid.sql.calcite.expression.DruidExpression;
+import org.apache.druid.sql.calcite.expression.Expressions;
+import org.apache.druid.sql.calcite.planner.Calcites;
+import org.apache.druid.sql.calcite.planner.PlannerContext;
+import org.apache.druid.sql.calcite.rel.VirtualColumnRegistry;
+
+import javax.annotation.Nullable;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+public class StringSqlAggregator implements SqlAggregator
+{
+  private static final String NAME = "STRING_AGG";
+  private static final SqlAggFunction FUNCTION = new StringAggFunction();
+
+  @Override
+  public SqlAggFunction calciteFunction()
+  {
+    return FUNCTION;
+  }
+
+  @Nullable
+  @Override
+  public Aggregation toDruidAggregation(
+      PlannerContext plannerContext,
+      RowSignature rowSignature,
+      VirtualColumnRegistry virtualColumnRegistry,
+      RexBuilder rexBuilder,
+      String name,
+      AggregateCall aggregateCall,
+      Project project,
+      List<Aggregation> existingAggregations,
+      boolean finalizeAggregations
+  )
+  {
+    final List<DruidExpression> arguments = aggregateCall
+        .getArgList()
+        .stream()
+        .map(i -> Expressions.fromFieldAccess(rowSignature, project, i))
+        .map(rexNode -> Expressions.toDruidExpression(plannerContext, rowSignature, rexNode))
+        .collect(Collectors.toList());
+
+    if (arguments.stream().anyMatch(Objects::isNull)) {
+      return null;
+    }
+
+    RexNode separatorNode = Expressions.fromFieldAccess(
+        rowSignature,
+        project,
+        aggregateCall.getArgList().get(1)
+    );
+    if (!separatorNode.isA(SqlKind.LITERAL)) {
+      // separator must be a literal
+      return null;
+    }
+    String separator = RexLiteral.stringValue(separatorNode);
+
+    if (separator == null) {
+      // separator must not be null
+      return null;
+    }
+
+    Integer maxSizeBytes = null;
+    if (arguments.size() > 2) {
+      RexNode maxBytes = Expressions.fromFieldAccess(
+          rowSignature,
+          project,
+          aggregateCall.getArgList().get(2)
+      );
+      if (!maxBytes.isA(SqlKind.LITERAL)) {
+        // maxBytes must be a literal
+        return null;
+      }
+      maxSizeBytes = ((Number) RexLiteral.value(maxBytes)).intValue();
+    }
+    final DruidExpression arg = arguments.get(0);
+    final ExprMacroTable macroTable = plannerContext.getExprMacroTable();
+
+    final String initialvalue = "[]";
+    final ValueType elementType = ValueType.STRING;
+    final String fieldName;
+    if (arg.isDirectColumnAccess()) {
+      fieldName = arg.getDirectColumn();
+    } else {
+      VirtualColumn vc = virtualColumnRegistry.getOrCreateVirtualColumnForExpression(plannerContext, arg, elementType);
+      fieldName = vc.getOutputName();
+    }
+
+    final String finalizer = StringUtils.format("if(array_length(o) == 0, null, array_to_string(o, '%s'))", separator);
+    final NotDimFilter dimFilter = new NotDimFilter(new SelectorDimFilter(fieldName, null, null));
+    if (aggregateCall.isDistinct()) {
+      return Aggregation.create(
+          // string_agg ignores nulls
+          new FilteredAggregatorFactory(
+              new ExpressionLambdaAggregatorFactory(
+                  name,
+                  ImmutableSet.of(fieldName),
+                  null,
+                  initialvalue,
+                  null,
+                  StringUtils.format("array_set_add(\"__acc\", \"%s\")", fieldName),
+                  StringUtils.format("array_set_add_all(\"__acc\", \"%s\")", name),
+                  null,
+                  finalizer,
+                  maxSizeBytes != null ? new HumanReadableBytes(maxSizeBytes) : null,
+                  macroTable
+              ),
+              dimFilter
+          )
+      );
+    } else {
+      return Aggregation.create(
+          // string_agg ignores nulls
+          new FilteredAggregatorFactory(
+              new ExpressionLambdaAggregatorFactory(
+                  name,
+                  ImmutableSet.of(fieldName),
+                  null,
+                  initialvalue,
+                  null,
+                  StringUtils.format("array_append(\"__acc\", \"%s\")", fieldName),
+                  StringUtils.format("array_concat(\"__acc\", \"%s\")", name),
+                  null,
+                  finalizer,
+                  maxSizeBytes != null ? new HumanReadableBytes(maxSizeBytes) : null,
+                  macroTable
+              ),
+              dimFilter
+          )
+      );
+    }
+  }
+
+  private static class StringAggFunction extends SqlAggFunction
+  {
+    StringAggFunction()
+    {
+      super(
+          NAME,
+          null,
+          SqlKind.OTHER_FUNCTION,
+          opBinding ->
+              Calcites.createSqlTypeWithNullability(opBinding.getTypeFactory(), SqlTypeName.VARCHAR, true),
+          InferTypes.ANY_NULLABLE,
+          OperandTypes.or(
+              OperandTypes.and(
+                  OperandTypes.sequence(
+                      StringUtils.format("'%s'(expr, separator)", NAME),
+                      OperandTypes.ANY,
+                      OperandTypes.LITERAL

Review comment:
       I'm not certain if this can (or should) handle an expression for the `separator` parameter, I'll do some investigation and potentially update this signature accordingly

##########
File path: sql/src/main/java/org/apache/druid/sql/calcite/aggregation/builtin/StringSqlAggregator.java
##########
@@ -0,0 +1,219 @@
+/*
+ * 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.druid.sql.calcite.aggregation.builtin;
+
+import com.google.common.collect.ImmutableSet;
+import org.apache.calcite.rel.core.AggregateCall;
+import org.apache.calcite.rel.core.Project;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.sql.SqlAggFunction;
+import org.apache.calcite.sql.SqlFunctionCategory;
+import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.sql.type.InferTypes;
+import org.apache.calcite.sql.type.OperandTypes;
+import org.apache.calcite.sql.type.SqlTypeFamily;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.calcite.util.Optionality;
+import org.apache.druid.java.util.common.HumanReadableBytes;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.math.expr.ExprMacroTable;
+import org.apache.druid.query.aggregation.ExpressionLambdaAggregatorFactory;
+import org.apache.druid.query.aggregation.FilteredAggregatorFactory;
+import org.apache.druid.query.filter.NotDimFilter;
+import org.apache.druid.query.filter.SelectorDimFilter;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.column.ValueType;
+import org.apache.druid.sql.calcite.aggregation.Aggregation;
+import org.apache.druid.sql.calcite.aggregation.SqlAggregator;
+import org.apache.druid.sql.calcite.expression.DruidExpression;
+import org.apache.druid.sql.calcite.expression.Expressions;
+import org.apache.druid.sql.calcite.planner.Calcites;
+import org.apache.druid.sql.calcite.planner.PlannerContext;
+import org.apache.druid.sql.calcite.rel.VirtualColumnRegistry;
+
+import javax.annotation.Nullable;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+public class StringSqlAggregator implements SqlAggregator
+{
+  private static final String NAME = "STRING_AGG";
+  private static final SqlAggFunction FUNCTION = new StringAggFunction();
+
+  @Override
+  public SqlAggFunction calciteFunction()
+  {
+    return FUNCTION;
+  }
+
+  @Nullable
+  @Override
+  public Aggregation toDruidAggregation(
+      PlannerContext plannerContext,
+      RowSignature rowSignature,
+      VirtualColumnRegistry virtualColumnRegistry,
+      RexBuilder rexBuilder,
+      String name,
+      AggregateCall aggregateCall,
+      Project project,
+      List<Aggregation> existingAggregations,
+      boolean finalizeAggregations
+  )
+  {
+    final List<DruidExpression> arguments = aggregateCall
+        .getArgList()
+        .stream()
+        .map(i -> Expressions.fromFieldAccess(rowSignature, project, i))
+        .map(rexNode -> Expressions.toDruidExpression(plannerContext, rowSignature, rexNode))
+        .collect(Collectors.toList());
+
+    if (arguments.stream().anyMatch(Objects::isNull)) {
+      return null;
+    }
+
+    RexNode separatorNode = Expressions.fromFieldAccess(
+        rowSignature,
+        project,
+        aggregateCall.getArgList().get(1)
+    );
+    if (!separatorNode.isA(SqlKind.LITERAL)) {
+      // separator must be a literal
+      return null;
+    }
+    String separator = RexLiteral.stringValue(separatorNode);
+
+    if (separator == null) {
+      // separator must not be null
+      return null;
+    }
+
+    Integer maxSizeBytes = null;
+    if (arguments.size() > 2) {
+      RexNode maxBytes = Expressions.fromFieldAccess(
+          rowSignature,
+          project,
+          aggregateCall.getArgList().get(2)
+      );
+      if (!maxBytes.isA(SqlKind.LITERAL)) {
+        // maxBytes must be a literal
+        return null;
+      }
+      maxSizeBytes = ((Number) RexLiteral.value(maxBytes)).intValue();
+    }
+    final DruidExpression arg = arguments.get(0);
+    final ExprMacroTable macroTable = plannerContext.getExprMacroTable();
+
+    final String initialvalue = "[]";
+    final ValueType elementType = ValueType.STRING;
+    final String fieldName;
+    if (arg.isDirectColumnAccess()) {
+      fieldName = arg.getDirectColumn();
+    } else {
+      VirtualColumn vc = virtualColumnRegistry.getOrCreateVirtualColumnForExpression(plannerContext, arg, elementType);
+      fieldName = vc.getOutputName();
+    }
+
+    final String finalizer = StringUtils.format("if(array_length(o) == 0, null, array_to_string(o, '%s'))", separator);
+    final NotDimFilter dimFilter = new NotDimFilter(new SelectorDimFilter(fieldName, null, null));
+    if (aggregateCall.isDistinct()) {
+      return Aggregation.create(
+          // string_agg ignores nulls
+          new FilteredAggregatorFactory(
+              new ExpressionLambdaAggregatorFactory(
+                  name,
+                  ImmutableSet.of(fieldName),
+                  null,
+                  initialvalue,
+                  null,
+                  StringUtils.format("array_set_add(\"__acc\", \"%s\")", fieldName),
+                  StringUtils.format("array_set_add_all(\"__acc\", \"%s\")", name),
+                  null,
+                  finalizer,
+                  maxSizeBytes != null ? new HumanReadableBytes(maxSizeBytes) : null,
+                  macroTable
+              ),
+              dimFilter
+          )
+      );
+    } else {
+      return Aggregation.create(
+          // string_agg ignores nulls
+          new FilteredAggregatorFactory(
+              new ExpressionLambdaAggregatorFactory(
+                  name,
+                  ImmutableSet.of(fieldName),
+                  null,
+                  initialvalue,
+                  null,
+                  StringUtils.format("array_append(\"__acc\", \"%s\")", fieldName),
+                  StringUtils.format("array_concat(\"__acc\", \"%s\")", name),
+                  null,
+                  finalizer,
+                  maxSizeBytes != null ? new HumanReadableBytes(maxSizeBytes) : null,
+                  macroTable
+              ),
+              dimFilter
+          )
+      );
+    }
+  }
+
+  private static class StringAggFunction extends SqlAggFunction
+  {
+    StringAggFunction()
+    {
+      super(
+          NAME,
+          null,
+          SqlKind.OTHER_FUNCTION,
+          opBinding ->
+              Calcites.createSqlTypeWithNullability(opBinding.getTypeFactory(), SqlTypeName.VARCHAR, true),
+          InferTypes.ANY_NULLABLE,
+          OperandTypes.or(
+              OperandTypes.and(
+                  OperandTypes.sequence(
+                      StringUtils.format("'%s'(expr, separator)", NAME),
+                      OperandTypes.ANY,
+                      OperandTypes.LITERAL

Review comment:
       I'm not certain if this can (or should) handle an expression for the `separator` parameter, I'll do some investigation and potentially update this signature accordingly and add a test case




-- 
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.

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



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] clintropolis commented on a change in pull request #11241: STRING_AGG SQL aggregator function

Posted by GitBox <gi...@apache.org>.
clintropolis commented on a change in pull request #11241:
URL: https://github.com/apache/druid/pull/11241#discussion_r682899966



##########
File path: sql/src/main/java/org/apache/druid/sql/calcite/aggregation/builtin/StringSqlAggregator.java
##########
@@ -0,0 +1,219 @@
+/*
+ * 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.druid.sql.calcite.aggregation.builtin;
+
+import com.google.common.collect.ImmutableSet;
+import org.apache.calcite.rel.core.AggregateCall;
+import org.apache.calcite.rel.core.Project;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.sql.SqlAggFunction;
+import org.apache.calcite.sql.SqlFunctionCategory;
+import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.sql.type.InferTypes;
+import org.apache.calcite.sql.type.OperandTypes;
+import org.apache.calcite.sql.type.SqlTypeFamily;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.calcite.util.Optionality;
+import org.apache.druid.java.util.common.HumanReadableBytes;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.math.expr.ExprMacroTable;
+import org.apache.druid.query.aggregation.ExpressionLambdaAggregatorFactory;
+import org.apache.druid.query.aggregation.FilteredAggregatorFactory;
+import org.apache.druid.query.filter.NotDimFilter;
+import org.apache.druid.query.filter.SelectorDimFilter;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.column.ValueType;
+import org.apache.druid.sql.calcite.aggregation.Aggregation;
+import org.apache.druid.sql.calcite.aggregation.SqlAggregator;
+import org.apache.druid.sql.calcite.expression.DruidExpression;
+import org.apache.druid.sql.calcite.expression.Expressions;
+import org.apache.druid.sql.calcite.planner.Calcites;
+import org.apache.druid.sql.calcite.planner.PlannerContext;
+import org.apache.druid.sql.calcite.rel.VirtualColumnRegistry;
+
+import javax.annotation.Nullable;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+public class StringSqlAggregator implements SqlAggregator
+{
+  private static final String NAME = "STRING_AGG";
+  private static final SqlAggFunction FUNCTION = new StringAggFunction();
+
+  @Override
+  public SqlAggFunction calciteFunction()
+  {
+    return FUNCTION;
+  }
+
+  @Nullable
+  @Override
+  public Aggregation toDruidAggregation(
+      PlannerContext plannerContext,
+      RowSignature rowSignature,
+      VirtualColumnRegistry virtualColumnRegistry,
+      RexBuilder rexBuilder,
+      String name,
+      AggregateCall aggregateCall,
+      Project project,
+      List<Aggregation> existingAggregations,
+      boolean finalizeAggregations
+  )
+  {
+    final List<DruidExpression> arguments = aggregateCall
+        .getArgList()
+        .stream()
+        .map(i -> Expressions.fromFieldAccess(rowSignature, project, i))
+        .map(rexNode -> Expressions.toDruidExpression(plannerContext, rowSignature, rexNode))
+        .collect(Collectors.toList());
+
+    if (arguments.stream().anyMatch(Objects::isNull)) {
+      return null;
+    }
+
+    RexNode separatorNode = Expressions.fromFieldAccess(
+        rowSignature,
+        project,
+        aggregateCall.getArgList().get(1)
+    );
+    if (!separatorNode.isA(SqlKind.LITERAL)) {
+      // separator must be a literal
+      return null;
+    }
+    String separator = RexLiteral.stringValue(separatorNode);
+
+    if (separator == null) {
+      // separator must not be null
+      return null;
+    }
+
+    Integer maxSizeBytes = null;
+    if (arguments.size() > 2) {
+      RexNode maxBytes = Expressions.fromFieldAccess(
+          rowSignature,
+          project,
+          aggregateCall.getArgList().get(2)
+      );
+      if (!maxBytes.isA(SqlKind.LITERAL)) {
+        // maxBytes must be a literal
+        return null;
+      }
+      maxSizeBytes = ((Number) RexLiteral.value(maxBytes)).intValue();
+    }
+    final DruidExpression arg = arguments.get(0);
+    final ExprMacroTable macroTable = plannerContext.getExprMacroTable();
+
+    final String initialvalue = "[]";
+    final ValueType elementType = ValueType.STRING;
+    final String fieldName;
+    if (arg.isDirectColumnAccess()) {
+      fieldName = arg.getDirectColumn();
+    } else {
+      VirtualColumn vc = virtualColumnRegistry.getOrCreateVirtualColumnForExpression(plannerContext, arg, elementType);
+      fieldName = vc.getOutputName();
+    }
+
+    final String finalizer = StringUtils.format("if(array_length(o) == 0, null, array_to_string(o, '%s'))", separator);
+    final NotDimFilter dimFilter = new NotDimFilter(new SelectorDimFilter(fieldName, null, null));
+    if (aggregateCall.isDistinct()) {
+      return Aggregation.create(
+          // string_agg ignores nulls
+          new FilteredAggregatorFactory(
+              new ExpressionLambdaAggregatorFactory(
+                  name,
+                  ImmutableSet.of(fieldName),
+                  null,
+                  initialvalue,
+                  null,
+                  StringUtils.format("array_set_add(\"__acc\", \"%s\")", fieldName),
+                  StringUtils.format("array_set_add_all(\"__acc\", \"%s\")", name),
+                  null,
+                  finalizer,
+                  maxSizeBytes != null ? new HumanReadableBytes(maxSizeBytes) : null,
+                  macroTable
+              ),
+              dimFilter
+          )
+      );
+    } else {
+      return Aggregation.create(

Review comment:
       yeah, it could if i pull out the two expressions into a separate conditional block; I did not make this change yet because it seems like minor shifting of the condition but will modify here (as well as [ARRAY_AGG](https://github.com/apache/druid/blob/master/sql/src/main/java/org/apache/druid/sql/calcite/aggregation/builtin/ArraySqlAggregator.java#L143) since I did the same thing there) if you feel more strongly about it.

##########
File path: processing/src/main/java/org/apache/druid/query/aggregation/ExpressionLambdaAggregatorFactory.java
##########
@@ -65,7 +65,7 @@
   // minimum permitted agg size is 10 bytes so it is at least large enough to hold primitive numerics (long, double)
   // | expression type byte | is_null byte | primitive value (8 bytes) |
   private static final int MIN_SIZE_BYTES = 10;
-  private static final HumanReadableBytes DEFAULT_MAX_SIZE_BYTES = new HumanReadableBytes(1L << 10);
+  public static final HumanReadableBytes DEFAULT_MAX_SIZE_BYTES = new HumanReadableBytes(1L << 10);

Review comment:
       it wasn't meant to be, its used in tests now




-- 
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: commits-unsubscribe@druid.apache.org

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



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] clintropolis commented on a change in pull request #11241: STRING_AGG SQL aggregator function

Posted by GitBox <gi...@apache.org>.
clintropolis commented on a change in pull request #11241:
URL: https://github.com/apache/druid/pull/11241#discussion_r682899966



##########
File path: sql/src/main/java/org/apache/druid/sql/calcite/aggregation/builtin/StringSqlAggregator.java
##########
@@ -0,0 +1,219 @@
+/*
+ * 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.druid.sql.calcite.aggregation.builtin;
+
+import com.google.common.collect.ImmutableSet;
+import org.apache.calcite.rel.core.AggregateCall;
+import org.apache.calcite.rel.core.Project;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.sql.SqlAggFunction;
+import org.apache.calcite.sql.SqlFunctionCategory;
+import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.sql.type.InferTypes;
+import org.apache.calcite.sql.type.OperandTypes;
+import org.apache.calcite.sql.type.SqlTypeFamily;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.calcite.util.Optionality;
+import org.apache.druid.java.util.common.HumanReadableBytes;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.math.expr.ExprMacroTable;
+import org.apache.druid.query.aggregation.ExpressionLambdaAggregatorFactory;
+import org.apache.druid.query.aggregation.FilteredAggregatorFactory;
+import org.apache.druid.query.filter.NotDimFilter;
+import org.apache.druid.query.filter.SelectorDimFilter;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.column.ValueType;
+import org.apache.druid.sql.calcite.aggregation.Aggregation;
+import org.apache.druid.sql.calcite.aggregation.SqlAggregator;
+import org.apache.druid.sql.calcite.expression.DruidExpression;
+import org.apache.druid.sql.calcite.expression.Expressions;
+import org.apache.druid.sql.calcite.planner.Calcites;
+import org.apache.druid.sql.calcite.planner.PlannerContext;
+import org.apache.druid.sql.calcite.rel.VirtualColumnRegistry;
+
+import javax.annotation.Nullable;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+public class StringSqlAggregator implements SqlAggregator
+{
+  private static final String NAME = "STRING_AGG";
+  private static final SqlAggFunction FUNCTION = new StringAggFunction();
+
+  @Override
+  public SqlAggFunction calciteFunction()
+  {
+    return FUNCTION;
+  }
+
+  @Nullable
+  @Override
+  public Aggregation toDruidAggregation(
+      PlannerContext plannerContext,
+      RowSignature rowSignature,
+      VirtualColumnRegistry virtualColumnRegistry,
+      RexBuilder rexBuilder,
+      String name,
+      AggregateCall aggregateCall,
+      Project project,
+      List<Aggregation> existingAggregations,
+      boolean finalizeAggregations
+  )
+  {
+    final List<DruidExpression> arguments = aggregateCall
+        .getArgList()
+        .stream()
+        .map(i -> Expressions.fromFieldAccess(rowSignature, project, i))
+        .map(rexNode -> Expressions.toDruidExpression(plannerContext, rowSignature, rexNode))
+        .collect(Collectors.toList());
+
+    if (arguments.stream().anyMatch(Objects::isNull)) {
+      return null;
+    }
+
+    RexNode separatorNode = Expressions.fromFieldAccess(
+        rowSignature,
+        project,
+        aggregateCall.getArgList().get(1)
+    );
+    if (!separatorNode.isA(SqlKind.LITERAL)) {
+      // separator must be a literal
+      return null;
+    }
+    String separator = RexLiteral.stringValue(separatorNode);
+
+    if (separator == null) {
+      // separator must not be null
+      return null;
+    }
+
+    Integer maxSizeBytes = null;
+    if (arguments.size() > 2) {
+      RexNode maxBytes = Expressions.fromFieldAccess(
+          rowSignature,
+          project,
+          aggregateCall.getArgList().get(2)
+      );
+      if (!maxBytes.isA(SqlKind.LITERAL)) {
+        // maxBytes must be a literal
+        return null;
+      }
+      maxSizeBytes = ((Number) RexLiteral.value(maxBytes)).intValue();
+    }
+    final DruidExpression arg = arguments.get(0);
+    final ExprMacroTable macroTable = plannerContext.getExprMacroTable();
+
+    final String initialvalue = "[]";
+    final ValueType elementType = ValueType.STRING;
+    final String fieldName;
+    if (arg.isDirectColumnAccess()) {
+      fieldName = arg.getDirectColumn();
+    } else {
+      VirtualColumn vc = virtualColumnRegistry.getOrCreateVirtualColumnForExpression(plannerContext, arg, elementType);
+      fieldName = vc.getOutputName();
+    }
+
+    final String finalizer = StringUtils.format("if(array_length(o) == 0, null, array_to_string(o, '%s'))", separator);
+    final NotDimFilter dimFilter = new NotDimFilter(new SelectorDimFilter(fieldName, null, null));
+    if (aggregateCall.isDistinct()) {
+      return Aggregation.create(
+          // string_agg ignores nulls
+          new FilteredAggregatorFactory(
+              new ExpressionLambdaAggregatorFactory(
+                  name,
+                  ImmutableSet.of(fieldName),
+                  null,
+                  initialvalue,
+                  null,
+                  StringUtils.format("array_set_add(\"__acc\", \"%s\")", fieldName),
+                  StringUtils.format("array_set_add_all(\"__acc\", \"%s\")", name),
+                  null,
+                  finalizer,
+                  maxSizeBytes != null ? new HumanReadableBytes(maxSizeBytes) : null,
+                  macroTable
+              ),
+              dimFilter
+          )
+      );
+    } else {
+      return Aggregation.create(

Review comment:
       yeah, it could if i pull out the two expressions into a separate conditional block; I did not make this change yet because it seems like minor shifting of the condition but will modify here (as well as [ARRAY_AGG](https://github.com/apache/druid/blob/master/sql/src/main/java/org/apache/druid/sql/calcite/aggregation/builtin/ArraySqlAggregator.java#L143) since I did the same thing there) if you feel more strongly about it.




-- 
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: commits-unsubscribe@druid.apache.org

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



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] clintropolis merged pull request #11241: STRING_AGG SQL aggregator function

Posted by GitBox <gi...@apache.org>.
clintropolis merged pull request #11241:
URL: https://github.com/apache/druid/pull/11241


   


-- 
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: commits-unsubscribe@druid.apache.org

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



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] clintropolis commented on a change in pull request #11241: STRING_AGG SQL aggregator function

Posted by GitBox <gi...@apache.org>.
clintropolis commented on a change in pull request #11241:
URL: https://github.com/apache/druid/pull/11241#discussion_r682900325



##########
File path: processing/src/main/java/org/apache/druid/query/aggregation/ExpressionLambdaAggregatorFactory.java
##########
@@ -65,7 +65,7 @@
   // minimum permitted agg size is 10 bytes so it is at least large enough to hold primitive numerics (long, double)
   // | expression type byte | is_null byte | primitive value (8 bytes) |
   private static final int MIN_SIZE_BYTES = 10;
-  private static final HumanReadableBytes DEFAULT_MAX_SIZE_BYTES = new HumanReadableBytes(1L << 10);
+  public static final HumanReadableBytes DEFAULT_MAX_SIZE_BYTES = new HumanReadableBytes(1L << 10);

Review comment:
       it wasn't meant to be, its used in tests now




-- 
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: commits-unsubscribe@druid.apache.org

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



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] clintropolis commented on pull request #11241: STRING_AGG SQL aggregator function

Posted by GitBox <gi...@apache.org>.
clintropolis commented on pull request #11241:
URL: https://github.com/apache/druid/pull/11241#issuecomment-896305994


   thanks for review @rohangarg and @jihoonson :+1:


-- 
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: commits-unsubscribe@druid.apache.org

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



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] rohangarg commented on a change in pull request #11241: STRING_AGG SQL aggregator function

Posted by GitBox <gi...@apache.org>.
rohangarg commented on a change in pull request #11241:
URL: https://github.com/apache/druid/pull/11241#discussion_r643765712



##########
File path: sql/src/main/java/org/apache/druid/sql/calcite/aggregation/builtin/StringSqlAggregator.java
##########
@@ -0,0 +1,219 @@
+/*
+ * 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.druid.sql.calcite.aggregation.builtin;
+
+import com.google.common.collect.ImmutableSet;
+import org.apache.calcite.rel.core.AggregateCall;
+import org.apache.calcite.rel.core.Project;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.sql.SqlAggFunction;
+import org.apache.calcite.sql.SqlFunctionCategory;
+import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.sql.type.InferTypes;
+import org.apache.calcite.sql.type.OperandTypes;
+import org.apache.calcite.sql.type.SqlTypeFamily;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.calcite.util.Optionality;
+import org.apache.druid.java.util.common.HumanReadableBytes;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.math.expr.ExprMacroTable;
+import org.apache.druid.query.aggregation.ExpressionLambdaAggregatorFactory;
+import org.apache.druid.query.aggregation.FilteredAggregatorFactory;
+import org.apache.druid.query.filter.NotDimFilter;
+import org.apache.druid.query.filter.SelectorDimFilter;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.column.ValueType;
+import org.apache.druid.sql.calcite.aggregation.Aggregation;
+import org.apache.druid.sql.calcite.aggregation.SqlAggregator;
+import org.apache.druid.sql.calcite.expression.DruidExpression;
+import org.apache.druid.sql.calcite.expression.Expressions;
+import org.apache.druid.sql.calcite.planner.Calcites;
+import org.apache.druid.sql.calcite.planner.PlannerContext;
+import org.apache.druid.sql.calcite.rel.VirtualColumnRegistry;
+
+import javax.annotation.Nullable;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+public class StringSqlAggregator implements SqlAggregator
+{
+  private static final String NAME = "STRING_AGG";
+  private static final SqlAggFunction FUNCTION = new StringAggFunction();
+
+  @Override
+  public SqlAggFunction calciteFunction()
+  {
+    return FUNCTION;
+  }
+
+  @Nullable
+  @Override
+  public Aggregation toDruidAggregation(
+      PlannerContext plannerContext,
+      RowSignature rowSignature,
+      VirtualColumnRegistry virtualColumnRegistry,
+      RexBuilder rexBuilder,
+      String name,
+      AggregateCall aggregateCall,
+      Project project,
+      List<Aggregation> existingAggregations,
+      boolean finalizeAggregations
+  )
+  {
+    final List<DruidExpression> arguments = aggregateCall
+        .getArgList()
+        .stream()
+        .map(i -> Expressions.fromFieldAccess(rowSignature, project, i))
+        .map(rexNode -> Expressions.toDruidExpression(plannerContext, rowSignature, rexNode))
+        .collect(Collectors.toList());
+
+    if (arguments.stream().anyMatch(Objects::isNull)) {
+      return null;
+    }
+
+    RexNode separatorNode = Expressions.fromFieldAccess(
+        rowSignature,
+        project,
+        aggregateCall.getArgList().get(1)
+    );
+    if (!separatorNode.isA(SqlKind.LITERAL)) {
+      // separator must be a literal
+      return null;
+    }
+    String separator = RexLiteral.stringValue(separatorNode);
+
+    if (separator == null) {
+      // separator must not be null
+      return null;
+    }
+
+    Integer maxSizeBytes = null;
+    if (arguments.size() > 2) {
+      RexNode maxBytes = Expressions.fromFieldAccess(
+          rowSignature,
+          project,
+          aggregateCall.getArgList().get(2)
+      );
+      if (!maxBytes.isA(SqlKind.LITERAL)) {
+        // maxBytes must be a literal
+        return null;
+      }
+      maxSizeBytes = ((Number) RexLiteral.value(maxBytes)).intValue();
+    }
+    final DruidExpression arg = arguments.get(0);
+    final ExprMacroTable macroTable = plannerContext.getExprMacroTable();
+
+    final String initialvalue = "[]";
+    final ValueType elementType = ValueType.STRING;
+    final String fieldName;
+    if (arg.isDirectColumnAccess()) {
+      fieldName = arg.getDirectColumn();
+    } else {
+      VirtualColumn vc = virtualColumnRegistry.getOrCreateVirtualColumnForExpression(plannerContext, arg, elementType);
+      fieldName = vc.getOutputName();
+    }
+
+    final String finalizer = StringUtils.format("if(array_length(o) == 0, null, array_to_string(o, '%s'))", separator);
+    final NotDimFilter dimFilter = new NotDimFilter(new SelectorDimFilter(fieldName, null, null));
+    if (aggregateCall.isDistinct()) {
+      return Aggregation.create(
+          // string_agg ignores nulls
+          new FilteredAggregatorFactory(
+              new ExpressionLambdaAggregatorFactory(
+                  name,
+                  ImmutableSet.of(fieldName),
+                  null,
+                  initialvalue,
+                  null,
+                  StringUtils.format("array_set_add(\"__acc\", \"%s\")", fieldName),
+                  StringUtils.format("array_set_add_all(\"__acc\", \"%s\")", name),
+                  null,
+                  finalizer,
+                  maxSizeBytes != null ? new HumanReadableBytes(maxSizeBytes) : null,
+                  macroTable
+              ),
+              dimFilter
+          )
+      );
+    } else {
+      return Aggregation.create(
+          // string_agg ignores nulls
+          new FilteredAggregatorFactory(
+              new ExpressionLambdaAggregatorFactory(
+                  name,
+                  ImmutableSet.of(fieldName),
+                  null,
+                  initialvalue,
+                  null,
+                  StringUtils.format("array_append(\"__acc\", \"%s\")", fieldName),
+                  StringUtils.format("array_concat(\"__acc\", \"%s\")", name),
+                  null,
+                  finalizer,
+                  maxSizeBytes != null ? new HumanReadableBytes(maxSizeBytes) : null,
+                  macroTable
+              ),
+              dimFilter
+          )
+      );
+    }
+  }
+
+  private static class StringAggFunction extends SqlAggFunction
+  {
+    StringAggFunction()
+    {
+      super(
+          NAME,
+          null,
+          SqlKind.OTHER_FUNCTION,
+          opBinding ->
+              Calcites.createSqlTypeWithNullability(opBinding.getTypeFactory(), SqlTypeName.VARCHAR, true),
+          InferTypes.ANY_NULLABLE,
+          OperandTypes.or(
+              OperandTypes.and(
+                  OperandTypes.sequence(
+                      StringUtils.format("'%s'(expr, separator)", NAME),
+                      OperandTypes.ANY,
+                      OperandTypes.LITERAL

Review comment:
       does this also take care of the cases if the literal is wrapped in a scalar function (like `concat('a', 'b')`)?




-- 
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.

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



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] rohangarg commented on a change in pull request #11241: STRING_AGG SQL aggregator function

Posted by GitBox <gi...@apache.org>.
rohangarg commented on a change in pull request #11241:
URL: https://github.com/apache/druid/pull/11241#discussion_r643766656



##########
File path: sql/src/main/java/org/apache/druid/sql/calcite/aggregation/builtin/StringSqlAggregator.java
##########
@@ -0,0 +1,219 @@
+/*
+ * 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.druid.sql.calcite.aggregation.builtin;
+
+import com.google.common.collect.ImmutableSet;
+import org.apache.calcite.rel.core.AggregateCall;
+import org.apache.calcite.rel.core.Project;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.sql.SqlAggFunction;
+import org.apache.calcite.sql.SqlFunctionCategory;
+import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.sql.type.InferTypes;
+import org.apache.calcite.sql.type.OperandTypes;
+import org.apache.calcite.sql.type.SqlTypeFamily;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.calcite.util.Optionality;
+import org.apache.druid.java.util.common.HumanReadableBytes;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.math.expr.ExprMacroTable;
+import org.apache.druid.query.aggregation.ExpressionLambdaAggregatorFactory;
+import org.apache.druid.query.aggregation.FilteredAggregatorFactory;
+import org.apache.druid.query.filter.NotDimFilter;
+import org.apache.druid.query.filter.SelectorDimFilter;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.column.ValueType;
+import org.apache.druid.sql.calcite.aggregation.Aggregation;
+import org.apache.druid.sql.calcite.aggregation.SqlAggregator;
+import org.apache.druid.sql.calcite.expression.DruidExpression;
+import org.apache.druid.sql.calcite.expression.Expressions;
+import org.apache.druid.sql.calcite.planner.Calcites;
+import org.apache.druid.sql.calcite.planner.PlannerContext;
+import org.apache.druid.sql.calcite.rel.VirtualColumnRegistry;
+
+import javax.annotation.Nullable;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+public class StringSqlAggregator implements SqlAggregator
+{
+  private static final String NAME = "STRING_AGG";
+  private static final SqlAggFunction FUNCTION = new StringAggFunction();
+
+  @Override
+  public SqlAggFunction calciteFunction()
+  {
+    return FUNCTION;
+  }
+
+  @Nullable
+  @Override
+  public Aggregation toDruidAggregation(
+      PlannerContext plannerContext,
+      RowSignature rowSignature,
+      VirtualColumnRegistry virtualColumnRegistry,
+      RexBuilder rexBuilder,
+      String name,
+      AggregateCall aggregateCall,
+      Project project,
+      List<Aggregation> existingAggregations,
+      boolean finalizeAggregations
+  )
+  {
+    final List<DruidExpression> arguments = aggregateCall
+        .getArgList()
+        .stream()
+        .map(i -> Expressions.fromFieldAccess(rowSignature, project, i))
+        .map(rexNode -> Expressions.toDruidExpression(plannerContext, rowSignature, rexNode))
+        .collect(Collectors.toList());
+
+    if (arguments.stream().anyMatch(Objects::isNull)) {
+      return null;
+    }
+
+    RexNode separatorNode = Expressions.fromFieldAccess(
+        rowSignature,
+        project,
+        aggregateCall.getArgList().get(1)
+    );
+    if (!separatorNode.isA(SqlKind.LITERAL)) {
+      // separator must be a literal
+      return null;
+    }
+    String separator = RexLiteral.stringValue(separatorNode);
+
+    if (separator == null) {
+      // separator must not be null
+      return null;
+    }
+
+    Integer maxSizeBytes = null;
+    if (arguments.size() > 2) {
+      RexNode maxBytes = Expressions.fromFieldAccess(
+          rowSignature,
+          project,
+          aggregateCall.getArgList().get(2)
+      );
+      if (!maxBytes.isA(SqlKind.LITERAL)) {
+        // maxBytes must be a literal
+        return null;
+      }
+      maxSizeBytes = ((Number) RexLiteral.value(maxBytes)).intValue();
+    }
+    final DruidExpression arg = arguments.get(0);
+    final ExprMacroTable macroTable = plannerContext.getExprMacroTable();
+
+    final String initialvalue = "[]";
+    final ValueType elementType = ValueType.STRING;
+    final String fieldName;
+    if (arg.isDirectColumnAccess()) {
+      fieldName = arg.getDirectColumn();
+    } else {
+      VirtualColumn vc = virtualColumnRegistry.getOrCreateVirtualColumnForExpression(plannerContext, arg, elementType);
+      fieldName = vc.getOutputName();
+    }
+
+    final String finalizer = StringUtils.format("if(array_length(o) == 0, null, array_to_string(o, '%s'))", separator);
+    final NotDimFilter dimFilter = new NotDimFilter(new SelectorDimFilter(fieldName, null, null));
+    if (aggregateCall.isDistinct()) {
+      return Aggregation.create(
+          // string_agg ignores nulls
+          new FilteredAggregatorFactory(
+              new ExpressionLambdaAggregatorFactory(
+                  name,
+                  ImmutableSet.of(fieldName),
+                  null,
+                  initialvalue,
+                  null,
+                  StringUtils.format("array_set_add(\"__acc\", \"%s\")", fieldName),
+                  StringUtils.format("array_set_add_all(\"__acc\", \"%s\")", name),
+                  null,
+                  finalizer,
+                  maxSizeBytes != null ? new HumanReadableBytes(maxSizeBytes) : null,
+                  macroTable
+              ),
+              dimFilter
+          )
+      );
+    } else {
+      return Aggregation.create(

Review comment:
       the if-else can be collapsed 

##########
File path: sql/src/main/java/org/apache/druid/sql/calcite/aggregation/builtin/StringSqlAggregator.java
##########
@@ -0,0 +1,219 @@
+/*
+ * 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.druid.sql.calcite.aggregation.builtin;
+
+import com.google.common.collect.ImmutableSet;
+import org.apache.calcite.rel.core.AggregateCall;
+import org.apache.calcite.rel.core.Project;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.sql.SqlAggFunction;
+import org.apache.calcite.sql.SqlFunctionCategory;
+import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.sql.type.InferTypes;
+import org.apache.calcite.sql.type.OperandTypes;
+import org.apache.calcite.sql.type.SqlTypeFamily;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.calcite.util.Optionality;
+import org.apache.druid.java.util.common.HumanReadableBytes;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.math.expr.ExprMacroTable;
+import org.apache.druid.query.aggregation.ExpressionLambdaAggregatorFactory;
+import org.apache.druid.query.aggregation.FilteredAggregatorFactory;
+import org.apache.druid.query.filter.NotDimFilter;
+import org.apache.druid.query.filter.SelectorDimFilter;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.column.ValueType;
+import org.apache.druid.sql.calcite.aggregation.Aggregation;
+import org.apache.druid.sql.calcite.aggregation.SqlAggregator;
+import org.apache.druid.sql.calcite.expression.DruidExpression;
+import org.apache.druid.sql.calcite.expression.Expressions;
+import org.apache.druid.sql.calcite.planner.Calcites;
+import org.apache.druid.sql.calcite.planner.PlannerContext;
+import org.apache.druid.sql.calcite.rel.VirtualColumnRegistry;
+
+import javax.annotation.Nullable;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+public class StringSqlAggregator implements SqlAggregator
+{
+  private static final String NAME = "STRING_AGG";
+  private static final SqlAggFunction FUNCTION = new StringAggFunction();
+
+  @Override
+  public SqlAggFunction calciteFunction()
+  {
+    return FUNCTION;
+  }
+
+  @Nullable
+  @Override
+  public Aggregation toDruidAggregation(
+      PlannerContext plannerContext,
+      RowSignature rowSignature,
+      VirtualColumnRegistry virtualColumnRegistry,
+      RexBuilder rexBuilder,
+      String name,
+      AggregateCall aggregateCall,
+      Project project,
+      List<Aggregation> existingAggregations,
+      boolean finalizeAggregations
+  )
+  {
+    final List<DruidExpression> arguments = aggregateCall
+        .getArgList()
+        .stream()
+        .map(i -> Expressions.fromFieldAccess(rowSignature, project, i))
+        .map(rexNode -> Expressions.toDruidExpression(plannerContext, rowSignature, rexNode))
+        .collect(Collectors.toList());
+
+    if (arguments.stream().anyMatch(Objects::isNull)) {
+      return null;
+    }
+
+    RexNode separatorNode = Expressions.fromFieldAccess(
+        rowSignature,
+        project,
+        aggregateCall.getArgList().get(1)
+    );
+    if (!separatorNode.isA(SqlKind.LITERAL)) {
+      // separator must be a literal
+      return null;
+    }
+    String separator = RexLiteral.stringValue(separatorNode);
+
+    if (separator == null) {
+      // separator must not be null
+      return null;
+    }
+
+    Integer maxSizeBytes = null;
+    if (arguments.size() > 2) {
+      RexNode maxBytes = Expressions.fromFieldAccess(
+          rowSignature,
+          project,
+          aggregateCall.getArgList().get(2)
+      );
+      if (!maxBytes.isA(SqlKind.LITERAL)) {
+        // maxBytes must be a literal
+        return null;
+      }
+      maxSizeBytes = ((Number) RexLiteral.value(maxBytes)).intValue();
+    }
+    final DruidExpression arg = arguments.get(0);

Review comment:
       should be `aggregationColumnArg`




-- 
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.

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



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] clintropolis commented on a change in pull request #11241: STRING_AGG SQL aggregator function

Posted by GitBox <gi...@apache.org>.
clintropolis commented on a change in pull request #11241:
URL: https://github.com/apache/druid/pull/11241#discussion_r647996719



##########
File path: sql/src/main/java/org/apache/druid/sql/calcite/aggregation/builtin/StringSqlAggregator.java
##########
@@ -0,0 +1,219 @@
+/*
+ * 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.druid.sql.calcite.aggregation.builtin;
+
+import com.google.common.collect.ImmutableSet;
+import org.apache.calcite.rel.core.AggregateCall;
+import org.apache.calcite.rel.core.Project;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.sql.SqlAggFunction;
+import org.apache.calcite.sql.SqlFunctionCategory;
+import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.sql.type.InferTypes;
+import org.apache.calcite.sql.type.OperandTypes;
+import org.apache.calcite.sql.type.SqlTypeFamily;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.calcite.util.Optionality;
+import org.apache.druid.java.util.common.HumanReadableBytes;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.math.expr.ExprMacroTable;
+import org.apache.druid.query.aggregation.ExpressionLambdaAggregatorFactory;
+import org.apache.druid.query.aggregation.FilteredAggregatorFactory;
+import org.apache.druid.query.filter.NotDimFilter;
+import org.apache.druid.query.filter.SelectorDimFilter;
+import org.apache.druid.segment.VirtualColumn;
+import org.apache.druid.segment.column.RowSignature;
+import org.apache.druid.segment.column.ValueType;
+import org.apache.druid.sql.calcite.aggregation.Aggregation;
+import org.apache.druid.sql.calcite.aggregation.SqlAggregator;
+import org.apache.druid.sql.calcite.expression.DruidExpression;
+import org.apache.druid.sql.calcite.expression.Expressions;
+import org.apache.druid.sql.calcite.planner.Calcites;
+import org.apache.druid.sql.calcite.planner.PlannerContext;
+import org.apache.druid.sql.calcite.rel.VirtualColumnRegistry;
+
+import javax.annotation.Nullable;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+public class StringSqlAggregator implements SqlAggregator
+{
+  private static final String NAME = "STRING_AGG";
+  private static final SqlAggFunction FUNCTION = new StringAggFunction();
+
+  @Override
+  public SqlAggFunction calciteFunction()
+  {
+    return FUNCTION;
+  }
+
+  @Nullable
+  @Override
+  public Aggregation toDruidAggregation(
+      PlannerContext plannerContext,
+      RowSignature rowSignature,
+      VirtualColumnRegistry virtualColumnRegistry,
+      RexBuilder rexBuilder,
+      String name,
+      AggregateCall aggregateCall,
+      Project project,
+      List<Aggregation> existingAggregations,
+      boolean finalizeAggregations
+  )
+  {
+    final List<DruidExpression> arguments = aggregateCall
+        .getArgList()
+        .stream()
+        .map(i -> Expressions.fromFieldAccess(rowSignature, project, i))
+        .map(rexNode -> Expressions.toDruidExpression(plannerContext, rowSignature, rexNode))
+        .collect(Collectors.toList());
+
+    if (arguments.stream().anyMatch(Objects::isNull)) {
+      return null;
+    }
+
+    RexNode separatorNode = Expressions.fromFieldAccess(
+        rowSignature,
+        project,
+        aggregateCall.getArgList().get(1)
+    );
+    if (!separatorNode.isA(SqlKind.LITERAL)) {
+      // separator must be a literal
+      return null;
+    }
+    String separator = RexLiteral.stringValue(separatorNode);
+
+    if (separator == null) {
+      // separator must not be null
+      return null;
+    }
+
+    Integer maxSizeBytes = null;
+    if (arguments.size() > 2) {
+      RexNode maxBytes = Expressions.fromFieldAccess(
+          rowSignature,
+          project,
+          aggregateCall.getArgList().get(2)
+      );
+      if (!maxBytes.isA(SqlKind.LITERAL)) {
+        // maxBytes must be a literal
+        return null;
+      }
+      maxSizeBytes = ((Number) RexLiteral.value(maxBytes)).intValue();
+    }
+    final DruidExpression arg = arguments.get(0);
+    final ExprMacroTable macroTable = plannerContext.getExprMacroTable();
+
+    final String initialvalue = "[]";
+    final ValueType elementType = ValueType.STRING;
+    final String fieldName;
+    if (arg.isDirectColumnAccess()) {
+      fieldName = arg.getDirectColumn();
+    } else {
+      VirtualColumn vc = virtualColumnRegistry.getOrCreateVirtualColumnForExpression(plannerContext, arg, elementType);
+      fieldName = vc.getOutputName();
+    }
+
+    final String finalizer = StringUtils.format("if(array_length(o) == 0, null, array_to_string(o, '%s'))", separator);
+    final NotDimFilter dimFilter = new NotDimFilter(new SelectorDimFilter(fieldName, null, null));
+    if (aggregateCall.isDistinct()) {
+      return Aggregation.create(
+          // string_agg ignores nulls
+          new FilteredAggregatorFactory(
+              new ExpressionLambdaAggregatorFactory(
+                  name,
+                  ImmutableSet.of(fieldName),
+                  null,
+                  initialvalue,
+                  null,
+                  StringUtils.format("array_set_add(\"__acc\", \"%s\")", fieldName),
+                  StringUtils.format("array_set_add_all(\"__acc\", \"%s\")", name),
+                  null,
+                  finalizer,
+                  maxSizeBytes != null ? new HumanReadableBytes(maxSizeBytes) : null,
+                  macroTable
+              ),
+              dimFilter
+          )
+      );
+    } else {
+      return Aggregation.create(
+          // string_agg ignores nulls
+          new FilteredAggregatorFactory(
+              new ExpressionLambdaAggregatorFactory(
+                  name,
+                  ImmutableSet.of(fieldName),
+                  null,
+                  initialvalue,
+                  null,
+                  StringUtils.format("array_append(\"__acc\", \"%s\")", fieldName),
+                  StringUtils.format("array_concat(\"__acc\", \"%s\")", name),
+                  null,
+                  finalizer,
+                  maxSizeBytes != null ? new HumanReadableBytes(maxSizeBytes) : null,
+                  macroTable
+              ),
+              dimFilter
+          )
+      );
+    }
+  }
+
+  private static class StringAggFunction extends SqlAggFunction
+  {
+    StringAggFunction()
+    {
+      super(
+          NAME,
+          null,
+          SqlKind.OTHER_FUNCTION,
+          opBinding ->
+              Calcites.createSqlTypeWithNullability(opBinding.getTypeFactory(), SqlTypeName.VARCHAR, true),
+          InferTypes.ANY_NULLABLE,
+          OperandTypes.or(
+              OperandTypes.and(
+                  OperandTypes.sequence(
+                      StringUtils.format("'%s'(expr, separator)", NAME),
+                      OperandTypes.ANY,
+                      OperandTypes.LITERAL

Review comment:
       btw, I'm going to hold off on updating this PR until #11280 goes in, since it has a slight refactor/improvement of the underlying expression aggregator that will require some minor changes in this PR.




-- 
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.

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



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org