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

[GitHub] [pinot] weixiangsun commented on a change in pull request #7781: Add Post-Aggregation Gapfilling functionality.

weixiangsun commented on a change in pull request #7781:
URL: https://github.com/apache/pinot/pull/7781#discussion_r751450736



##########
File path: pinot-core/src/main/java/org/apache/pinot/core/query/reduce/GapFillGroupByDataTableReducer.java
##########
@@ -0,0 +1,725 @@
+/**
+ * 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.reduce;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import org.apache.pinot.common.exception.QueryException;
+import org.apache.pinot.common.metrics.BrokerGauge;
+import org.apache.pinot.common.metrics.BrokerMeter;
+import org.apache.pinot.common.metrics.BrokerMetrics;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.FilterContext;
+import org.apache.pinot.common.response.broker.AggregationResult;
+import org.apache.pinot.common.response.broker.BrokerResponseNative;
+import org.apache.pinot.common.response.broker.GroupByResult;
+import org.apache.pinot.common.response.broker.QueryProcessingException;
+import org.apache.pinot.common.response.broker.ResultTable;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.common.utils.DataSchema.ColumnDataType;
+import org.apache.pinot.common.utils.DataTable;
+import org.apache.pinot.core.data.table.ConcurrentIndexedTable;
+import org.apache.pinot.core.data.table.IndexedTable;
+import org.apache.pinot.core.data.table.Key;
+import org.apache.pinot.core.data.table.Record;
+import org.apache.pinot.core.data.table.SimpleIndexedTable;
+import org.apache.pinot.core.data.table.UnboundedConcurrentIndexedTable;
+import org.apache.pinot.core.operator.combine.GroupByOrderByCombineOperator;
+import org.apache.pinot.core.query.aggregation.function.AggregationFunction;
+import org.apache.pinot.core.query.aggregation.function.AggregationFunctionUtils;
+import org.apache.pinot.core.query.aggregation.groupby.AggregationGroupByTrimmingService;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.core.transport.ServerRoutingInstance;
+import org.apache.pinot.core.util.GroupByUtils;
+import org.apache.pinot.core.util.QueryOptionsUtils;
+import org.apache.pinot.core.util.trace.TraceRunnable;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.DateTimeGranularitySpec;
+
+
+/**
+ * Helper class to reduce data tables and set group by results into the BrokerResponseNative
+ */
+@SuppressWarnings({"rawtypes", "unchecked"})
+public class GapFillGroupByDataTableReducer implements DataTableReducer {
+  private static final int MIN_DATA_TABLES_FOR_CONCURRENT_REDUCE = 2; // TBD, find a better value.
+
+  private final QueryContext _queryContext;
+  private final AggregationFunction[] _aggregationFunctions;
+  private final int _numAggregationFunctions;
+  private final List<ExpressionContext> _groupByExpressions;
+  private final int _numGroupByExpressions;
+  private final int _numColumns;
+  private final boolean _preserveType;
+  private final boolean _groupByModeSql;
+  private final boolean _responseFormatSql;
+  private final boolean _sqlQuery;
+  private final DateTimeGranularitySpec _dateTimeGranularity;
+  private final DateTimeFormatSpec _dateTimeFormatter;
+  private final long _startMs;
+  private final long _endMs;
+  private final Set<Key> _primaryKeys;
+  private final Map<Key, Object[]> _previous;
+  private final int _numOfKeyColumns;
+
+  GapFillGroupByDataTableReducer(QueryContext queryContext) {
+    _queryContext = queryContext;
+    _aggregationFunctions = queryContext.getAggregationFunctions();
+    assert _aggregationFunctions != null;
+    _numAggregationFunctions = _aggregationFunctions.length;
+    _groupByExpressions = queryContext.getGroupByExpressions();
+    assert _groupByExpressions != null;
+    _numGroupByExpressions = _groupByExpressions.size();
+    _numColumns = _numAggregationFunctions + _numGroupByExpressions;
+    Map<String, String> queryOptions = queryContext.getQueryOptions();
+    _preserveType = QueryOptionsUtils.isPreserveType(queryOptions);
+    _groupByModeSql = QueryOptionsUtils.isGroupByModeSQL(queryOptions);
+    _responseFormatSql = QueryOptionsUtils.isResponseFormatSQL(queryOptions);
+    _sqlQuery = queryContext.getBrokerRequest().getPinotQuery() != null;
+
+    ExpressionContext firstExpressionContext = _queryContext.getSelectExpressions().get(0);
+    List<ExpressionContext> args = firstExpressionContext.getFunction().getArguments();
+    _dateTimeFormatter = new DateTimeFormatSpec(args.get(1).getLiteral());
+    _dateTimeGranularity = new DateTimeGranularitySpec(args.get(4).getLiteral());
+    String start = args.get(2).getLiteral();
+    String end = args.get(3).getLiteral();
+    _startMs = truncate(_dateTimeFormatter.fromFormatToMillis(start));
+    _endMs = truncate(_dateTimeFormatter.fromFormatToMillis(end));
+    _primaryKeys = new HashSet<>();
+    _previous = new HashMap<>();
+    _numOfKeyColumns = _queryContext.getGroupByExpressions().size() - 1;
+  }
+
+  private long truncate(long epoch) {
+    int sz = _dateTimeGranularity.getSize();
+    return epoch / sz * sz;
+  }
+
+  /**
+   * Reduces and sets group by results into ResultTable, if responseFormat = sql
+   * By default, sets group by results into GroupByResults
+   */
+  @Override
+  public void reduceAndSetResults(String tableName, DataSchema dataSchema,
+      Map<ServerRoutingInstance, DataTable> dataTableMap, BrokerResponseNative brokerResponseNative,
+      DataTableReducerContext reducerContext, BrokerMetrics brokerMetrics) {
+    assert dataSchema != null;
+    int resultSize = 0;
+    Collection<DataTable> dataTables = dataTableMap.values();
+
+    // For group by, PQL behavior is different than the SQL behavior. In the PQL way,
+    // a result is generated for each aggregation in the query,
+    // and the group by keys are not the same across the aggregations
+    // This PQL style of execution makes it impossible to support order by on group by.
+    //
+    // We could not simply change the group by execution behavior,
+    // as that would not be backward compatible for existing users of group by.
+    // As a result, we have 2 modes of group by execution - pql and sql - which can be controlled via query options
+    //
+    // Long term, we may completely move to sql, and keep only full sql mode alive
+    // Until then, we need to support responseFormat = sql for both the modes of execution.
+    // The 4 variants are as described below:
+
+    if (_groupByModeSql) {
+
+      if (_responseFormatSql) {
+        // 1. groupByMode = sql, responseFormat = sql
+        // This is the primary SQL compliant group by
+
+        try {
+          setSQLGroupByInResultTable(brokerResponseNative, dataSchema, dataTables, reducerContext, tableName,
+              brokerMetrics);
+        } catch (TimeoutException e) {
+          brokerResponseNative.getProcessingExceptions()
+              .add(new QueryProcessingException(QueryException.BROKER_TIMEOUT_ERROR_CODE, e.getMessage()));
+        }
+        resultSize = brokerResponseNative.getResultTable().getRows().size();
+      } else {
+        // 2. groupByMode = sql, responseFormat = pql
+        // This mode will invoke SQL style group by execution, but present results in PQL way
+        // This mode is useful for users who want to avail of SQL compliant group by behavior,
+        // w/o having to forcefully move to a new result type
+
+        try {
+          setSQLGroupByInAggregationResults(brokerResponseNative, dataSchema, dataTables, reducerContext);
+        } catch (TimeoutException e) {
+          brokerResponseNative.getProcessingExceptions()
+              .add(new QueryProcessingException(QueryException.BROKER_TIMEOUT_ERROR_CODE, e.getMessage()));
+        }
+
+        if (!brokerResponseNative.getAggregationResults().isEmpty()) {
+          resultSize = brokerResponseNative.getAggregationResults().get(0).getGroupByResult().size();
+        }
+      }
+    } else {
+
+      // 3. groupByMode = pql, responseFormat = sql
+      // This mode is for users who want response presented in SQL style, but want PQL style group by behavior
+      // Multiple aggregations in PQL violates the tabular nature of results
+      // As a result, in this mode, only single aggregations are supported
+
+      // 4. groupByMode = pql, responseFormat = pql
+      // This is the primary PQL compliant group by
+
+      setGroupByResults(brokerResponseNative, dataTables);
+
+      if (_responseFormatSql) {
+        resultSize = brokerResponseNative.getResultTable().getRows().size();
+      } else {
+        // We emit the group by size when the result isn't empty. All the sizes among group-by results should be the
+        // same.
+        // Thus, we can just emit the one from the 1st result.
+        if (!brokerResponseNative.getAggregationResults().isEmpty()) {
+          resultSize = brokerResponseNative.getAggregationResults().get(0).getGroupByResult().size();
+        }
+      }
+    }
+
+    if (brokerMetrics != null && resultSize > 0) {
+      brokerMetrics.addMeteredTableValue(tableName, BrokerMeter.GROUP_BY_SIZE, resultSize);
+    }
+  }
+
+  private Key constructKey(Object[] row) {
+    Object [] keyColumns = new Object[_numOfKeyColumns];
+    for (int i = 0; i < _numOfKeyColumns; i++) {
+      keyColumns[i] = row[i + 1];
+    }
+    return new Key(keyColumns);

Review comment:
       Done




-- 
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@pinot.apache.org

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



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