Skip to content

Commit

Permalink
Timestamp in MSE (#14690)
Browse files Browse the repository at this point in the history
  • Loading branch information
gortiz authored Jan 7, 2025
1 parent 3ee3dd4 commit 6e9a70f
Show file tree
Hide file tree
Showing 10 changed files with 547 additions and 84 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@
import org.apache.pinot.spi.utils.CommonConstants.Broker;
import org.apache.pinot.spi.utils.CommonConstants.Broker.Request.QueryOptionKey;
import org.apache.pinot.spi.utils.DataSizeUtils;
import org.apache.pinot.spi.utils.TimestampIndexUtils;
import org.apache.pinot.spi.utils.builder.TableNameBuilder;
import org.apache.pinot.sql.FilterKind;
import org.apache.pinot.sql.parsers.CalciteSqlCompiler;
Expand Down Expand Up @@ -938,24 +937,7 @@ private void setTimestampIndexExpressionOverrideHints(@Nullable Expression expre
return;
}
Function function = expression.getFunctionCall();
switch (function.getOperator()) {
case "datetrunc":
String granularString = function.getOperands().get(0).getLiteral().getStringValue().toUpperCase();
Expression timeExpression = function.getOperands().get(1);
if (((function.getOperandsSize() == 2) || (function.getOperandsSize() == 3 && "MILLISECONDS".equalsIgnoreCase(
function.getOperands().get(2).getLiteral().getStringValue()))) && TimestampIndexUtils.isValidGranularity(
granularString) && timeExpression.getIdentifier() != null) {
String timeColumn = timeExpression.getIdentifier().getName();
String timeColumnWithGranularity = TimestampIndexUtils.getColumnWithGranularity(timeColumn, granularString);
if (timestampIndexColumns.contains(timeColumnWithGranularity)) {
pinotQuery.putToExpressionOverrideHints(expression,
RequestUtils.getIdentifierExpression(timeColumnWithGranularity));
}
}
break;
default:
break;
}
RequestUtils.applyTimestampIndexOverrideHints(expression, pinotQuery, timestampIndexColumns::contains);
function.getOperands()
.forEach(operand -> setTimestampIndexExpressionOverrideHints(operand, timestampIndexColumns, pinotQuery));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
Expand All @@ -42,6 +43,7 @@
import org.apache.calcite.sql.SqlNumericLiteral;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.pinot.common.function.TransformFunctionType;
import org.apache.pinot.common.request.DataSource;
import org.apache.pinot.common.request.Expression;
import org.apache.pinot.common.request.ExpressionType;
Expand All @@ -53,6 +55,7 @@
import org.apache.pinot.spi.utils.BigDecimalUtils;
import org.apache.pinot.spi.utils.BytesUtils;
import org.apache.pinot.spi.utils.CommonConstants.Broker.Request;
import org.apache.pinot.spi.utils.TimestampIndexUtils;
import org.apache.pinot.sql.FilterKind;
import org.apache.pinot.sql.parsers.CalciteSqlParser;
import org.apache.pinot.sql.parsers.SqlCompilationException;
Expand Down Expand Up @@ -631,4 +634,32 @@ public static Map<String, String> getOptionsFromJson(JsonNode request, String op
public static Map<String, String> getOptionsFromString(String optionStr) {
return Splitter.on(';').omitEmptyStrings().trimResults().withKeyValueSeparator('=').split(optionStr);
}

public static void applyTimestampIndexOverrideHints(Expression expression, PinotQuery query) {
applyTimestampIndexOverrideHints(expression, query, timeColumnWithGranularity -> true);
}

public static void applyTimestampIndexOverrideHints(
Expression expression, PinotQuery query, Predicate<String> timeColumnWithGranularityPredicate
) {
if (!expression.isSetFunctionCall()) {
return;
}
Function function = expression.getFunctionCall();
if (!function.getOperator().equalsIgnoreCase(TransformFunctionType.DATE_TRUNC.getName())) {
return;
}
String granularString = function.getOperands().get(0).getLiteral().getStringValue().toUpperCase();
Expression timeExpression = function.getOperands().get(1);
if (((function.getOperandsSize() == 2) || (function.getOperandsSize() == 3 && "MILLISECONDS".equalsIgnoreCase(
function.getOperands().get(2).getLiteral().getStringValue()))) && TimestampIndexUtils.isValidGranularity(
granularString) && timeExpression.getIdentifier() != null) {
String timeColumn = timeExpression.getIdentifier().getName();
String timeColumnWithGranularity = TimestampIndexUtils.getColumnWithGranularity(timeColumn, granularString);

if (timeColumnWithGranularityPredicate.test(timeColumnWithGranularity)) {
query.putToExpressionOverrideHints(expression, getIdentifierExpression(timeColumnWithGranularity));
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import java.util.concurrent.ExecutorService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.pinot.common.metrics.ServerMetrics;
import org.apache.pinot.common.request.context.ExpressionContext;
import org.apache.pinot.common.request.context.FilterContext;
Expand All @@ -46,6 +47,7 @@
import org.apache.pinot.core.plan.StreamingInstanceResponsePlanNode;
import org.apache.pinot.core.plan.StreamingSelectionPlanNode;
import org.apache.pinot.core.plan.TimeSeriesPlanNode;
import org.apache.pinot.core.query.aggregation.function.AggregationFunction;
import org.apache.pinot.core.query.executor.ResultsBlockStreamer;
import org.apache.pinot.core.query.prefetch.FetchPlanner;
import org.apache.pinot.core.query.prefetch.FetchPlannerRegistry;
Expand Down Expand Up @@ -321,6 +323,7 @@ public Plan makeStreamingInstancePlan(List<SegmentContext> segmentContexts, Quer
public PlanNode makeStreamingSegmentPlanNode(SegmentContext segmentContext, QueryContext queryContext) {
if (QueryContextUtils.isSelectionOnlyQuery(queryContext) && queryContext.getLimit() != 0) {
// Use streaming operator only for non-empty selection-only query
rewriteQueryContextWithHints(queryContext, segmentContext.getIndexSegment());
return new StreamingSelectionPlanNode(segmentContext, queryContext);
} else {
return makeSegmentPlanNode(segmentContext, queryContext);
Expand All @@ -344,6 +347,17 @@ public static void rewriteQueryContextWithHints(QueryContext queryContext, Index
selectExpressions.replaceAll(
expression -> overrideWithExpressionHints(expression, indexSegment, expressionOverrideHints));

List<Pair<AggregationFunction, FilterContext>> filtAggrFuns = queryContext.getFilteredAggregationFunctions();
if (filtAggrFuns != null) {
for (Pair<AggregationFunction, FilterContext> filteredAggregationFunction : filtAggrFuns) {
FilterContext right = filteredAggregationFunction.getRight();
if (right != null) {
Predicate predicate = right.getPredicate();
predicate.setLhs(overrideWithExpressionHints(predicate.getLhs(), indexSegment, expressionOverrideHints));
}
}
}

List<ExpressionContext> groupByExpressions = queryContext.getGroupByExpressions();
if (CollectionUtils.isNotEmpty(groupByExpressions)) {
groupByExpressions.replaceAll(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,22 +186,22 @@ protected String getSortedColumn() {

@Nullable
protected List<String> getInvertedIndexColumns() {
return DEFAULT_INVERTED_INDEX_COLUMNS;
return new ArrayList<>(DEFAULT_INVERTED_INDEX_COLUMNS);
}

@Nullable
protected List<String> getNoDictionaryColumns() {
return DEFAULT_NO_DICTIONARY_COLUMNS;
return new ArrayList<>(DEFAULT_NO_DICTIONARY_COLUMNS);
}

@Nullable
protected List<String> getRangeIndexColumns() {
return DEFAULT_RANGE_INDEX_COLUMNS;
return new ArrayList<>(DEFAULT_RANGE_INDEX_COLUMNS);
}

@Nullable
protected List<String> getBloomFilterColumns() {
return DEFAULT_BLOOM_FILTER_COLUMNS;
return new ArrayList<>(DEFAULT_BLOOM_FILTER_COLUMNS);
}

@Nullable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,7 @@ protected JsonNode getDebugInfo(final String uri)
/**
* Queries the broker's sql query endpoint (/query/sql)
*/
protected JsonNode postQuery(String query)
public JsonNode postQuery(String query)
throws Exception {
return postQuery(query, getBrokerQueryApiUrl(getBrokerBaseApiUrl(), useMultiStageQueryEngine()), null,
getExtraQueryProperties());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/**
* 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.integration.tests;

import com.fasterxml.jackson.databind.JsonNode;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.pinot.spi.utils.JsonUtils;
import org.intellij.lang.annotations.Language;
import org.testng.Assert;


public interface ExplainIntegrationTestTrait {

JsonNode postQuery(@Language("sql") String query)
throws Exception;

default void explainLogical(@Language("sql") String query, String expected) {
try {
JsonNode jsonNode = postQuery("explain plan without implementation for " + query);
JsonNode plan = jsonNode.get("resultTable").get("rows").get(0).get(1);

Assert.assertEquals(plan.asText(), expected);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}

default void explainSse(boolean verbose, @Language("sql") String query, Object... expected) {
try {
@Language("sql")
String actualQuery = "SET useMultistageEngine=false; explain plan for " + query;
if (verbose) {
actualQuery = "SET explainPlanVerbose=true; " + actualQuery;
}
JsonNode jsonNode = postQuery(actualQuery);
JsonNode plan = jsonNode.get("resultTable").get("rows");
List<String> planAsStrList = (List<String>) JsonUtils.jsonNodeToObject(plan, List.class).stream()
.map(Object::toString)
.collect(Collectors.toList());

if (planAsStrList.size() != expected.length) {
Assert.fail("Actual: " + planAsStrList + ", Expected: " + Arrays.toString(expected)
+ ". Size mismatch. Actual: " + planAsStrList.size() + ", Expected: " + expected.length);
}
for (int i = 0; i < planAsStrList.size(); i++) {
String planAsStr = planAsStrList.get(i);
Object expectedObj = expected[i];
if (expectedObj instanceof Pattern) {
Assert.assertTrue(((Pattern) expectedObj).matcher(planAsStr).matches(),
"Pattern doesn't match. Actual: " + planAsStr + ", Expected: " + expectedObj
+ ", Actual complete plan: " + planAsStrList);
} else if (expectedObj instanceof String) {
Assert.assertEquals(planAsStr, expectedObj, "Actual: " + planAsStr + ", Expected: " + expectedObj
+ ", Actual complete plan: " + planAsStrList);
} else {
Assert.fail("Expected object should be either Pattern or String in position " + i + ". Actual: "
+ expectedObj + " of type " + expectedObj.getClass());
}
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}

default void explainSse(@Language("sql") String query, Object... expected) {
explainSse(false, query, expected);
}

default void explain(@Language("sql") String query, String expected) {
try {
JsonNode jsonNode = postQuery("explain plan for " + query);
JsonNode plan = jsonNode.get("resultTable").get("rows").get(0).get(1);

Assert.assertEquals(plan.asText(), expected);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}

default void explainVerbose(@Language("sql") String query, String expected) {
try {
JsonNode jsonNode = postQuery("set explainPlanVerbose=true; explain plan for " + query);
JsonNode plan = jsonNode.get("resultTable").get("rows").get(0).get(1);

String actual = plan.asText()
.replaceAll("numDocs=\\[[^\\]]*]", "numDocs=[any]")
.replaceAll("segment=\\[[^\\]]*]", "segment=[any]")
.replaceAll("totalDocs=\\[[^\\]]*]", "totalDocs=[any]");


Assert.assertEquals(actual, expected);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Loading

0 comments on commit 6e9a70f

Please sign in to comment.