This is an automated email from the ASF dual-hosted git repository.
raghavyadav01 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git
The following commit(s) were added to refs/heads/master by this push:
new 2edb2e7e750 Support OPEN_STRUCT columns in the multi-stage engine
(#20303)
2edb2e7e750 is described below
commit 2edb2e7e7504c3795be444eb0bb336dcb745b00c
Author: RAGHVENDRA KUMAR YADAV <[email protected]>
AuthorDate: Fri Nov 20 22:19:29 2026 -0800
Support OPEN_STRUCT columns in the multi-stage engine (#20303)
* Support OPEN_STRUCT columns in the multi-stage engine
Every multi-stage query on a table with an OPEN_STRUCT column failed with
'Unsupported type: OPEN_STRUCT'. The column is now an OpenStructSqlType (a
MAP<VARCHAR, VARCHAR> carrying the declared child types): a key read v['k']
is
typed by the key's declared child field spec, else VARCHAR, and the whole
column is JSON text, as in the single-stage engine. The leaf converts values
by their logical type where the plan types them differently.
* Test the OPEN_STRUCT planner paths the first round left uncovered
Plan the column with the physical optimizer (its own row-type converter
maps it
to JSON), ITEM on array operands, a key typed by the declaration of the
column
it is read from, child specs by shape (multi-value, complex, nullability),
the
canonical type on nullability changes, and leastRestrictive falling back to
Calcite for other mixes.
* Apply OPEN_STRUCT key types before segment operations
Reproduce the incorrect result by storing an undeclared integer key with
values 2 and 10 and ordering or filtering it through a multi-stage query. The
planner exposes the key as VARCHAR while the segment previously compared it as
an integer.
Carry the planned type to the segment, preserve indexes on matching keys,
and convert mismatches before evaluation. Keep whole documents usable in CASE
and COALESCE, distinguish declared keys in Calcite's type cache, and validate
computed operands before dispatch.
* Test planned key types and CASE over OPEN_STRUCT documents
Cover that a pushed-down OPEN_STRUCT key read carries its planned type
(VARCHAR for an undeclared key, the declared type otherwise), and that a
CASE branch holding a whole OPEN_STRUCT column reads as its JSON text.
* Verify each OPEN_STRUCT key type in the leaf plan
The assertion previously accepted a typed ITEM in any stage and skipped
untyped calls. Restrict it to table-scanning fragments and check the arity of
every key lookup so moving the conversion above an exchange fails the test.
---------
Co-authored-by: Xiang Fu <[email protected]>
---
.../org/apache/pinot/common/utils/DataSchema.java | 2 +
.../core/operator/filter/MapFilterOperator.java | 21 +-
.../transform/function/CaseTransformFunction.java | 4 +
.../function/CoalesceTransformFunction.java | 4 +
.../transform/function/ItemTransformFunction.java | 167 +++++++++++--
.../filter/MapFilterOperatorOpenStructTest.java | 7 +
.../CaseTransformFunctionOpenStructTest.java | 69 ++++++
.../ItemTransformFunctionScalarTypeTest.java | 50 ++++
.../custom/OpenStructIngestionCommitTestBase.java | 91 +++++++-
.../pinot/calcite/sql/fun/PinotItemOperator.java | 69 ++++++
.../pinot/calcite/sql/fun/PinotOperatorTable.java | 3 +-
.../planner/logical/RelToPlanNodeConverter.java | 5 +
.../query/planner/logical/RexExpressionUtils.java | 21 ++
.../physical/v2/PRelToPlanNodeConverter.java | 5 +
.../apache/pinot/query/type/OpenStructSqlType.java | 89 +++++++
.../org/apache/pinot/query/type/TypeFactory.java | 89 ++++++-
.../query/OpenStructMultiStagePlanningTest.java | 257 +++++++++++++++++++++
.../apache/pinot/query/type/TypeFactoryTest.java | 147 ++++++++++++
18 files changed, 1072 insertions(+), 28 deletions(-)
diff --git
a/pinot-common/src/main/java/org/apache/pinot/common/utils/DataSchema.java
b/pinot-common/src/main/java/org/apache/pinot/common/utils/DataSchema.java
index b4246d60616..f9236c137e8 100644
--- a/pinot-common/src/main/java/org/apache/pinot/common/utils/DataSchema.java
+++ b/pinot-common/src/main/java/org/apache/pinot/common/utils/DataSchema.java
@@ -1082,6 +1082,8 @@ public class DataSchema {
return PinotDataType.STRING_ARRAY;
case BYTES_ARRAY:
return PinotDataType.BYTES_ARRAY;
+ case UUID_ARRAY:
+ return PinotDataType.UUID_ARRAY;
default:
throw new IllegalStateException("Cannot convert ColumnDataType: " +
this + " to PinotDataType");
}
diff --git
a/pinot-core/src/main/java/org/apache/pinot/core/operator/filter/MapFilterOperator.java
b/pinot-core/src/main/java/org/apache/pinot/core/operator/filter/MapFilterOperator.java
index 636bf442a9b..c33cc0e9843 100644
---
a/pinot-core/src/main/java/org/apache/pinot/core/operator/filter/MapFilterOperator.java
+++
b/pinot-core/src/main/java/org/apache/pinot/core/operator/filter/MapFilterOperator.java
@@ -31,6 +31,7 @@ import
org.apache.pinot.common.request.context.predicate.NotEqPredicate;
import org.apache.pinot.common.request.context.predicate.NotInPredicate;
import org.apache.pinot.common.request.context.predicate.Predicate;
import org.apache.pinot.common.request.context.predicate.RangePredicate;
+import org.apache.pinot.common.utils.DataSchema.ColumnDataType;
import org.apache.pinot.core.common.BlockDocIdSet;
import org.apache.pinot.core.common.Operator;
import org.apache.pinot.core.operator.ExplainAttributeBuilder;
@@ -39,6 +40,7 @@ import
org.apache.pinot.core.operator.filter.predicate.PredicateEvaluatorProvide
import org.apache.pinot.core.query.request.context.QueryContext;
import org.apache.pinot.segment.spi.IndexSegment;
import org.apache.pinot.segment.spi.datasource.DataSource;
+import org.apache.pinot.segment.spi.datasource.DataSourceMetadata;
import org.apache.pinot.segment.spi.datasource.OpenStructDataSource;
import org.apache.pinot.segment.spi.index.IndexService;
import org.apache.pinot.segment.spi.index.IndexType;
@@ -76,8 +78,8 @@ public class MapFilterOperator extends BaseFilterOperator {
_predicate = predicate;
List<ExpressionContext> arguments =
predicate.getLhs().getFunction().getArguments();
- if (arguments.size() != 2) {
- throw new IllegalStateException("Expected two arguments (column name and
key name), found: " + arguments.size());
+ if (arguments.size() != 2 && arguments.size() != 3) {
+ throw new IllegalStateException("Expected column, key and optional
result type, found: " + arguments.size());
}
_columnName = arguments.get(0).getIdentifier();
@@ -86,13 +88,14 @@ public class MapFilterOperator extends BaseFilterOperator {
// Try dispatch paths in priority order
DataSource columnDs = indexSegment.getDataSourceNullable(_columnName);
- BaseFilterOperator perKey = tryPerKeyIndex(columnDs, queryContext,
numDocs);
+ String plannedType = arguments.size() == 3 ?
arguments.get(2).getLiteral().getStringValue() : null;
+ BaseFilterOperator perKey = tryPerKeyIndex(columnDs, queryContext,
numDocs, plannedType);
if (perKey != null) {
_delegate = perKey;
return;
}
- JsonMatchFilterOperator jsonOp = tryJsonIndex(columnDs, numDocs);
+ JsonMatchFilterOperator jsonOp = plannedType == null ?
tryJsonIndex(columnDs, numDocs) : null;
if (jsonOp != null) {
_delegate = jsonOp;
_delegateType = DelegateType.JSON_MATCH;
@@ -104,12 +107,20 @@ public class MapFilterOperator extends BaseFilterOperator
{
}
@Nullable
- private BaseFilterOperator tryPerKeyIndex(@Nullable DataSource columnDs,
QueryContext queryContext, int numDocs) {
+ private BaseFilterOperator tryPerKeyIndex(@Nullable DataSource columnDs,
QueryContext queryContext, int numDocs,
+ @Nullable String plannedType) {
if (!(columnDs instanceof OpenStructDataSource)) {
return null;
}
OpenStructDataSource osDs = (OpenStructDataSource) columnDs;
DataSource keyDs = osDs.getDataSource(_keyName);
+ if (plannedType != null) {
+ DataSourceMetadata metadata = keyDs.getDataSourceMetadata();
+ if (!ColumnDataType.fromDataType(metadata.getDataType(),
metadata.isSingleValue()).name().equals(plannedType)) {
+ // Per-key indexes compare the segment type. The expression scan
converts each key to its planned type first.
+ return null;
+ }
+ }
// Among unmaterialized keys only a sparse virtual source lacks a
dictionary; an absent key folds through its
// single-entry dictionary, which is cheaper on the per-key path than
consulting the blob's JSON index
if (!osDs.isMaterialized(_keyName) && keyDs.getDictionary() == null) {
diff --git
a/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/CaseTransformFunction.java
b/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/CaseTransformFunction.java
index 16ae22a76c1..b00cd9dc753 100644
---
a/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/CaseTransformFunction.java
+++
b/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/CaseTransformFunction.java
@@ -116,6 +116,10 @@ public class CaseTransformFunction extends
ComputeDifferentlyWhenNullHandlingEna
TransformResultMetadata newMetadata = newFunction.getResultMetadata();
Preconditions.checkArgument(newMetadata.isSingleValue(), "Unsupported
multi-value expression in THEN/ELSE clause");
DataType newType = newMetadata.getDataType();
+ // A whole OPEN_STRUCT branch supplies its JSON document through
transformToStringValuesSV.
+ if (newType == DataType.OPEN_STRUCT) {
+ newType = DataType.STRING;
+ }
if (newType == DataType.UNKNOWN) {
return;
}
diff --git
a/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/CoalesceTransformFunction.java
b/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/CoalesceTransformFunction.java
index f6721ef7f51..7d8744573a3 100644
---
a/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/CoalesceTransformFunction.java
+++
b/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/CoalesceTransformFunction.java
@@ -271,6 +271,10 @@ public class CoalesceTransformFunction extends
BaseTransformFunction {
for (int i = 0; i < argSize; i++) {
TransformFunction func = arguments.get(i);
DataType dataType = func.getResultMetadata().getDataType();
+ // A whole OPEN_STRUCT argument supplies its JSON document through
transformToStringValuesSV.
+ if (dataType == DataType.OPEN_STRUCT) {
+ dataType = DataType.STRING;
+ }
if (_dataType != null) {
_dataType = getCompatibleType(_dataType, dataType);
} else {
diff --git
a/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/ItemTransformFunction.java
b/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/ItemTransformFunction.java
index a9b567dc384..acb7b99d0c6 100644
---
a/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/ItemTransformFunction.java
+++
b/pinot-core/src/main/java/org/apache/pinot/core/operator/transform/function/ItemTransformFunction.java
@@ -18,20 +18,31 @@
*/
package org.apache.pinot.core.operator.transform.function;
+import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Preconditions;
+import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
+import org.apache.pinot.common.utils.DataSchema.ColumnDataType;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
import org.apache.pinot.core.operator.ColumnContext;
import org.apache.pinot.core.operator.blocks.ValueBlock;
import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
import org.apache.pinot.segment.spi.datasource.DataSource;
import org.apache.pinot.segment.spi.datasource.DataSourceMetadata;
import org.apache.pinot.segment.spi.datasource.MapDataSource;
import org.apache.pinot.segment.spi.datasource.OpenStructDataSource;
import org.apache.pinot.segment.spi.index.reader.Dictionary;
import org.apache.pinot.segment.spi.index.reader.ForwardIndexReader;
+import org.apache.pinot.spi.data.ComplexFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.apache.pinot.spi.utils.ByteArray;
+import org.apache.pinot.spi.utils.JsonUtils;
import org.roaringbitmap.RoaringBitmap;
@@ -43,11 +54,29 @@ public class ItemTransformFunction extends
BaseTransformFunction {
private Dictionary _dictionary;
private TransformResultMetadata _resultMetadata;
private boolean _perKeyNullsAvailable;
+ private ColumnDataType _sourceType;
+ // Set only when a multi-stage plan needs a different type from this segment.
+ @Nullable
+ private ColumnDataType _targetType;
+ private Object _defaultValue;
@Override
public void init(List<TransformFunction> arguments, Map<String,
ColumnContext> columnContextMap) {
+ initWithSchema(arguments, columnContextMap, null);
+ }
+
+ @Override
+ public void init(List<TransformFunction> arguments, Map<String,
ColumnContext> columnContextMap,
+ QueryContext queryContext) {
+ _nullHandlingEnabled = queryContext.isNullHandlingEnabled();
+ initWithSchema(arguments, columnContextMap, queryContext.getSchema());
+ }
+
+ private void initWithSchema(List<TransformFunction> arguments, Map<String,
ColumnContext> columnContextMap,
+ @Nullable Schema schema) {
super.init(arguments, columnContextMap);
- Preconditions.checkArgument(arguments.size() == 2, "Expected exactly 2
arguments, got: %s", arguments.size());
+ Preconditions.checkArgument(arguments.size() == 2 || arguments.size() == 3,
+ "Expected column, key and optional result type, got: %s arguments",
arguments.size());
TransformFunction mapValue = arguments.get(0);
Preconditions.checkArgument(mapValue instanceof
IdentifierTransformFunction,
@@ -68,15 +97,103 @@ public class ItemTransformFunction extends
BaseTransformFunction {
// Per-key nulls are exact whenever the key's source tracks them: every
OPEN_STRUCT key does, a MAP key only when
// it is absent from the segment
_perKeyNullsAvailable = valueDataSource.getNullValueVector() != null;
+ DataSourceMetadata metadata = valueDataSource.getDataSourceMetadata();
+ if (arguments.size() == 3) {
+ Preconditions.checkArgument(dataSource instanceof OpenStructDataSource
+ && arguments.get(2) instanceof LiteralTransformFunction, "Expected
an OPEN_STRUCT column and a result type");
+ String typeName = ((LiteralTransformFunction)
arguments.get(2)).getStringLiteral();
+ ColumnDataType targetType = ColumnDataType.valueOf(typeName);
+ _sourceType = ColumnDataType.fromDataType(metadata.getDataType(),
metadata.isSingleValue());
+ if (_sourceType != targetType) {
+ _targetType = targetType;
+ FieldSpec parent =
+ schema != null ? schema.getFieldSpecFor(column) :
((OpenStructDataSource) dataSource).getFieldSpec();
+ FieldSpec child = parent instanceof ComplexFieldSpec complex ?
complex.getChildFieldSpec(key) : null;
+ _defaultValue = getDefaultValue(targetType, child);
+ _resultMetadata = new TransformResultMetadata(targetType.toDataType(),
!targetType.isArray(), false);
+ return;
+ }
+ }
// Only expose the dictionary when the forward index is dict-encoded. A
column can have a dictionary alongside
// a RAW forward index (e.g. dict + inverted/range), in which case
transformToDictIdsSV would fail because
// BlockValueSet.getDictionaryIdsSV requires a dict-encoded forward index.
ForwardIndexReader<?> forwardIndex = valueDataSource.getForwardIndex();
_dictionary = forwardIndex != null && forwardIndex.isDictionaryEncoded() ?
valueDataSource.getDictionary() : null;
- DataSourceMetadata valueDataSourceMetadata =
valueDataSource.getDataSourceMetadata();
_resultMetadata =
- new TransformResultMetadata(valueDataSourceMetadata.getDataType(),
valueDataSourceMetadata.isSingleValue(),
- _dictionary != null);
+ new TransformResultMetadata(metadata.getDataType(),
metadata.isSingleValue(), _dictionary != null);
+ }
+
+ /// OPEN_STRUCT stores the declared default (or the dimension default for an
undeclared key) in absent rows.
+ /// A missing multi-value field stores a single element containing that same
default.
+ private static Object getDefaultValue(ColumnDataType targetType, @Nullable
FieldSpec child) {
+ FieldSpec.DataType type = targetType.toDataType();
+ // The planner maps JSON to VARCHAR. Types sharing storage, such as BYTES
and UUID, can have different defaults.
+ boolean matches = child != null && (child.getDataType() == type
+ || (child.getDataType() == FieldSpec.DataType.JSON && type ==
FieldSpec.DataType.STRING));
+ Object scalar = matches ? child.getDefaultNullValue()
+ : FieldSpec.getDefaultNullValue(FieldSpec.FieldType.DIMENSION, type,
null);
+ scalar = ColumnDataType.OBJECT.toInternal(scalar);
+ if (!targetType.isArray()) {
+ return scalar;
+ }
+ Object singleton =
Array.newInstance(targetType.getNullPlaceholder().getClass().getComponentType(),
1);
+ Array.set(singleton, 0, scalar);
+ return singleton;
+ }
+
+ /// Reads the key in its native representation before converting it. In
particular, asking a STRING dictionary
+ /// directly for numbers would parse even the placeholders of null rows.
Matching segments never take this path.
+ private <T> T convertValues(ValueBlock block, ColumnDataType readType,
Class<T> arrayClass) {
+ BlockValSet source = block.getBlockValueSet(_keyPath);
+ RowBasedBlockValueFetcher fetcher = new RowBasedBlockValueFetcher(new
BlockValSet[]{source});
+ // An absent key has no value to cast, even when the caller uses
placeholders instead of SQL nulls.
+ RoaringBitmap nulls = source.getNullBitmap();
+ int length = block.getNumDocs();
+ Object result = Array.newInstance(arrayClass.getComponentType(), length);
+ Object[] row = new Object[1];
+ boolean nativeRead = readType == _targetType.getStoredType();
+ for (int i = 0; i < length; i++) {
+ Object value;
+ boolean missing = nulls != null && nulls.contains(i);
+ if (missing && _nullHandlingEnabled) {
+ value = (nativeRead ? _targetType : readType).getNullPlaceholder();
+ } else {
+ try {
+ if (missing) {
+ value = _defaultValue;
+ } else {
+ fetcher.getRow(i, row, 0);
+ value = convertValue(row[0], _sourceType, _targetType);
+ }
+ if (!nativeRead) {
+ // An enclosing transform can request a different representation
of the already typed key.
+ value = convertValue(value, _targetType, readType);
+ }
+ } catch (RuntimeException | JsonProcessingException e) {
+ throw new IllegalStateException("Cannot convert " + _sourceType + "
key '" + _keyPath[1] + "' to "
+ + _targetType, e);
+ }
+ }
+ if (value instanceof ByteArray bytes) {
+ value = bytes.getBytes();
+ } else if (value instanceof ByteArray[] bytes) {
+ value = ColumnDataType.BYTES_ARRAY.toExternal(bytes);
+ }
+ Array.set(result, i, value);
+ }
+ return arrayClass.cast(result);
+ }
+
+ private static Object convertValue(Object value, ColumnDataType sourceType,
ColumnDataType targetType)
+ throws JsonProcessingException {
+ if (targetType == ColumnDataType.STRING) {
+ Object formatted = sourceType.convertAndFormat(value);
+ return sourceType.isArray() ? JsonUtils.objectToString(formatted) :
formatted.toString();
+ }
+ Preconditions.checkArgument(!sourceType.isArray() || targetType.isArray(),
"Cannot cast an array to a scalar");
+ Object converted =
targetType.toPinotDataType().convert(sourceType.toExternal(value),
sourceType.toPinotDataType());
+ // Preserve the row fetcher's internal representations, including
ByteArray[] for byte[][].
+ return ColumnDataType.OBJECT.toInternal(converted);
}
@Override
@@ -114,22 +231,26 @@ public class ItemTransformFunction extends
BaseTransformFunction {
@Override
public int[] transformToIntValuesSV(ValueBlock valueBlock) {
- return valueBlock.getBlockValueSet(_keyPath).getIntValuesSV();
+ return _targetType == null ?
valueBlock.getBlockValueSet(_keyPath).getIntValuesSV()
+ : convertValues(valueBlock, ColumnDataType.INT, int[].class);
}
@Override
public long[] transformToLongValuesSV(ValueBlock valueBlock) {
- return valueBlock.getBlockValueSet(_keyPath).getLongValuesSV();
+ return _targetType == null ?
valueBlock.getBlockValueSet(_keyPath).getLongValuesSV()
+ : convertValues(valueBlock, ColumnDataType.LONG, long[].class);
}
@Override
public float[] transformToFloatValuesSV(ValueBlock valueBlock) {
- return valueBlock.getBlockValueSet(_keyPath).getFloatValuesSV();
+ return _targetType == null ?
valueBlock.getBlockValueSet(_keyPath).getFloatValuesSV()
+ : convertValues(valueBlock, ColumnDataType.FLOAT, float[].class);
}
@Override
public double[] transformToDoubleValuesSV(ValueBlock valueBlock) {
- return valueBlock.getBlockValueSet(_keyPath).getDoubleValuesSV();
+ return _targetType == null ?
valueBlock.getBlockValueSet(_keyPath).getDoubleValuesSV()
+ : convertValues(valueBlock, ColumnDataType.DOUBLE, double[].class);
}
/// Without this the base class has no way to produce a BIG_DECIMAL: its
conversion switch widens INT, LONG, FLOAT,
@@ -138,17 +259,20 @@ public class ItemTransformFunction extends
BaseTransformFunction {
/// the cheaper path.
@Override
public BigDecimal[] transformToBigDecimalValuesSV(ValueBlock valueBlock) {
- return valueBlock.getBlockValueSet(_keyPath).getBigDecimalValuesSV();
+ return _targetType == null ?
valueBlock.getBlockValueSet(_keyPath).getBigDecimalValuesSV()
+ : convertValues(valueBlock, ColumnDataType.BIG_DECIMAL,
BigDecimal[].class);
}
@Override
public String[] transformToStringValuesSV(ValueBlock valueBlock) {
- return valueBlock.getBlockValueSet(_keyPath).getStringValuesSV();
+ return _targetType == null ?
valueBlock.getBlockValueSet(_keyPath).getStringValuesSV()
+ : convertValues(valueBlock, ColumnDataType.STRING, String[].class);
}
@Override
public byte[][] transformToBytesValuesSV(ValueBlock valueBlock) {
- return valueBlock.getBlockValueSet(_keyPath).getBytesValuesSV();
+ return _targetType == null ?
valueBlock.getBlockValueSet(_keyPath).getBytesValuesSV()
+ : convertValues(valueBlock, ColumnDataType.BYTES, byte[][].class);
}
// A key can hold a list, in which case its value source is multi-value and
the engine asks for the values that
@@ -162,22 +286,26 @@ public class ItemTransformFunction extends
BaseTransformFunction {
@Override
public int[][] transformToIntValuesMV(ValueBlock valueBlock) {
- return valueBlock.getBlockValueSet(_keyPath).getIntValuesMV();
+ return _targetType == null ?
valueBlock.getBlockValueSet(_keyPath).getIntValuesMV()
+ : convertValues(valueBlock, ColumnDataType.INT_ARRAY, int[][].class);
}
@Override
public long[][] transformToLongValuesMV(ValueBlock valueBlock) {
- return valueBlock.getBlockValueSet(_keyPath).getLongValuesMV();
+ return _targetType == null ?
valueBlock.getBlockValueSet(_keyPath).getLongValuesMV()
+ : convertValues(valueBlock, ColumnDataType.LONG_ARRAY, long[][].class);
}
@Override
public float[][] transformToFloatValuesMV(ValueBlock valueBlock) {
- return valueBlock.getBlockValueSet(_keyPath).getFloatValuesMV();
+ return _targetType == null ?
valueBlock.getBlockValueSet(_keyPath).getFloatValuesMV()
+ : convertValues(valueBlock, ColumnDataType.FLOAT_ARRAY,
float[][].class);
}
@Override
public double[][] transformToDoubleValuesMV(ValueBlock valueBlock) {
- return valueBlock.getBlockValueSet(_keyPath).getDoubleValuesMV();
+ return _targetType == null ?
valueBlock.getBlockValueSet(_keyPath).getDoubleValuesMV()
+ : convertValues(valueBlock, ColumnDataType.DOUBLE_ARRAY,
double[][].class);
}
/// The multi-value twin of [#transformToBigDecimalValuesSV]: the base class
widens INT, LONG, FLOAT, DOUBLE,
@@ -186,16 +314,19 @@ public class ItemTransformFunction extends
BaseTransformFunction {
/// that switch.
@Override
public BigDecimal[][] transformToBigDecimalValuesMV(ValueBlock valueBlock) {
- return valueBlock.getBlockValueSet(_keyPath).getBigDecimalValuesMV();
+ return _targetType == null ?
valueBlock.getBlockValueSet(_keyPath).getBigDecimalValuesMV()
+ : convertValues(valueBlock, ColumnDataType.BIG_DECIMAL_ARRAY,
BigDecimal[][].class);
}
@Override
public String[][] transformToStringValuesMV(ValueBlock valueBlock) {
- return valueBlock.getBlockValueSet(_keyPath).getStringValuesMV();
+ return _targetType == null ?
valueBlock.getBlockValueSet(_keyPath).getStringValuesMV()
+ : convertValues(valueBlock, ColumnDataType.STRING_ARRAY,
String[][].class);
}
@Override
public byte[][][] transformToBytesValuesMV(ValueBlock valueBlock) {
- return valueBlock.getBlockValueSet(_keyPath).getBytesValuesMV();
+ return _targetType == null ?
valueBlock.getBlockValueSet(_keyPath).getBytesValuesMV()
+ : convertValues(valueBlock, ColumnDataType.BYTES_ARRAY,
byte[][][].class);
}
}
diff --git
a/pinot-core/src/test/java/org/apache/pinot/core/operator/filter/MapFilterOperatorOpenStructTest.java
b/pinot-core/src/test/java/org/apache/pinot/core/operator/filter/MapFilterOperatorOpenStructTest.java
index 27c17091bfc..ba077abc3a9 100644
---
a/pinot-core/src/test/java/org/apache/pinot/core/operator/filter/MapFilterOperatorOpenStructTest.java
+++
b/pinot-core/src/test/java/org/apache/pinot/core/operator/filter/MapFilterOperatorOpenStructTest.java
@@ -233,6 +233,13 @@ public class MapFilterOperatorOpenStructTest {
MapFilterOperator op = new MapFilterOperator(segment, predicate, qc,
NUM_DOCS);
assertTrue(op.toExplainString().contains("delegateTo:per_key_index"));
+
+ // MSE carries the planned type. A matching key can use the same inverted
index.
+ ExpressionContext typedItem = ExpressionContext.forFunction(new
FunctionContext(FunctionContext.Type.TRANSFORM,
+ ItemTransformFunction.FUNCTION_NAME,
List.of(ExpressionContext.forIdentifier(COLUMN),
+ ExpressionContext.forLiteral(DataType.STRING, KEY),
ExpressionContext.forLiteral(DataType.STRING, "STRING"))));
+ MapFilterOperator typed = new MapFilterOperator(segment, new
EqPredicate(typedItem, "active"), qc, NUM_DOCS);
+ assertTrue(typed.toExplainString().contains("delegateTo:per_key_index"));
}
/// Absent key on a fully materialized segment with EQ → no doc matches
(getTrues returns EOF).
diff --git
a/pinot-core/src/test/java/org/apache/pinot/core/operator/transform/function/CaseTransformFunctionOpenStructTest.java
b/pinot-core/src/test/java/org/apache/pinot/core/operator/transform/function/CaseTransformFunctionOpenStructTest.java
new file mode 100644
index 00000000000..be1bc631775
--- /dev/null
+++
b/pinot-core/src/test/java/org/apache/pinot/core/operator/transform/function/CaseTransformFunctionOpenStructTest.java
@@ -0,0 +1,69 @@
+/**
+ * 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.operator.transform.function;
+
+import java.util.Map;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.RequestContextUtils;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.operator.blocks.ValueBlock;
+import org.apache.pinot.segment.spi.datasource.DataSource;
+import org.apache.pinot.segment.spi.datasource.DataSourceMetadata;
+import org.apache.pinot.segment.spi.datasource.OpenStructDataSource;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.testng.annotations.Test;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+
+
+/// A CASE branch that is a whole OPEN_STRUCT column is read as the column's
JSON document, the way a bare projection
+/// of the column reads it, so the leaf stage can fetch the CASE result.
+public class CaseTransformFunctionOpenStructTest {
+ private static final String DOCUMENT = "{\"latencyMs\":0}";
+
+ @Test
+ public void testOpenStructBranchIsReadAsJsonText() {
+ Map<String, DataSource> columns = Map.of("flag",
dataSource(DataSource.class, DataType.LONG),
+ "metrics", dataSource(OpenStructDataSource.class,
DataType.OPEN_STRUCT));
+ ExpressionContext expression = RequestContextUtils.getExpression("CASE
WHEN flag = 0 THEN metrics ELSE NULL END");
+ TransformFunction function = TransformFunctionFactory.get(expression,
columns);
+ assertEquals(function.getResultMetadata().getDataType(), DataType.STRING);
+
+ ValueBlock block = mock(ValueBlock.class);
+ when(block.getNumDocs()).thenReturn(1);
+ BlockValSet flag = mock(BlockValSet.class);
+ when(flag.getLongValuesSV()).thenReturn(new long[]{0L});
+ BlockValSet metrics = mock(BlockValSet.class);
+ when(metrics.getStringValuesSV()).thenReturn(new String[]{DOCUMENT});
+ when(block.getBlockValueSet("flag")).thenReturn(flag);
+ when(block.getBlockValueSet("metrics")).thenReturn(metrics);
+ assertEquals(function.transformToStringValuesSV(block)[0], DOCUMENT);
+ }
+
+ private static DataSource dataSource(Class<? extends DataSource> type,
DataType dataType) {
+ DataSource dataSource = mock(type);
+ DataSourceMetadata metadata = mock(DataSourceMetadata.class);
+ when(metadata.getDataType()).thenReturn(dataType);
+ when(metadata.isSingleValue()).thenReturn(true);
+ when(dataSource.getDataSourceMetadata()).thenReturn(metadata);
+ return dataSource;
+ }
+}
diff --git
a/pinot-core/src/test/java/org/apache/pinot/core/operator/transform/function/ItemTransformFunctionScalarTypeTest.java
b/pinot-core/src/test/java/org/apache/pinot/core/operator/transform/function/ItemTransformFunctionScalarTypeTest.java
index bee5eea42fa..d52bd747416 100644
---
a/pinot-core/src/test/java/org/apache/pinot/core/operator/transform/function/ItemTransformFunctionScalarTypeTest.java
+++
b/pinot-core/src/test/java/org/apache/pinot/core/operator/transform/function/ItemTransformFunctionScalarTypeTest.java
@@ -19,19 +19,25 @@
package org.apache.pinot.core.operator.transform.function;
import java.math.BigDecimal;
+import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import org.apache.pinot.core.common.BlockValSet;
import org.apache.pinot.core.operator.ColumnContext;
import org.apache.pinot.core.operator.blocks.ProjectionBlock;
import org.apache.pinot.core.operator.blocks.ValueBlock;
+import org.apache.pinot.core.query.request.context.QueryContext;
import org.apache.pinot.segment.spi.datasource.DataSource;
import org.apache.pinot.segment.spi.datasource.DataSourceMetadata;
import org.apache.pinot.segment.spi.datasource.OpenStructDataSource;
import org.apache.pinot.segment.spi.index.reader.ForwardIndexReader;
+import org.apache.pinot.spi.data.ComplexFieldSpec;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.roaringbitmap.RoaringBitmap;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -102,6 +108,50 @@ public class ItemTransformFunctionScalarTypeTest {
return fn;
}
+ @Test
+ public void testPlannedLogicalTypeOverStringSegment() {
+ when(_keyMetadata.getDataType()).thenReturn(DataType.STRING);
+ when(_columnContext.getDataSource()).thenReturn(_openStructDataSource);
+ when(_perKeyBlockValSet.getValueType()).thenReturn(DataType.STRING);
+ when(_perKeyBlockValSet.isSingleValue()).thenReturn(true);
+ when(_projectionBlock.getNumDocs()).thenReturn(1);
+ LiteralTransformFunction target = mock(LiteralTransformFunction.class);
+ when(target.getStringLiteral()).thenReturn("BOOLEAN", "TIMESTAMP");
+
+ ItemTransformFunction flag = new ItemTransformFunction();
+ flag.init(List.of(_identifierArg, _literalArg, target), Map.of(COLUMN,
_columnContext));
+ when(_perKeyBlockValSet.getStringValuesSV()).thenReturn(new
String[]{"true"});
+ assertEquals(flag.transformToIntValuesSV(_projectionBlock), new int[]{1});
+
+ ItemTransformFunction timestamp = new ItemTransformFunction();
+ timestamp.init(List.of(_identifierArg, _literalArg, target),
Map.of(COLUMN, _columnContext));
+ String text = "2024-01-01 00:00:00";
+ when(_perKeyBlockValSet.getStringValuesSV()).thenReturn(new
String[]{text});
+ assertEquals(timestamp.transformToLongValuesSV(_projectionBlock), new
long[]{Timestamp.valueOf(text).getTime()});
+ }
+
+ @Test
+ public void testMissingKeyUsesPlannedFieldDefaultWithNullHandlingDisabled() {
+ when(_keyMetadata.getDataType()).thenReturn(DataType.STRING);
+ when(_columnContext.getDataSource()).thenReturn(_openStructDataSource);
+ when(_perKeyBlockValSet.getValueType()).thenReturn(DataType.STRING);
+ when(_perKeyBlockValSet.isSingleValue()).thenReturn(true);
+ when(_perKeyBlockValSet.getStringValuesSV()).thenReturn(new String[]{"17",
"null"});
+
when(_perKeyBlockValSet.getNullBitmap()).thenReturn(RoaringBitmap.bitmapOf(1));
+ when(_projectionBlock.getNumDocs()).thenReturn(2);
+ LiteralTransformFunction target = mock(LiteralTransformFunction.class);
+ when(target.getStringLiteral()).thenReturn("LONG_ARRAY");
+ Schema schema = new Schema();
+ schema.addField(new ComplexFieldSpec(COLUMN, DataType.OPEN_STRUCT, true,
+ Map.of(KEY, new DimensionFieldSpec(KEY, DataType.LONG, false, -7L))));
+ QueryContext queryContext = mock(QueryContext.class);
+ when(queryContext.getSchema()).thenReturn(schema);
+
+ ItemTransformFunction fn = new ItemTransformFunction();
+ fn.init(List.of(_identifierArg, _literalArg, target), Map.of(COLUMN,
_columnContext), queryContext);
+ assertEquals(fn.transformToLongValuesMV(_projectionBlock), new
long[][]{{17}, {-7}});
+ }
+
@Test
public void testBigDecimalValuesComeFromTheKeysOwnValueSet() {
BigDecimal[] values = {new BigDecimal("12.5"), new BigDecimal("-0.001")};
diff --git
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/OpenStructIngestionCommitTestBase.java
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/OpenStructIngestionCommitTestBase.java
index aae6cec3954..f06f74a0c23 100644
---
a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/OpenStructIngestionCommitTestBase.java
+++
b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/OpenStructIngestionCommitTestBase.java
@@ -141,8 +141,9 @@ public abstract class OpenStructIngestionCommitTestBase
extends CustomDataQueryC
public List<File> createAvroFiles()
throws Exception {
org.apache.avro.Schema avroSchema =
org.apache.avro.Schema.createRecord("OpenStructRecord", null, null, false);
- org.apache.avro.Schema mapSchema =
-
org.apache.avro.Schema.createMap(org.apache.avro.Schema.create(org.apache.avro.Schema.Type.STRING));
+ org.apache.avro.Schema mapSchema =
org.apache.avro.Schema.createMap(org.apache.avro.Schema.createUnion(
+ org.apache.avro.Schema.create(org.apache.avro.Schema.Type.STRING),
+ org.apache.avro.Schema.create(org.apache.avro.Schema.Type.INT)));
List<org.apache.avro.Schema.Field> fields = Arrays.asList(
new org.apache.avro.Schema.Field(METRICS, mapSchema, null, null),
new org.apache.avro.Schema.Field(TIMESTAMP_FIELD_NAME,
@@ -153,12 +154,14 @@ public abstract class OpenStructIngestionCommitTestBase
extends CustomDataQueryC
try (AvroFilesAndWriters avroFilesAndWriters =
createAvroFilesAndWriters(avroSchema)) {
List<DataFileWriter<GenericData.Record>> writers =
avroFilesAndWriters.getWriters();
for (int i = 0; i < NUM_DOCS; i++) {
- Map<String, String> metrics = new HashMap<>();
+ Map<String, Object> metrics = new HashMap<>();
metrics.put("views", String.valueOf(i)); // LONG, high
cardinality (dict + inverted)
metrics.put("cpu", String.valueOf(i * 0.5)); // DOUBLE (dict)
metrics.put("host", "host-" + (i % 5)); // STRING, small
set (raw forward)
metrics.put("region", "region-" + (i % 4)); // sparse
metrics.put("latencyMs", String.valueOf(i % 100)); // sparse
+ metrics.put("rank", i % 2 == 0 ? 2 : 10); // undeclared
INT, exposed as VARCHAR in MSE
+ metrics.put("", "empty key"); // a NULL
subscript must not read this key
metrics.put("debug", "noise-" + i); // ignoredKeys:
dropped at ingestion
GenericData.Record record = new GenericData.Record(avroSchema);
record.put(METRICS, metrics);
@@ -183,6 +186,88 @@ public abstract class OpenStructIngestionCommitTestBase
extends CustomDataQueryC
assertEquals(response.get("resultTable").get("rows").get(0).get(0).asLong(),
NUM_DOCS);
}
+ /// The multi-stage engine returns what the single-stage engine returns for
key reads on the OPEN_STRUCT column:
+ /// declared dense (`views`, `cpu`, `host`) and sparse (`region`,
`latencyMs`) keys in filters, aggregations,
+ /// group-by and order-by. Numbers are compared by value, since the engines
differ in aggregation result types
+ /// (e.g. SUM is DOUBLE in the single-stage engine).
+ @Test
+ public void testMultiStageMatchesSingleStage()
+ throws Exception {
+ String t = getTableName();
+ String m = METRICS;
+ List<String> queries = List.of(
+ "SELECT COUNT(*), SUM(" + m + "['views']) FROM " + t + " WHERE " + m +
"['views'] > 500",
+ "SELECT COUNT(*) FROM " + t + " WHERE " + m + "['latencyMs'] >= 50",
+ "SELECT COUNT(*) FROM " + t + " WHERE " + m + "['region'] = 'region-0'
AND " + m + "['views'] < 100",
+ "SELECT " + m + "['region'], COUNT(*), SUM(" + m + "['latencyMs'])
FROM " + t + " GROUP BY " + m
+ + "['region'] ORDER BY " + m + "['region']",
+ "SELECT " + m + "['host'], MAX(" + m + "['cpu']) FROM " + t + " GROUP
BY " + m + "['host'] ORDER BY " + m
+ + "['host']",
+ "SELECT " + m + "['views'], " + m + "['region'], " + m + "['cpu'] FROM
" + t + " ORDER BY " + m
+ + "['views'] DESC LIMIT 5");
+ boolean multiStage = useMultiStageQueryEngine();
+ try {
+ for (String query : queries) {
+ setUseMultiStageQueryEngine(false);
+ JsonNode singleStage = postQuery(query);
+ setUseMultiStageQueryEngine(true);
+ JsonNode multiStageResponse = postQuery(query);
+ assertEquals(singleStage.get("exceptions").size(), 0, query + " -> " +
singleStage);
+ assertEquals(multiStageResponse.get("exceptions").size(), 0, query + "
-> " + multiStageResponse);
+ assertSameRows(multiStageResponse.get("resultTable").get("rows"),
singleStage.get("resultTable").get("rows"),
+ query);
+ }
+ // Only the multi-stage engine joins: every row matches itself on the
unique `views` key.
+ JsonNode join = postQuery("SELECT COUNT(*) FROM " + t + " a JOIN " + t +
" b ON a." + m + "['views'] = b." + m
+ + "['views']");
+ assertEquals(join.get("exceptions").size(), 0, join.toString());
+ assertEquals(join.get("resultTable").get("rows").get(0).get(0).asLong(),
NUM_DOCS);
+ // The whole column is JSON text carrying the declared and sparse keys.
+ JsonNode whole = postQuery("SELECT " + m + " FROM " + t + " WHERE " + m
+ "['views'] = 7");
+ assertEquals(whole.get("exceptions").size(), 0, whole.toString());
+ JsonNode document =
JsonUtils.stringToJsonNode(whole.get("resultTable").get("rows").get(0).get(0).asText());
+ assertEquals(document.get("views").asLong(), 7);
+ assertEquals(document.get("region").asText(), "region-3");
+
+ String documentOrNull = "CASE WHEN " + m + "['views'] = 0 THEN " + m + "
ELSE NULL END";
+ JsonNode conditional = postQuery("SET enableNullHandling = true; SELECT
" + documentOrNull + ", COALESCE("
+ + documentOrNull + ", " + m + "), " + m + "[NULL] FROM " + t + "
ORDER BY " + TIMESTAMP_FIELD_NAME
+ + " LIMIT 2");
+ assertEquals(conditional.get("exceptions").size(), 0,
conditional.toString());
+ JsonNode rows = conditional.get("resultTable").get("rows");
+
assertEquals(JsonUtils.stringToJsonNode(rows.get(0).get(0).asText()).get("views").asInt(),
0);
+ assertTrue(rows.get(1).get(0).isNull());
+
assertEquals(JsonUtils.stringToJsonNode(rows.get(1).get(1).asText()).get("views").asInt(),
1);
+ assertTrue(rows.get(0).get(2).isNull());
+
+ // The segment stores rank numerically, but both the predicate and top-N
must use string ordering.
+ JsonNode filtered = postQuery("SELECT COUNT(*) FROM " + t + " WHERE " +
m + "['rank'] > '2'");
+ assertEquals(filtered.get("exceptions").size(), 0, filtered.toString());
+
assertEquals(filtered.get("resultTable").get("rows").get(0).get(0).asLong(),
0L);
+ JsonNode sorted = postQuery("SELECT " + m + "['rank'] FROM " + t + "
ORDER BY " + m + "['rank'] LIMIT 1");
+ assertEquals(sorted.get("exceptions").size(), 0, sorted.toString());
+
assertEquals(sorted.get("resultTable").get("rows").get(0).get(0).textValue(),
"10");
+ } finally {
+ setUseMultiStageQueryEngine(multiStage);
+ }
+ }
+
+ private static void assertSameRows(JsonNode actual, JsonNode expected,
String query) {
+ assertEquals(actual.size(), expected.size(), query);
+ for (int i = 0; i < expected.size(); i++) {
+ assertEquals(actual.get(i).size(), expected.get(i).size(), query);
+ for (int j = 0; j < expected.get(i).size(); j++) {
+ JsonNode a = actual.get(i).get(j);
+ JsonNode e = expected.get(i).get(j);
+ if (a.isNumber() && e.isNumber()) {
+ assertEquals(a.asDouble(), e.asDouble(), 1e-9, query + " row " + i);
+ } else {
+ assertEquals(a, e, query + " row " + i);
+ }
+ }
+ }
+ }
+
@Test
public void testSparseKeyGroupBy()
throws Exception {
diff --git
a/pinot-query-planner/src/main/java/org/apache/pinot/calcite/sql/fun/PinotItemOperator.java
b/pinot-query-planner/src/main/java/org/apache/pinot/calcite/sql/fun/PinotItemOperator.java
new file mode 100644
index 00000000000..e1b7f3afe12
--- /dev/null
+++
b/pinot-query-planner/src/main/java/org/apache/pinot/calcite/sql/fun/PinotItemOperator.java
@@ -0,0 +1,69 @@
+/**
+ * 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.calcite.sql.fun;
+
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rel.type.RelDataTypeFactory;
+import org.apache.calcite.sql.SqlCallBinding;
+import org.apache.calcite.sql.SqlOperatorBinding;
+import org.apache.calcite.sql.fun.SqlItemOperator;
+import org.apache.calcite.sql.fun.SqlStdOperatorTable;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.calcite.util.Static;
+import org.apache.pinot.query.type.OpenStructSqlType;
+
+
+/// The SQL `ITEM` operator (`x[i]`, `m['k']`), typed for OPEN_STRUCT columns.
+///
+/// Every operand type behaves as Calcite's standard ITEM. When the operand is
an [OpenStructSqlType] and the key is a
+/// literal, the result is the key's declared type, so `v['n'] > 50` and
`SUM(v['n'])` are numeric when `n` is
+/// declared numeric; an undeclared key is VARCHAR. Either way the result is
nullable, since any row may lack the key.
+/// The leaf resolves a column reference and a literal key once per segment.
The planner rejects computed operands
+/// that cannot be evaluated this way. Stateless and thread-safe.
+public class PinotItemOperator extends SqlItemOperator {
+ public static final PinotItemOperator INSTANCE = new
PinotItemOperator((SqlItemOperator) SqlStdOperatorTable.ITEM);
+
+ private PinotItemOperator(SqlItemOperator standard) {
+ super(standard.getName(), standard.getOperandTypeChecker(),
standard.offset, standard.safe);
+ }
+
+ @Override
+ public boolean checkOperandTypes(SqlCallBinding callBinding, boolean
throwOnFailure) {
+ if (callBinding.getOperandType(0) instanceof OpenStructSqlType &&
!callBinding.isOperandLiteral(1, false)) {
+ if (throwOnFailure) {
+ throw
callBinding.getValidator().newValidationError(callBinding.operand(1),
+ Static.RESOURCE.argumentMustBeLiteral(getName()));
+ }
+ return false;
+ }
+ return super.checkOperandTypes(callBinding, throwOnFailure);
+ }
+
+ @Override
+ public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
+ if (opBinding.getOperandType(0) instanceof OpenStructSqlType openStruct) {
+ RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
+ String key = opBinding.isOperandLiteral(1, false) ?
opBinding.getOperandLiteralValue(1, String.class) : null;
+ RelDataType declared = key == null ? null :
openStruct.getDeclaredKeyType(key);
+ RelDataType type = declared != null ? declared :
typeFactory.createSqlType(SqlTypeName.VARCHAR);
+ return typeFactory.createTypeWithNullability(type, true);
+ }
+ return super.inferReturnType(opBinding);
+ }
+}
diff --git
a/pinot-query-planner/src/main/java/org/apache/pinot/calcite/sql/fun/PinotOperatorTable.java
b/pinot-query-planner/src/main/java/org/apache/pinot/calcite/sql/fun/PinotOperatorTable.java
index e28995fc7df..6e61be04bad 100644
---
a/pinot-query-planner/src/main/java/org/apache/pinot/calcite/sql/fun/PinotOperatorTable.java
+++
b/pinot-query-planner/src/main/java/org/apache/pinot/calcite/sql/fun/PinotOperatorTable.java
@@ -302,7 +302,8 @@ public class PinotOperatorTable implements SqlOperatorTable
{
SqlStdOperatorTable.TIMESTAMP_DIFF,
SqlStdOperatorTable.CAST,
SqlStdOperatorTable.EXTRACT,
- SqlStdOperatorTable.ITEM,
+ // ITEM typed for OPEN_STRUCT columns; standard ITEM otherwise
+ PinotItemOperator.INSTANCE,
SqlStdOperatorTable.ARRAY_VALUE_CONSTRUCTOR,
SqlStdOperatorTable.LISTAGG
);
diff --git
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/RelToPlanNodeConverter.java
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/RelToPlanNodeConverter.java
index 0f5fa245801..43f4c2d4dfa 100644
---
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/RelToPlanNodeConverter.java
+++
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/RelToPlanNodeConverter.java
@@ -86,6 +86,7 @@ import org.apache.pinot.query.planner.plannode.TableScanNode;
import org.apache.pinot.query.planner.plannode.UnnestNode;
import org.apache.pinot.query.planner.plannode.ValueNode;
import org.apache.pinot.query.planner.plannode.WindowNode;
+import org.apache.pinot.query.type.OpenStructSqlType;
import org.apache.pinot.spi.utils.CommonConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -1054,6 +1055,10 @@ public final class RelToPlanNodeConverter {
}
public static ColumnDataType convertToColumnDataType(RelDataType
relDataType) {
+ if (relDataType instanceof OpenStructSqlType) {
+ // The leaf returns an OPEN_STRUCT column as JSON text, as the
single-stage engine does
+ return ColumnDataType.JSON;
+ }
SqlTypeName sqlTypeName = relDataType.getSqlTypeName();
if (sqlTypeName == SqlTypeName.NULL) {
return ColumnDataType.UNKNOWN;
diff --git
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/RexExpressionUtils.java
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/RexExpressionUtils.java
index 69d0f626a0f..ce59915eefc 100644
---
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/RexExpressionUtils.java
+++
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/RexExpressionUtils.java
@@ -62,6 +62,7 @@ import org.apache.pinot.common.function.FunctionRegistry;
import org.apache.pinot.common.function.TransformFunctionType;
import org.apache.pinot.common.function.scalar.arithmetic.NegateScalarFunction;
import org.apache.pinot.common.utils.DataSchema.ColumnDataType;
+import org.apache.pinot.query.type.OpenStructSqlType;
import org.apache.pinot.spi.utils.BooleanUtils;
import org.apache.pinot.spi.utils.ByteArray;
import org.apache.pinot.spi.utils.UuidUtils;
@@ -121,6 +122,10 @@ public class RexExpressionUtils {
return builder.getRexBuilder().makeCast(type, operand);
}
+ // The third ITEM operand is the leaf's planned output type. SQL ITEM
itself takes two operands.
+ if (operator.kind == SqlKind.ITEM && operands.size() == 3) {
+ return builder.call(operator, operands.subList(0, 2));
+ }
return builder.call(operator, operands);
}
@@ -317,6 +322,22 @@ public class RexExpressionUtils {
return handleSearch(rexCall.operands.get(0),
((PinotSealedSearchOperator) rexCall.op).getSargLiteral());
}
switch (rexCall.op.kind) {
+ case ITEM: {
+ ColumnDataType resultType =
RelToPlanNodeConverter.convertToColumnDataType(rexCall.type);
+ RexNode column = rexCall.operands.get(0);
+ if (!(column.getType() instanceof OpenStructSqlType)) {
+ return new RexExpression.FunctionCall(resultType,
SqlKind.ITEM.name(), fromRexNodes(rexCall.operands));
+ }
+ RexNode key = rexCall.operands.get(1);
+ if (RexLiteral.isNullLiteral(key)) {
+ return new RexExpression.Literal(resultType, null);
+ }
+ Preconditions.checkArgument(column instanceof RexInputRef,
+ "OPEN_STRUCT key lookup requires a column reference");
+ // A segment may have inferred a different type or shape. Carry the
planned type into pushed-down expressions.
+ return new RexExpression.FunctionCall(resultType, SqlKind.ITEM.name(),
List.of(fromRexNode(column),
+ fromRexNode(key), new RexExpression.Literal(ColumnDataType.STRING,
resultType.name())));
+ }
case CAST:
return handleCast(rexCall);
case REINTERPRET:
diff --git
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/physical/v2/PRelToPlanNodeConverter.java
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/physical/v2/PRelToPlanNodeConverter.java
index cc9d4416593..049255e1c5c 100644
---
a/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/physical/v2/PRelToPlanNodeConverter.java
+++
b/pinot-query-planner/src/main/java/org/apache/pinot/query/planner/physical/v2/PRelToPlanNodeConverter.java
@@ -65,6 +65,7 @@ import org.apache.pinot.query.planner.plannode.SortNode;
import org.apache.pinot.query.planner.plannode.TableScanNode;
import org.apache.pinot.query.planner.plannode.ValueNode;
import org.apache.pinot.query.planner.plannode.WindowNode;
+import org.apache.pinot.query.type.OpenStructSqlType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -293,6 +294,10 @@ public class PRelToPlanNodeConverter {
}
public static ColumnDataType convertToColumnDataType(RelDataType
relDataType) {
+ if (relDataType instanceof OpenStructSqlType) {
+ // The leaf returns an OPEN_STRUCT column as JSON text, as the
single-stage engine does
+ return ColumnDataType.JSON;
+ }
SqlTypeName sqlTypeName = relDataType.getSqlTypeName();
if (sqlTypeName == SqlTypeName.NULL) {
return ColumnDataType.UNKNOWN;
diff --git
a/pinot-query-planner/src/main/java/org/apache/pinot/query/type/OpenStructSqlType.java
b/pinot-query-planner/src/main/java/org/apache/pinot/query/type/OpenStructSqlType.java
new file mode 100644
index 00000000000..5b4061fbfca
--- /dev/null
+++
b/pinot-query-planner/src/main/java/org/apache/pinot/query/type/OpenStructSqlType.java
@@ -0,0 +1,89 @@
+/**
+ * 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.query.type;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Objects;
+import java.util.TreeMap;
+import javax.annotation.Nullable;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.sql.type.MapSqlType;
+
+
+/// Calcite type of an OPEN_STRUCT column.
+///
+/// It is a `MAP<VARCHAR, VARCHAR>` so that `col['key']` validates as a map
lookup, and it carries the column's
+/// declared child field specs as Calcite types. The `ITEM` operator uses a
key's declared type or VARCHAR for an
+/// undeclared key. Selecting the whole column returns JSON text.
+///
+/// The declared types are part of the digest, so two OPEN_STRUCT columns with
different declarations are different
+/// types after canonicalization. Instances are immutable.
+public class OpenStructSqlType extends MapSqlType {
+ private final Map<String, RelDataType> _declaredKeyTypes;
+
+ public OpenStructSqlType(RelDataType keyType, RelDataType valueType, boolean
isNullable,
+ Map<String, RelDataType> declaredKeyTypes) {
+ super(keyType, valueType, isNullable);
+ _declaredKeyTypes = Collections.unmodifiableMap(new
TreeMap<>(declaredKeyTypes));
+ // MapSqlType computed the digest before the declared types were set;
include them now.
+ computeDigest();
+ }
+
+ /// Declared type of `key`, or null when the key is not declared.
+ @Nullable
+ public RelDataType getDeclaredKeyType(String key) {
+ return _declaredKeyTypes.get(key);
+ }
+
+ public Map<String, RelDataType> getDeclaredKeyTypes() {
+ return _declaredKeyTypes;
+ }
+
+ @Override
+ public boolean deepEquals(@Nullable Object obj) {
+ return obj instanceof OpenStructSqlType other && super.deepEquals(other)
+ && Objects.equals(_declaredKeyTypes, other._declaredKeyTypes);
+ }
+
+ @Override
+ public int deepHashCode() {
+ return 31 * super.deepHashCode() + Objects.hashCode(_declaredKeyTypes);
+ }
+
+ @Override
+ protected void generateTypeString(StringBuilder sb, boolean withDetail) {
+ sb.append("OPEN_STRUCT");
+ // Null while the super constructor computes its first digest.
+ if (_declaredKeyTypes != null && !_declaredKeyTypes.isEmpty()) {
+ sb.append('(');
+ boolean first = true;
+ for (Map.Entry<String, RelDataType> entry :
_declaredKeyTypes.entrySet()) {
+ if (!first) {
+ sb.append(", ");
+ }
+ first = false;
+ // A key can contain a type name, a separator, or a quote.
+ sb.append('"').append(entry.getKey().replace("\"", "\"\"")).append("\"
")
+ .append(withDetail ? entry.getValue().getFullTypeString() :
entry.getValue().toString());
+ }
+ sb.append(')');
+ }
+ }
+}
diff --git
a/pinot-query-planner/src/main/java/org/apache/pinot/query/type/TypeFactory.java
b/pinot-query-planner/src/main/java/org/apache/pinot/query/type/TypeFactory.java
index 3f04dce7283..c546da48218 100644
---
a/pinot-query-planner/src/main/java/org/apache/pinot/query/type/TypeFactory.java
+++
b/pinot-query-planner/src/main/java/org/apache/pinot/query/type/TypeFactory.java
@@ -20,11 +20,18 @@ package org.apache.pinot.query.type;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.function.Predicate;
+import javax.annotation.Nullable;
import org.apache.calcite.jdbc.JavaTypeFactoryImpl;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.calcite.sql.type.SqlTypeUtil;
import org.apache.pinot.spi.data.ComplexFieldSpec;
import org.apache.pinot.spi.data.FieldSpec;
import org.apache.pinot.spi.data.Schema;
@@ -39,6 +46,9 @@ import org.apache.pinot.spi.data.Schema;
/// Noted that [JavaTypeFactoryImpl] is subject to change. Please pay extra
attention to this class when
/// upgrading Calcite versions.
public class TypeFactory extends JavaTypeFactoryImpl {
+ /// Child types an OPEN_STRUCT key read cannot carry as a Calcite type; such
a key reads as JSON text.
+ private static final Set<FieldSpec.DataType> COMPLEX_TYPES =
EnumSet.of(FieldSpec.DataType.MAP,
+ FieldSpec.DataType.LIST, FieldSpec.DataType.STRUCT,
FieldSpec.DataType.OPEN_STRUCT);
public static final TypeFactory INSTANCE = new TypeFactory();
@@ -70,7 +80,9 @@ public class TypeFactory extends JavaTypeFactoryImpl {
private RelDataType toRelDataType(FieldSpec fieldSpec, boolean
enableNullHandling) {
SqlTypeName sqlTypeName = getSqlTypeName(fieldSpec);
RelDataType type;
- if (sqlTypeName == SqlTypeName.MAP) {
+ if (fieldSpec.getDataType() == FieldSpec.DataType.OPEN_STRUCT) {
+ type = createOpenStructType((ComplexFieldSpec) fieldSpec,
enableNullHandling);
+ } else if (sqlTypeName == SqlTypeName.MAP) {
ComplexFieldSpec.MapFieldSpec mapFieldSpec =
ComplexFieldSpec.toMapFieldSpec((ComplexFieldSpec) fieldSpec);
type =
createMapType(createSqlType(getSqlTypeName(mapFieldSpec.getKeyFieldSpec())),
createSqlType(getSqlTypeName(mapFieldSpec.getValueFieldSpec())));
@@ -83,6 +95,78 @@ public class TypeFactory extends JavaTypeFactoryImpl {
return enableNullHandling && fieldSpec.isNullable() ?
createTypeWithNullability(type, true) : type;
}
+ /// `MAP<VARCHAR, VARCHAR>` carrying the declared child types; see
[OpenStructSqlType]. A declared key is always
+ /// nullable when null handling is on, since any row may lack it. A complex
child (MAP, LIST, STRUCT, OPEN_STRUCT)
+ /// is VARCHAR: the single-stage engine reads it as JSON text.
+ private RelDataType createOpenStructType(ComplexFieldSpec fieldSpec, boolean
enableNullHandling) {
+ Map<String, RelDataType> declaredKeyTypes = new HashMap<>();
+ for (Map.Entry<String, FieldSpec> child :
fieldSpec.getChildFieldSpecs().entrySet()) {
+ FieldSpec childSpec = child.getValue();
+ RelDataType childType;
+ if (COMPLEX_TYPES.contains(childSpec.getDataType())) {
+ childType = createSqlType(SqlTypeName.VARCHAR);
+ } else {
+ childType = createSqlType(getSqlTypeName(childSpec));
+ if (!childSpec.isSingleValueField()) {
+ childType = createArrayType(childType, -1);
+ }
+ }
+ declaredKeyTypes.put(child.getKey(),
createTypeWithNullability(childType, enableNullHandling));
+ }
+ RelDataType varchar = createSqlType(SqlTypeName.VARCHAR);
+ return canonize(new OpenStructSqlType(varchar, varchar, false,
declaredKeyTypes));
+ }
+
+ /// Keeps an [OpenStructSqlType] when its nullability changes; Calcite's
copy would degrade it to a plain map.
+ @Override
+ public RelDataType createTypeWithNullability(RelDataType type, boolean
nullable) {
+ if (type instanceof OpenStructSqlType openStruct) {
+ if (openStruct.isNullable() == nullable) {
+ return type;
+ }
+ return canonize(new OpenStructSqlType(openStruct.getKeyType(),
openStruct.getValueType(), nullable,
+ openStruct.getDeclaredKeyTypes()));
+ }
+ return super.createTypeWithNullability(type, nullable);
+ }
+
+ /// Keeps an [OpenStructSqlType] when every input is one (for example the
branches of a UNION ALL); Calcite's
+ /// version would return a plain map, which the plan converters do not map
to JSON. The result declares the keys
+ /// every input declares with the same type (nullable if any input's is),
and is nullable when any input is.
+ ///
+ /// A NULL input is not handled: Calcite casts it to the union type through
a type spec, which loses the subclass.
+ @Override
+ @Nullable
+ public RelDataType leastRestrictive(List<RelDataType> types) {
+ Map<String, RelDataType> declaredKeyTypes = null;
+ boolean nullable = false;
+ for (RelDataType type : types) {
+ if (!(type instanceof OpenStructSqlType openStruct)) {
+ return super.leastRestrictive(types);
+ }
+ nullable |= openStruct.isNullable();
+ if (declaredKeyTypes == null) {
+ declaredKeyTypes = new HashMap<>(openStruct.getDeclaredKeyTypes());
+ continue;
+ }
+ Iterator<Map.Entry<String, RelDataType>> iterator =
declaredKeyTypes.entrySet().iterator();
+ while (iterator.hasNext()) {
+ Map.Entry<String, RelDataType> entry = iterator.next();
+ RelDataType other = openStruct.getDeclaredKeyType(entry.getKey());
+ if (other == null || !SqlTypeUtil.equalSansNullability(this,
entry.getValue(), other)) {
+ iterator.remove();
+ } else if (other.isNullable()) {
+ entry.setValue(createTypeWithNullability(entry.getValue(), true));
+ }
+ }
+ }
+ if (declaredKeyTypes == null) {
+ return super.leastRestrictive(types);
+ }
+ RelDataType varchar = createSqlType(SqlTypeName.VARCHAR);
+ return canonize(new OpenStructSqlType(varchar, varchar, nullable,
declaredKeyTypes));
+ }
+
private static SqlTypeName getSqlTypeName(FieldSpec fieldSpec) {
switch (fieldSpec.getDataType()) {
case INT:
@@ -100,6 +184,9 @@ public class TypeFactory extends JavaTypeFactoryImpl {
case STRING:
case JSON:
return SqlTypeName.VARCHAR;
+ // See OpenStructSqlType. Without a mapping, building the row type fails
for every query on the table.
+ case OPEN_STRUCT:
+ return SqlTypeName.MAP;
case UUID:
return SqlTypeName.UUID;
case BYTES:
diff --git
a/pinot-query-planner/src/test/java/org/apache/pinot/query/OpenStructMultiStagePlanningTest.java
b/pinot-query-planner/src/test/java/org/apache/pinot/query/OpenStructMultiStagePlanningTest.java
new file mode 100644
index 00000000000..f088cebcf60
--- /dev/null
+++
b/pinot-query-planner/src/test/java/org/apache/pinot/query/OpenStructMultiStagePlanningTest.java
@@ -0,0 +1,257 @@
+/**
+ * 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.query;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.common.utils.DataSchema.ColumnDataType;
+import org.apache.pinot.query.planner.logical.RexExpression;
+import org.apache.pinot.query.planner.physical.DispatchablePlanFragment;
+import org.apache.pinot.query.planner.physical.DispatchableSubPlan;
+import org.apache.pinot.query.planner.plannode.FilterNode;
+import org.apache.pinot.query.planner.plannode.PlanNode;
+import org.apache.pinot.query.planner.plannode.ProjectNode;
+import org.apache.pinot.query.type.OpenStructSqlType;
+import org.apache.pinot.spi.data.ComplexFieldSpec;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.data.Schema;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.expectThrows;
+
+
+/// OPEN_STRUCT columns in the multi-stage engine: a key read (`v['n']`) is
typed by the key's declared child field
+/// spec and falls back to VARCHAR for an undeclared key, matching what the
leaf stage returns for it; selecting the
+/// whole column is JSON text, as in the single-stage engine; and queries that
never touch the column still plan.
+public class OpenStructMultiStagePlanningTest extends QueryEnvironmentTestBase
{
+ private QueryEnvironment _env;
+
+ @BeforeClass
+ public void setUpOpenStructTable() {
+ Map<String, Schema> schemas = new HashMap<>(TABLE_SCHEMAS);
+ Schema schema = getSchemaBuilder("d").build();
+ Map<String, FieldSpec> declared = Map.of("n", new DimensionFieldSpec("n",
DataType.LONG, true),
+ "price", new DimensionFieldSpec("price", DataType.DOUBLE, true),
+ "inner", new ComplexFieldSpec("inner", DataType.OPEN_STRUCT, true,
Map.of()));
+ schema.addField(new ComplexFieldSpec("v", DataType.OPEN_STRUCT, true,
declared));
+ schemas.put("d", schema);
+ // Same column, declaring `n` with the same type and `price` with another.
+ Schema other = getSchemaBuilder("d2").build();
+ other.addField(new ComplexFieldSpec("v", DataType.OPEN_STRUCT, true,
+ Map.of("n", new DimensionFieldSpec("n", DataType.LONG, true),
+ "price", new DimensionFieldSpec("price", DataType.STRING, true))));
+ schemas.put("d2", other);
+ _env = getQueryEnvironment(3, 1, 2, schemas, SERVER1_SEGMENTS,
SERVER2_SEGMENTS, PARTITIONED_SEGMENTS_MAP);
+ }
+
+ private RelDataType validatedRowType(String sql) {
+ try (QueryEnvironment.CompiledQuery query = _env.compile(sql)) {
+ return query.getRelRoot().validatedRowType;
+ }
+ }
+
+ private DispatchableSubPlan planQuery(String sql) {
+ try (QueryEnvironment.CompiledQuery query = _env.compile(sql)) {
+ return query.planQuery(0).getQueryPlan();
+ }
+ }
+
+ @Test
+ public void testDeclaredKeyIsTypedByItsChildFieldSpec() {
+ RelDataType rowType = validatedRowType("SELECT v['n'], v['price'] FROM d");
+ assertEquals(rowType.getFieldList().get(0).getType().getSqlTypeName(),
SqlTypeName.BIGINT);
+ assertEquals(rowType.getFieldList().get(1).getType().getSqlTypeName(),
SqlTypeName.DOUBLE);
+ assertTrue(rowType.getFieldList().get(0).getType().isNullable());
+ }
+
+ @Test
+ public void testUndeclaredKeyAndNestedPathAreVarchar() {
+ RelDataType rowType = validatedRowType("SELECT v['name'], v['o.z'] FROM
d");
+ assertEquals(rowType.getFieldList().get(0).getType().getSqlTypeName(),
SqlTypeName.VARCHAR);
+ assertEquals(rowType.getFieldList().get(1).getType().getSqlTypeName(),
SqlTypeName.VARCHAR);
+ }
+
+ @Test
+ public void testNumericFilterAndAggregationOnDeclaredKeyPlan() {
+ RelDataType rowType = validatedRowType("SELECT SUM(v['n']), COUNT(*) FROM
d WHERE v['n'] > 50");
+ assertEquals(rowType.getFieldList().get(0).getType().getSqlTypeName(),
SqlTypeName.BIGINT);
+ assertNotNull(planQuery("SELECT SUM(v['n']), COUNT(*) FROM d WHERE v['n']
> 50"));
+ assertNotNull(planQuery("SELECT CAST(v['name'] AS BIGINT) FROM d"));
+ }
+
+ @Test
+ public void testWholeColumnIsJsonText() {
+ DispatchableSubPlan plan = planQuery("SELECT col1, v FROM d");
+ DataSchema schema =
plan.getQueryStageMap().get(0).getPlanFragment().getFragmentRoot().getDataSchema();
+ assertEquals(schema.getColumnDataTypes()[1], ColumnDataType.JSON);
+ }
+
+ @Test
+ public void testComplexDeclaredChildIsVarchar() {
+ RelDataType rowType = validatedRowType("SELECT v['inner'] FROM d");
+ assertEquals(rowType.getFieldList().get(0).getType().getSqlTypeName(),
SqlTypeName.VARCHAR);
+ }
+
+ /// A UNION ALL of two OPEN_STRUCT columns stays OPEN_STRUCT: the whole
column is still JSON, and a key both sides
+ /// declare with the same type keeps it while a key they declare differently
is VARCHAR.
+ @Test
+ public void testUnionAllKeepsOpenStruct() {
+ DispatchableSubPlan plan = planQuery("SELECT v FROM d UNION ALL SELECT v
FROM d WHERE col3 > 0");
+ DataSchema schema =
plan.getQueryStageMap().get(0).getPlanFragment().getFragmentRoot().getDataSchema();
+ assertEquals(schema.getColumnDataTypes()[0], ColumnDataType.JSON);
+ // d2 has no segments, so only validate across the two declarations.
+ String union = "(SELECT v FROM d UNION ALL SELECT v FROM d2)";
+ assertTrue(validatedRowType("SELECT v FROM " +
union).getFieldList().get(0).getType()
+ instanceof OpenStructSqlType);
+ RelDataType rowType = validatedRowType("SELECT u.v['n'], u.v['price'] FROM
" + union + " AS u");
+ assertEquals(rowType.getFieldList().get(0).getType().getSqlTypeName(),
SqlTypeName.BIGINT);
+ assertEquals(rowType.getFieldList().get(1).getType().getSqlTypeName(),
SqlTypeName.VARCHAR);
+ }
+
+ @Test
+ public void testCaseAndCoalesceWithNullKeepJson() {
+ for (String sql : List.of("SELECT CASE WHEN col3 > 0 THEN v ELSE NULL END
FROM d",
+ "SELECT COALESCE(v, NULL) FROM d")) {
+ DataSchema schema =
+
planQuery(sql).getQueryStageMap().get(0).getPlanFragment().getFragmentRoot().getDataSchema();
+ assertEquals(schema.getColumnDataTypes()[0], ColumnDataType.JSON, sql);
+ }
+ }
+
+ @Test
+ public void testNonLiteralKeyIsRejected() {
+ Exception e = expectThrows(Exception.class, () -> planQuery("SELECT
v[col1] FROM d"));
+ assertTrue(e.getMessage().contains("must be a literal"), e.getMessage());
+ }
+
+ @Test
+ public void testComputedOpenStructKeyLookupIsRejectedDuringPlanning() {
+ String computed = "CASE WHEN col3 > 0 THEN v ELSE NULL END";
+ for (String sql : List.of("SELECT (" + computed + ")['n'] FROM d",
+ "SELECT x['n'] FROM (SELECT " + computed + " AS x FROM d)")) {
+ Exception e = expectThrows(Exception.class, () -> planQuery(sql));
+ assertTrue(e.getMessage().contains("OPEN_STRUCT key lookup requires a
column reference"), e.getMessage());
+ }
+ }
+
+ /// The leaf receives the planned key type, so it can convert a segment
value stored as another type (for example an
+ /// undeclared INT key that the plan types VARCHAR) before a pushed-down
comparison or sort. The type is the same
+ /// for a declared key, whose matching segments keep their index.
+ @Test
+ public void testPushedKeyReadCarriesThePlannedType() {
+ assertEquals(plannedKeyTypes("SELECT col1 FROM d WHERE v['k'] > '2'"),
List.of("STRING"));
+ assertEquals(plannedKeyTypes("SELECT v['k'] FROM d ORDER BY v['k'] LIMIT
1"), List.of("STRING"));
+ assertEquals(plannedKeyTypes("SELECT col1 FROM d WHERE v['n'] > 2"),
List.of("LONG"));
+ }
+
+ private List<String> plannedKeyTypes(String sql) {
+ List<RexExpression> expressions = new ArrayList<>();
+ for (DispatchablePlanFragment fragment :
planQuery(sql).getQueryStageMap().values()) {
+ if (fragment.getTableName() != null) {
+ collectExpressions(fragment.getPlanFragment().getFragmentRoot(),
expressions);
+ }
+ }
+ List<String> types = new ArrayList<>();
+ expressions.forEach(expression -> collectItemTypes(expression, types));
+ return types.stream().distinct().toList();
+ }
+
+ private static void collectExpressions(PlanNode node, List<RexExpression>
expressions) {
+ if (node instanceof FilterNode filter) {
+ expressions.add(filter.getCondition());
+ } else if (node instanceof ProjectNode project) {
+ expressions.addAll(project.getProjects());
+ }
+ for (PlanNode input : node.getInputs()) {
+ collectExpressions(input, expressions);
+ }
+ }
+
+ private static void collectItemTypes(RexExpression expression, List<String>
types) {
+ if (expression instanceof RexExpression.FunctionCall call) {
+ List<RexExpression> operands = call.getFunctionOperands();
+ if (call.getFunctionName().equals("ITEM")) {
+ assertEquals(operands.size(), 3, "OPEN_STRUCT key lookup must carry
its planned type");
+ types.add(String.valueOf(((RexExpression.Literal)
operands.get(2)).getValue()));
+ }
+ operands.forEach(operand -> collectItemTypes(operand, types));
+ }
+ }
+
+ /// The multi-stage engine casts an undeclared VARCHAR key when comparing it
to a numeric literal.
+ @Test
+ public void testUndeclaredKeyComparedToNumberIsCast() {
+ String sql = "EXPLAIN PLAN FOR SELECT COUNT(*) FROM d WHERE v['x'] > 5";
+ try (QueryEnvironment.CompiledQuery query = _env.compile(sql)) {
+ String plan = query.explain(0, null).getExplainPlan();
+ assertTrue(plan.contains("CAST(ITEM("), plan);
+ }
+ }
+
+ /// The physical optimizer converts the table scan's row type through its
own converter; the column is JSON there
+ /// too, and key reads are typed as with the default planner.
+ @Test
+ public void testPhysicalOptimizerPlansTheColumnAsJson() {
+ String options = "SET usePhysicalOptimizer=true; ";
+ DataSchema schema = planQuery(options + "SELECT col1, v FROM
d").getQueryStageMap().get(0).getPlanFragment()
+ .getFragmentRoot().getDataSchema();
+ assertEquals(schema.getColumnDataTypes()[1], ColumnDataType.JSON);
+ for (String sql : List.of("SELECT SUM(v['n']), COUNT(*) FROM d WHERE
v['n'] > 50", "SELECT v['name'] FROM d",
+ "SELECT v['n'], COUNT(*) FROM d GROUP BY v['n']")) {
+ assertNotNull(planQuery(options + sql), sql);
+ }
+ }
+
+ /// `ITEM` on an array (a multi-value column) keeps its standard typing and
one-based indexing; only an OPEN_STRUCT
+ /// operand takes the declared-key typing.
+ @Test
+ public void testItemOnNonOpenStructOperandsIsUnchanged() {
+ RelDataType rowType = validatedRowType("SELECT mcol1[1], mcol2[1] FROM e");
+ assertEquals(rowType.getFieldList().get(0).getType().getSqlTypeName(),
SqlTypeName.VARCHAR);
+ assertEquals(rowType.getFieldList().get(1).getType().getSqlTypeName(),
SqlTypeName.BIGINT);
+ assertNotNull(planQuery("SELECT mcol1[1], mcol2[1] FROM e WHERE mcol2[1] >
5"));
+ }
+
+ /// A key is looked up in the operand's own declared keys, so the same key
name on another OPEN_STRUCT column with a
+ /// different declaration is typed by that column's declaration.
+ @Test
+ public void testDeclaredKeyTypeFollowsTheColumnItIsReadFrom() {
+ RelDataType rowType = validatedRowType("SELECT x.v['price'], u.v['price']
FROM d AS x CROSS JOIN d2 AS u LIMIT 1");
+ assertEquals(rowType.getFieldList().get(0).getType().getSqlTypeName(),
SqlTypeName.DOUBLE);
+ assertEquals(rowType.getFieldList().get(1).getType().getSqlTypeName(),
SqlTypeName.VARCHAR);
+ }
+
+ @Test
+ public void testQueriesThatDoNotReadTheColumnPlan() {
+ for (String sql : List.of("SELECT COUNT(*) FROM d", "SELECT SUM(col3) FROM
d", "SELECT * FROM d LIMIT 1")) {
+ assertNotNull(planQuery(sql), sql);
+ }
+ }
+}
diff --git
a/pinot-query-planner/src/test/java/org/apache/pinot/query/type/TypeFactoryTest.java
b/pinot-query-planner/src/test/java/org/apache/pinot/query/type/TypeFactoryTest.java
index 52a44627bd7..5acec68a05e 100644
---
a/pinot-query-planner/src/test/java/org/apache/pinot/query/type/TypeFactoryTest.java
+++
b/pinot-query-planner/src/test/java/org/apache/pinot/query/type/TypeFactoryTest.java
@@ -23,6 +23,7 @@ import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
import org.apache.calcite.adapter.java.JavaTypeFactory;
import org.apache.calcite.jdbc.JavaTypeFactoryImpl;
import org.apache.calcite.rel.type.RelDataType;
@@ -31,6 +32,8 @@ import org.apache.calcite.sql.SqlCollation;
import org.apache.calcite.sql.type.ArraySqlType;
import org.apache.calcite.sql.type.BasicSqlType;
import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.pinot.spi.data.ComplexFieldSpec;
+import org.apache.pinot.spi.data.DimensionFieldSpec;
import org.apache.pinot.spi.data.FieldSpec;
import org.apache.pinot.spi.data.Schema;
import org.testng.Assert;
@@ -132,6 +135,150 @@ public class TypeFactoryTest {
return cases.iterator();
}
+ /// A table with an OPEN_STRUCT column must stay plannable: the multi-stage
engine converts every column into the
+ /// row type, so an unmapped type used to fail every query on the table,
even `COUNT(*)`. The column maps to an
+ /// [OpenStructSqlType] (a `MAP<VARCHAR, VARCHAR>`) carrying the declared
child types.
+ @Test(dataProvider = "nullHandlingModes")
+ public void testOpenStructColumnMapsToOpenStructSqlType(boolean
columnNullMode) {
+ TypeFactory typeFactory = new TypeFactory();
+ Schema testSchema = new Schema.SchemaBuilder()
+ .addSingleValueDimension("id", FieldSpec.DataType.LONG)
+ .setEnableColumnBasedNullHandling(columnNullMode)
+ .build();
+ ComplexFieldSpec openStruct = new ComplexFieldSpec("event",
FieldSpec.DataType.OPEN_STRUCT, true,
+ Map.of("n", new DimensionFieldSpec("n", FieldSpec.DataType.LONG,
true)));
+ testSchema.addField(openStruct);
+
+ RelDataType rowType = typeFactory.createRelDataTypeFromSchema(testSchema);
+
+ Assert.assertEquals(rowType.getField("id", true,
false).getType().getSqlTypeName(), SqlTypeName.BIGINT);
+ RelDataType eventType = rowType.getField("event", true, false).getType();
+ Assert.assertTrue(eventType instanceof OpenStructSqlType,
eventType.getFullTypeString());
+ OpenStructSqlType open = (OpenStructSqlType) eventType;
+ Assert.assertEquals(open.getSqlTypeName(), SqlTypeName.MAP);
+ Assert.assertEquals(open.getKeyType().getSqlTypeName(),
SqlTypeName.VARCHAR);
+ Assert.assertEquals(open.getValueType().getSqlTypeName(),
SqlTypeName.VARCHAR);
+ Assert.assertEquals(open.isNullable(), columnNullMode &&
openStruct.isNullable());
+ Assert.assertEquals(open.getDeclaredKeyType("n").getSqlTypeName(),
SqlTypeName.BIGINT);
+ Assert.assertNull(open.getDeclaredKeyType("other"));
+ // A nullability change keeps the declared types, and different
declarations stay distinct types.
+ RelDataType flipped = typeFactory.createTypeWithNullability(open,
!open.isNullable());
+ Assert.assertTrue(flipped instanceof OpenStructSqlType);
+ Assert.assertEquals(((OpenStructSqlType)
flipped).getDeclaredKeyType("n").getSqlTypeName(), SqlTypeName.BIGINT);
+ Schema undeclared = new
Schema.SchemaBuilder().setEnableColumnBasedNullHandling(columnNullMode).build();
+ undeclared.addField(new ComplexFieldSpec("event",
FieldSpec.DataType.OPEN_STRUCT, true, Map.of()));
+
Assert.assertNotEquals(typeFactory.createRelDataTypeFromSchema(undeclared).getField("event",
true, false).getType(),
+ eventType);
+ }
+
+ @Test
+ public void testOpenStructKeysCannotCollideInTypeCache() {
+ String combinedKey = "a INTEGER, b";
+ Schema schema = new
Schema.SchemaBuilder().setEnableColumnBasedNullHandling(true)
+ .addOpenStruct("split", Map.of("a", new DimensionFieldSpec("a",
FieldSpec.DataType.INT, true),
+ "b", new DimensionFieldSpec("b", FieldSpec.DataType.LONG, true)))
+ .addOpenStruct("combined", Map.of(combinedKey, new
DimensionFieldSpec(combinedKey, FieldSpec.DataType.LONG,
+ true)))
+ .build();
+ RelDataType row = new TypeFactory().createRelDataTypeFromSchema(schema);
+ OpenStructSqlType split = (OpenStructSqlType) row.getField("split", true,
false).getType();
+ OpenStructSqlType combined = (OpenStructSqlType) row.getField("combined",
true, false).getType();
+ Assert.assertNotEquals(split.getFullTypeString(),
combined.getFullTypeString());
+ Assert.assertFalse(split.deepEquals(combined));
+ Assert.assertEquals(split.getDeclaredKeyType("a").getSqlTypeName(),
SqlTypeName.INTEGER);
+
Assert.assertEquals(combined.getDeclaredKeyType(combinedKey).getSqlTypeName(),
SqlTypeName.BIGINT);
+ }
+
+ /// Child specs map by shape: a multi-value child is an array of its type,
and a complex child (a nested OPEN_STRUCT,
+ /// MAP or LIST) has no Calcite counterpart as a key read, so it is VARCHAR,
the JSON text the leaf returns.
+ /// With null handling on, every declared key is nullable since any row may
lack it.
+ @Test(dataProvider = "nullHandlingModes")
+ public void testOpenStructChildTypesFollowTheirShape(boolean columnNullMode)
{
+ TypeFactory typeFactory = new TypeFactory();
+ Map<String, FieldSpec> children = Map.of(
+ "tags", new DimensionFieldSpec("tags", FieldSpec.DataType.STRING,
false),
+ "n", new DimensionFieldSpec("n", FieldSpec.DataType.LONG, true),
+ "inner", new ComplexFieldSpec("inner", FieldSpec.DataType.OPEN_STRUCT,
true, Map.of()),
+ "m", new ComplexFieldSpec("m", FieldSpec.DataType.MAP, true, Map.of()),
+ "l", new ComplexFieldSpec("l", FieldSpec.DataType.LIST, true,
Map.of()));
+ Schema schema = new
Schema.SchemaBuilder().setEnableColumnBasedNullHandling(columnNullMode).build();
+ schema.addField(new ComplexFieldSpec("event",
FieldSpec.DataType.OPEN_STRUCT, true, children));
+
+ OpenStructSqlType open = (OpenStructSqlType)
typeFactory.createRelDataTypeFromSchema(schema)
+ .getField("event", true, false).getType();
+
+ Assert.assertEquals(open.getDeclaredKeyType("tags").getSqlTypeName(),
SqlTypeName.ARRAY);
+
Assert.assertEquals(open.getDeclaredKeyType("tags").getComponentType().getSqlTypeName(),
SqlTypeName.VARCHAR);
+ Assert.assertEquals(open.getDeclaredKeyType("n").getSqlTypeName(),
SqlTypeName.BIGINT);
+ for (String complex : List.of("inner", "m", "l")) {
+ Assert.assertEquals(open.getDeclaredKeyType(complex).getSqlTypeName(),
SqlTypeName.VARCHAR, complex);
+ }
+ for (String key : children.keySet()) {
+ Assert.assertEquals(open.getDeclaredKeyType(key).isNullable(),
columnNullMode, key);
+ }
+ }
+
+ /// `createTypeWithNullability` returns the same instance when nothing
changes, and the canonical instance of the new
+ /// nullability otherwise, so equal declarations stay one type and keep
their declared keys.
+ @Test
+ public void testOpenStructNullabilityChangeIsCanonical() {
+ TypeFactory typeFactory = new TypeFactory();
+ RelDataType varchar = typeFactory.createSqlType(SqlTypeName.VARCHAR);
+ OpenStructSqlType open =
+ new OpenStructSqlType(varchar, varchar, false, Map.of("n",
typeFactory.createSqlType(SqlTypeName.BIGINT)));
+ Assert.assertSame(typeFactory.createTypeWithNullability(open, false),
open);
+ RelDataType nullable = typeFactory.createTypeWithNullability(open, true);
+ Assert.assertTrue(nullable instanceof OpenStructSqlType);
+ Assert.assertTrue(nullable.isNullable());
+ Assert.assertSame(typeFactory.createTypeWithNullability(nullable, true),
nullable);
+ Assert.assertSame(typeFactory.createTypeWithNullability(nullable, true),
+ typeFactory.createTypeWithNullability(open, true));
+ Assert.assertEquals(typeFactory.createTypeWithNullability(nullable,
false), open);
+ }
+
+ /// `leastRestrictive` only keeps the OPEN_STRUCT type when every input is
one; any other mix, and a single input,
+ /// are Calcite's.
+ @Test
+ public void testLeastRestrictiveFallsBackToCalciteForOtherMixes() {
+ TypeFactory typeFactory = new TypeFactory();
+ RelDataType varchar = typeFactory.createSqlType(SqlTypeName.VARCHAR);
+ RelDataType bigint = typeFactory.createSqlType(SqlTypeName.BIGINT);
+ OpenStructSqlType open = new OpenStructSqlType(varchar, varchar, false,
Map.of("n", bigint));
+
+ Assert.assertEquals(typeFactory.leastRestrictive(List.of(bigint, bigint)),
bigint);
+ Assert.assertFalse(typeFactory.leastRestrictive(List.of(bigint, open))
instanceof OpenStructSqlType);
+ Assert.assertFalse(typeFactory.leastRestrictive(List.of(open, bigint))
instanceof OpenStructSqlType);
+ Assert.assertTrue(typeFactory.leastRestrictive(List.of(open)) instanceof
OpenStructSqlType);
+ }
+
+ /// A key two declarations agree on keeps its type even when only one side
is nullable; a key they type
+ /// differently, or that only one declares, is dropped (reads as VARCHAR).
+ @Test
+ public void testLeastRestrictiveOfOpenStructTypesKeepsAgreedKeys() {
+ TypeFactory typeFactory = new TypeFactory();
+ RelDataType varchar = typeFactory.createSqlType(SqlTypeName.VARCHAR);
+ RelDataType bigint = typeFactory.createSqlType(SqlTypeName.BIGINT);
+ OpenStructSqlType left = new OpenStructSqlType(varchar, varchar, false,
+ Map.of("n", bigint, "p",
typeFactory.createSqlType(SqlTypeName.DOUBLE), "only", bigint));
+ OpenStructSqlType right = new OpenStructSqlType(varchar, varchar, true,
+ Map.of("n", typeFactory.createTypeWithNullability(bigint, true), "p",
varchar));
+
+ RelDataType merged = typeFactory.leastRestrictive(List.of(left, right));
+
+ Assert.assertTrue(merged instanceof OpenStructSqlType,
String.valueOf(merged));
+ OpenStructSqlType open = (OpenStructSqlType) merged;
+ Assert.assertTrue(open.isNullable());
+ Assert.assertEquals(open.getDeclaredKeyType("n").getSqlTypeName(),
SqlTypeName.BIGINT);
+ Assert.assertTrue(open.getDeclaredKeyType("n").isNullable());
+ Assert.assertNull(open.getDeclaredKeyType("p"));
+ Assert.assertNull(open.getDeclaredKeyType("only"));
+ }
+
+ @DataProvider(name = "nullHandlingModes")
+ public Object[][] nullHandlingModes() {
+ return new Object[][]{{true}, {false}};
+ }
+
@Test(dataProvider = "relDataTypeConversion")
public void testScalarTypes(FieldSpec.DataType dataType, RelDataType
scalarType, boolean columnNullMode) {
TypeFactory typeFactory = new TypeFactory();
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]