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 9cb4ef81ddb OPEN_STRUCT sparse keys: resolve dotted paths, read typed 
keys as the dense tier does (#20300)
9cb4ef81ddb is described below

commit 9cb4ef81ddbebb38e293d6ddabdbc6042c080877
Author: RAGHVENDRA KUMAR YADAV <[email protected]>
AuthorDate: Fri Nov 20 20:18:53 2026 -0800

    OPEN_STRUCT sparse keys: resolve dotted paths, read typed keys as the dense 
tier does (#20300)
    
    * Resolve dotted OPEN_STRUCT keys through nested objects in the sparse blob
    
    A key read from the sparse blob was a literal top-level lookup, so 
col['o.z']
    returned null for {"o": {"z": 2}} unless the column had been flattened at
    ingest. Columns backed by an external source (for example a Parquet VARIANT)
    are never flattened, so a nested field was silently null on every row.
    
    - OpenStructSparseBlobReader walks a dotted key through nested objects when 
the
      document has no literal key of that name, with OpenStructKeyFlattener's 
rules:
      a literal key wins at every level, colliding synthesized paths resolve in
      document order, arrays are not indexed into, and a missing, null or scalar
      intermediate is absent. Presence and filters use the same lookup.
    - ImmutableOpenStructDataSource no longer treats a dotted key as 
definitively
      absent when the sparse manifest lists a key it is a path under (o.z under 
o);
      the manifest names document keys, never the nested paths below them.
    
    Mutable (consuming) segments keep a column per key and are unchanged: nested
    keys there are reachable when flattening is enabled.
    
    * Read declared OPEN_STRUCT sparse keys strictly; match the flattener on 
empty segments
    
    - A sparse key declared numeric or boolean read its JSON value with 
Jackson's
      lenient asInt/asLong/asDouble, so text read as 0, 1.5 in a LONG key as 1 
and
      an object as 0, while the null vector still marked the row present. Those
      invented values were counted by SUM and matched filters. Single-value 
reads
      now accept only values that fit the declared type (integral numbers that 
fit,
      whole floating values, numeric text, booleans for BOOLEAN); anything else
      reads as absent and the null vector agrees.
    - resolve() allows empty key segments, as OpenStructKeyFlattener emits them
      (o. for {"o":{"":1}}), and a test checks it against the flattener as an
      oracle across literal, collision, empty-segment, array and null cases.
    - Drop the manifest-prefix routing: segments with a sparse manifest store an
      unflattened nested object as JSON text, which the walk does not parse, so 
it
      added a scan without changing results.
    
    * Accept the value forms the materialized tier accepts for declared sparse 
keys
    
    BOOLEAN accepts 0/1 and their text forms, TIMESTAMP parses timestamp text,
    BIG_DECIMAL trims. Multi-value elements stay lenient (documented).
    
    * Read sparse keys with the dense tier's conversion
    
    A declared or manifest-typed sparse key now converts each value with the
    PinotDataType of its stored type, as OpenStructColumnSplitter does at build,
    so a key reads the same whichever tier holds it: 1.5 in a LONG key reads 1,
    2 in a BOOLEAN key reads 2, timestamp text in a TIMESTAMP key is absent. A
    value the conversion rejects is absent, as the build drops it. Multi-value
    keys follow the same rule: absent when any element is rejected.
    
    OpenStructSparseDenseParityTest checks an external blob of raw values 
against
    the dense columns built from the same values, for every scalar type.
    
    * Document the stored-type contract of the sparse key getters
    
    * Test the multi-value getters of a sparse OPEN_STRUCT key
    
    Cover every multi-value getter and its buffer variant: numeric elements
    converted as the dense tier converts them, BIG_DECIMAL, STRING (nested 
elements
    as JSON) and BYTES (malformed and non-binary elements read as the default),
    absent documents, scalars stored before the key became multi-value, and a 
null
    element making the value absent.
    
    * Keep sparse OPEN_STRUCT reads and filters consistent across tiers
    
    * Test sparse OPEN_STRUCT reads for exact big decimals and empty lists
    
    Regression cases for review findings: an integer beyond the long range 
stays exact for a BIG_DECIMAL key, and an empty array on a multi-value key 
reads as absent.
    
    * Consolidate sparse decimal and empty-list regression coverage
    
    ---------
    
    Co-authored-by: Xiang Fu <[email protected]>
---
 .../core/operator/filter/MapFilterOperator.java    |   2 +-
 .../filter/MapFilterOperatorOpenStructTest.java    |  45 +++
 .../openstruct/ImmutableOpenStructDataSource.java  |  51 ++-
 .../openstruct/OpenStructSparseBlobReader.java     |  95 +++++-
 .../index/openstruct/SparseKeyDataSource.java      | 357 ++++++++++++++-------
 .../ImmutableOpenStructDataSourceTest.java         |  27 ++
 .../openstruct/OpenStructSparseBlobReaderTest.java |  90 ++++++
 .../OpenStructSparseDenseParityTest.java           |  72 +++++
 .../index/openstruct/SparseKeyDataSourceTest.java  | 218 ++++++++++++-
 .../spi/datasource/OpenStructDataSource.java       |  18 ++
 10 files changed, 834 insertions(+), 141 deletions(-)

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 3900a3be3c1..636bf442a9b 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
@@ -163,7 +163,7 @@ public class MapFilterOperator extends BaseFilterOperator {
   @Nullable
   private BaseFilterOperator trySparseJsonIndex(OpenStructDataSource osDs, 
DataSource sparseKeyDs,
       QueryContext queryContext, int numDocs) {
-    JsonIndexReader jsonIndex = osDs.getSparseJsonIndex();
+    JsonIndexReader jsonIndex = osDs.getSparseJsonIndex(_keyName);
     if (jsonIndex == null || !servesKey(jsonIndex)) {
       return null;
     }
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 d818936b836..27c17091bfc 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
@@ -42,6 +42,7 @@ import 
org.apache.pinot.core.operator.transform.function.ItemTransformFunction;
 import org.apache.pinot.core.query.request.context.QueryContext;
 import org.apache.pinot.segment.local.segment.index.datasource.NullDataSource;
 import 
org.apache.pinot.segment.local.segment.index.openstruct.FakeStringForwardIndex;
+import 
org.apache.pinot.segment.local.segment.index.openstruct.ImmutableOpenStructDataSource;
 import 
org.apache.pinot.segment.local.segment.index.openstruct.OpenStructSparseBlobReader;
 import 
org.apache.pinot.segment.local.segment.index.openstruct.SparseKeyDataSource;
 import org.apache.pinot.segment.spi.Constants;
@@ -65,6 +66,7 @@ import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.Mockito.*;
 import static org.testng.Assert.assertEquals;
 import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNull;
 import static org.testng.Assert.assertTrue;
 
 
@@ -604,6 +606,8 @@ public class MapFilterOperatorOpenStructTest {
   private static OpenStructDataSource withSparseJsonIndex(OpenStructDataSource 
osDs,
       JsonIndexReader jsonIndex) {
     when(osDs.getSparseJsonIndex()).thenReturn(jsonIndex);
+    when(osDs.getSparseJsonIndex(anyString())).thenCallRealMethod();
+    when(osDs.hasUnambiguousSparseJsonPath(anyString())).thenCallRealMethod();
     return osDs;
   }
 
@@ -625,6 +629,47 @@ public class MapFilterOperatorOpenStructTest {
     assertEquals(countMatches(op), 2);
   }
 
+  @Test
+  public void testSparseJsonIndexScansAmbiguousKeys() {
+    String[] blobs = new String[NUM_DOCS];
+    blobs[0] = "{\"a.b\":{\"c\":\"first\"},\"a\":{\"b.c\":\"second\"},"
+        + "\"x[0]\":\"first\",\"$x\":\"first\",\"x[\":\"first\"}";
+    JsonIndexReader jsonIndex = mock(JsonIndexReader.class);
+    when(jsonIndex.isPathIndexed(anyString())).thenReturn(true);
+    // The JSON index retains the second value where the OPEN_STRUCT reader 
resolves the first.
+    when(jsonIndex.getMatchingDocIds(any(FilterContext.class))).thenReturn(new 
MutableRoaringBitmap());
+    OpenStructDataSource osDs = 
withSparseJsonIndex(mockSparseSegmentSource(null, Map.of(), blobs), jsonIndex);
+
+    for (String key : List.of("a.b.c", "x[0]", "$x", "x[")) {
+      MapFilterOperator op = new MapFilterOperator(mockSegment(osDs),
+          makeEqPredicate(COLUMN, key, "first"), mockQueryContext(), NUM_DOCS);
+      assertEquals(collect(op.getTrues()), List.of(0), key);
+    }
+    verify(jsonIndex, never()).getMatchingDocIds(any(FilterContext.class));
+  }
+
+  @Test
+  public void testSparseJsonIndexUsesNativeDottedString() {
+    String[] blobs = 
{"{\"device\":\"{}\",\"device.os\":\"linux\",\"tags\":[\"a\",\"b\"],\"tags.$index\":\"custom\"}"};
+    JsonIndexReader jsonIndex = mock(JsonIndexReader.class);
+    when(jsonIndex.isPathIndexed("$.device.os")).thenReturn(true);
+    
when(jsonIndex.getMatchingDocIds(any(FilterContext.class))).thenReturn(MutableRoaringBitmap.bitmapOf(0));
+    DataSource sparse = mock(DataSource.class);
+    doReturn(new FakeStringForwardIndex(blobs)).when(sparse).getForwardIndex();
+    when(sparse.getJsonIndex()).thenReturn(jsonIndex);
+    Map<String, DataType> types = Map.of("device", DataType.STRING, 
"device.os", DataType.STRING,
+        "tags", DataType.STRING, "tags.$index", DataType.STRING);
+    OpenStructDataSource osDs = new ImmutableOpenStructDataSource(
+        new ComplexFieldSpec(COLUMN, DataType.OPEN_STRUCT, true, Map.of()), 
Map.of(), sparse, blobs.length,
+        List.copyOf(types.keySet()), Map.of("tags", 2), types);
+
+    MapFilterOperator op = new MapFilterOperator(mockSegment(osDs),
+        makeEqPredicate(COLUMN, "device.os", "linux"), mockQueryContext(), 
blobs.length);
+    assertTrue(op.toExplainString().contains("delegateTo:json_match"));
+    assertEquals(collect(op.getTrues()), List.of(0));
+    assertNull(osDs.getSparseJsonIndex("tags.$index"), "the array index and 
the literal key share a posting key");
+  }
+
   @Test
   public void testSparseJsonIndexNotEqComplementsPostings() {
     JsonIndexReader jsonIndex = mock(JsonIndexReader.class);
diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/openstruct/ImmutableOpenStructDataSource.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/openstruct/ImmutableOpenStructDataSource.java
index 7bd3274325b..f37ea1bae61 100644
--- 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/openstruct/ImmutableOpenStructDataSource.java
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/openstruct/ImmutableOpenStructDataSource.java
@@ -43,6 +43,8 @@ import 
org.apache.pinot.segment.spi.partition.PartitionFunction;
 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.OpenStructKeyFlattener;
 import org.apache.pinot.spi.utils.JsonUtils;
 
 
@@ -63,7 +65,6 @@ public class ImmutableOpenStructDataSource extends 
BaseDataSource implements Ope
   /// Sparse keys whose values are collections, mapped to the longest value 
each one holds. Read from the parent
   /// column's metadata, where the segment build records it for exactly the 
keys whose shape is not visible in a
   /// column of their own.
-  @Nullable
   private final Map<String, Integer> _sparseMultiValueKeys;
   /// Sparse keys mapped to the type the segment build resolved for them, read 
from the parent column's metadata
   /// for the same reason as the shape above: the blob is JSON and carries no 
type of its own.
@@ -83,7 +84,7 @@ public class ImmutableOpenStructDataSource extends 
BaseDataSource implements Ope
     _perKeyDataSources = perKeyDataSources;
     _sparseDataSource = sparseDataSource;
     _sparseKeys = sparseKeys != null ? Set.copyOf(sparseKeys) : null;
-    _sparseMultiValueKeys = sparseMultiValueKeys != null ? 
Map.copyOf(sparseMultiValueKeys) : null;
+    _sparseMultiValueKeys = sparseMultiValueKeys != null ? 
Map.copyOf(sparseMultiValueKeys) : Map.of();
     _sparseKeyTypes = sparseKeyTypes != null ? Map.copyOf(sparseKeyTypes) : 
null;
     if (sparseDataSource != null) {
       ForwardIndexReader<?> blobFwd = sparseDataSource.getForwardIndex();
@@ -128,8 +129,8 @@ public class ImmutableOpenStructDataSource extends 
BaseDataSource implements Ope
       // Definitively absent: no sparse blob, or the sparse manifest does not 
list the key
       return new NullDataSource(getValueFieldSpec(key), 
getDataSourceMetadata().getNumDocs());
     }
-    return _sparseKeyDataSourceCache.computeIfAbsent(key,
-        k -> new SparseKeyDataSource(getValueFieldSpec(k), _sparseBlobReader, 
maxNumValues(k)));
+    return _sparseKeyDataSourceCache.computeIfAbsent(key, k -> new 
SparseKeyDataSource(getValueFieldSpec(k),
+        _sparseBlobReader, _sparseMultiValueKeys.getOrDefault(k, 
SparseKeyDataSource.UNKNOWN_MAX_NUM_VALUES)));
   }
 
   /// Field spec for a key's values, with an undeclared sparse key's shape and 
type taken from the segment's
@@ -146,24 +147,13 @@ public class ImmutableOpenStructDataSource extends 
BaseDataSource implements Ope
     if (childFieldSpec != null) {
       return childFieldSpec;
     }
-    boolean singleValue = _sparseMultiValueKeys == null || 
!_sparseMultiValueKeys.containsKey(key);
+    boolean singleValue = !_sparseMultiValueKeys.containsKey(key);
     FieldSpec.DataType dataType = _sparseKeyTypes != null
         ? _sparseKeyTypes.getOrDefault(key, FieldSpec.DataType.STRING)
         : FieldSpec.DataType.STRING;
     return new DimensionFieldSpec(key, dataType, singleValue);
   }
 
-  /// Longest value a multi-value sparse key holds, which is what the readers 
over it size their buffers from.
-  /// Zero for a single-value key, as 
[DataSourceMetadata#getMaxNumValuesPerMVEntry()] reports for one.
-  private int maxNumValues(String key) {
-    FieldSpec valueFieldSpec = getValueFieldSpec(key);
-    if (valueFieldSpec.isSingleValueField()) {
-      return 0;
-    }
-    // A declared multi-value key has no manifest entry when every one of its 
values was a scalar.
-    return _sparseMultiValueKeys != null ? 
_sparseMultiValueKeys.getOrDefault(key, 1) : 1;
-  }
-
   @Override
   public boolean isMaterialized(String key) {
     return _perKeyDataSources.containsKey(key);
@@ -193,6 +183,35 @@ public class ImmutableOpenStructDataSource extends 
BaseDataSource implements Ope
     return ds instanceof ImmutableDataSource immutableDs ? 
immutableDs.getIndexContainer() : null;
   }
 
+  @Override
+  public boolean hasUnambiguousSparseJsonPath(String key) {
+    int dot = key.indexOf(OpenStructKeyFlattener.PATH_SEPARATOR);
+    if (dot < 0) {
+      return true;
+    }
+    // The native build writes each manifest key as a literal field. Only a 
physical scalar STRING is indexed
+    // as its projected text.
+    if (_sparseKeys == null || !_sparseKeys.contains(key) || _sparseKeyTypes 
== null
+        || _sparseKeyTypes.get(key) != DataType.STRING
+        || _sparseMultiValueKeys.containsKey(key)) {
+      return false;
+    }
+    // The JSON index merges nested paths with literal dotted fields. A prefix 
absent from the blob or stored
+    // as a scalar (including a flattened container serialized as STRING) 
cannot contribute a competing path.
+    for (; dot >= 0; dot = key.indexOf(OpenStructKeyFlattener.PATH_SEPARATOR, 
dot + 1)) {
+      String prefix = key.substring(0, dot);
+      if (!_sparseKeys.contains(prefix)) {
+        continue;
+      }
+      DataType type = _sparseKeyTypes.get(prefix);
+      if (type == null || (!type.isNumeric() && type != DataType.STRING && 
type != DataType.BYTES)
+          || _sparseMultiValueKeys.containsKey(prefix)) {
+        return false;
+      }
+    }
+    return true;
+  }
+
   @Override
   @Nullable
   public JsonIndexReader getSparseJsonIndex() {
diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/openstruct/OpenStructSparseBlobReader.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/openstruct/OpenStructSparseBlobReader.java
index 2a5f62fa67c..ba3c49cf9e3 100644
--- 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/openstruct/OpenStructSparseBlobReader.java
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/openstruct/OpenStructSparseBlobReader.java
@@ -18,12 +18,22 @@
  */
 package org.apache.pinot.segment.local.segment.index.openstruct;
 
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.util.JsonParserDelegate;
 import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectReader;
+import com.fasterxml.jackson.databind.cfg.JsonNodeFeature;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.util.Map;
+import java.util.function.Predicate;
 import javax.annotation.Nullable;
 import org.apache.pinot.segment.spi.index.reader.ForwardIndexReader;
 import org.apache.pinot.segment.spi.index.reader.ForwardIndexReaderContext;
 import org.apache.pinot.segment.spi.index.reader.NullValueVectorReader;
+import org.apache.pinot.spi.data.OpenStructKeyFlattener;
 import org.apache.pinot.spi.utils.JsonUtils;
+import org.apache.pinot.spi.utils.PinotDataType;
 import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
 import org.roaringbitmap.buffer.MutableRoaringBitmap;
 
@@ -32,6 +42,9 @@ import org.roaringbitmap.buffer.MutableRoaringBitmap;
 /// stateless and segment-shared; each caller needs its own 
[ForwardIndexReaderContext].
 /// FastJsonPathExtractor is the planned follow-up for making repeated key 
reads cheap.
 public class OpenStructSparseBlobReader {
+  private static final ObjectReader NUMERIC_READER =
+      
JsonUtils.DEFAULT_READER.without(JsonNodeFeature.STRIP_TRAILING_BIGDECIMAL_ZEROES);
+
   private final ForwardIndexReader<ForwardIndexReaderContext> _blobReader;
   @Nullable
   private final NullValueVectorReader _blobNulls;
@@ -56,14 +69,52 @@ public class OpenStructSparseBlobReader {
 
   @Nullable
   public JsonNode getValue(int docId, String key, @Nullable 
ForwardIndexReaderContext context) {
+    return getValue(docId, key, context, null);
+  }
+
+  @Nullable
+  JsonNode getValue(int docId, String key, @Nullable ForwardIndexReaderContext 
context,
+      @Nullable PinotDataType converter) {
     // TODO: an N-key projection parses each doc N times. 
FastJsonPathExtractor fixes this in one pass,
     // but only across a batch of paths — this single-key signature has to 
change first.
-    JsonNode blob = parseBlob(docId, context);
-    return blob == null ? null : blob.get(key);
+    JsonNode blob = parseBlob(docId, context, converter);
+    return blob == null ? null : resolve(blob, key);
   }
 
+  /// Resolves `key` against one document the way [OpenStructKeyFlattener] 
would have keyed
+  /// it at ingest, so `col['o.z']` reads `{"o": {"z": 2}}` from a blob that 
holds the nested object:
+  /// - a key the object carries literally wins at every level (`.` is an 
ordinary key character);
+  /// - otherwise the key is walked through nested objects, taking the first 
match in document order when two
+  ///   synthesized paths collide, as the flattener's first emission does;
+  /// - arrays are never indexed into, and a missing, null or scalar 
intermediate is absent;
+  /// - empty key segments are allowed, as the flattener emits them (`{"o": 
{"": 1}}` keys `o.` to `1`);
+  /// - unlike a flattened column, the walk has no depth limit. Native 
segments store a nested object that was not
+  ///   flattened as JSON text, which this does not parse, and a segment with 
a sparse-key manifest only serves the
+  ///   keys it lists, so the walk serves blobs written without flattening: a 
segment with no manifest, such as one
+  ///   produced outside the standard build. A miss costs a scan of each 
level's field names per document.
   @Nullable
-  private JsonNode parseBlob(int docId, @Nullable ForwardIndexReaderContext 
context) {
+  static JsonNode resolve(JsonNode node, String key) {
+    JsonNode literal = node.get(key);
+    if (literal != null || key.indexOf(OpenStructKeyFlattener.PATH_SEPARATOR) 
< 0 || !node.isObject()) {
+      return literal;
+    }
+    for (Map.Entry<String, JsonNode> field : node.properties()) {
+      String name = field.getKey();
+      JsonNode child = field.getValue();
+      if (child.isObject() && key.length() > name.length() && 
key.startsWith(name)
+          && key.charAt(name.length()) == 
OpenStructKeyFlattener.PATH_SEPARATOR) {
+        JsonNode found = resolve(child, key.substring(name.length() + 1));
+        if (found != null) {
+          return found;
+        }
+      }
+    }
+    return null;
+  }
+
+  @Nullable
+  private JsonNode parseBlob(int docId, @Nullable ForwardIndexReaderContext 
context,
+      @Nullable PinotDataType converter) {
     if (_blobNulls != null && _blobNulls.isNull(docId)) {
       return null;
     }
@@ -72,21 +123,55 @@ public class OpenStructSparseBlobReader {
       return null;
     }
     try {
+      if (converter == PinotDataType.INT || converter == PinotDataType.LONG || 
converter == PinotDataType.FLOAT
+          || converter == PinotDataType.BIG_DECIMAL) {
+        return readNumericBlob(json, converter == PinotDataType.BIG_DECIMAL);
+      }
       return JsonUtils.stringToJsonNode(json);
     } catch (Exception e) {
       throw new IllegalStateException("Failed to parse OPEN_STRUCT sparse blob 
at doc " + docId, e);
     }
   }
 
+  /// JSON does not distinguish a producer's double from its decimal. Preserve 
the double conversion when its
+  /// printed value round-trips, including signed zero and overflow 
saturation. Otherwise let PinotDataType narrow
+  /// the exact decimal to INT, LONG or FLOAT, without first rounding away 
digits through a double.
+  private static JsonNode readNumericBlob(String json, boolean requireDecimal)
+      throws IOException {
+    try (JsonParser parser = new 
JsonParserDelegate(JsonUtils.DEFAULT_READER.createParser(json)) {
+      @Override
+      public NumberTypeFP getNumberTypeFP()
+          throws IOException {
+        double value = getDoubleValue();
+        try {
+          BigDecimal exact = getDecimalValue();
+          if (requireDecimal || !Double.isFinite(value) || 
BigDecimal.valueOf(value).compareTo(exact) != 0) {
+            return NumberTypeFP.BIG_DECIMAL;
+          }
+        } catch (NumberFormatException e) {
+          // A JSON exponent can exceed BigDecimal's scale range. Keep the 
rest of the document readable.
+        }
+        return NumberTypeFP.DOUBLE64;
+      }
+    }) {
+      return NUMERIC_READER.readTree(parser);
+    }
+  }
+
   /// Full scan for docs where `key` is present (explicit JSON null = absent). 
Callers memoize.
   public ImmutableRoaringBitmap computePresence(String key) {
+    return computePresence(key, null, node -> true);
+  }
+
+  /// Full scan for docs where `key` holds a non-null value that `accept` 
takes. Callers memoize.
+  ImmutableRoaringBitmap computePresence(String key, @Nullable PinotDataType 
converter, Predicate<JsonNode> accept) {
     // TODO: the opt-in sparse JSON index already encodes this; deriving 
presence from it needs a
     // handle on the index, which only ImmutableOpenStructDataSource has.
     MutableRoaringBitmap present = new MutableRoaringBitmap();
     try (ForwardIndexReaderContext context = createBlobContext()) {
       for (int docId = 0; docId < _numDocs; docId++) {
-        JsonNode val = getValue(docId, key, context);
-        if (val != null && !val.isNull()) {
+        JsonNode val = getValue(docId, key, context, converter);
+        if (val != null && !val.isNull() && accept.test(val)) {
           present.add(docId);
         }
       }
diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/openstruct/SparseKeyDataSource.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/openstruct/SparseKeyDataSource.java
index ddabb103660..b3d78d3ad45 100644
--- 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/openstruct/SparseKeyDataSource.java
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/openstruct/SparseKeyDataSource.java
@@ -24,7 +24,9 @@ import java.math.BigDecimal;
 import java.util.Map;
 import java.util.Set;
 import java.util.function.Function;
+import java.util.function.IntFunction;
 import javax.annotation.Nullable;
+import org.apache.pinot.common.utils.DataSchema.ColumnDataType;
 import org.apache.pinot.segment.local.segment.index.datasource.BaseDataSource;
 import org.apache.pinot.segment.spi.Constants;
 import org.apache.pinot.segment.spi.datasource.DataSourceMetadata;
@@ -36,6 +38,7 @@ import 
org.apache.pinot.segment.spi.index.reader.NullValueVectorReader;
 import org.apache.pinot.segment.spi.partition.PartitionFunction;
 import org.apache.pinot.spi.data.FieldSpec;
 import org.apache.pinot.spi.data.FieldSpec.DataType;
+import org.apache.pinot.spi.utils.PinotDataType;
 import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
 import org.roaringbitmap.buffer.MutableRoaringBitmap;
 
@@ -47,19 +50,31 @@ import org.roaringbitmap.buffer.MutableRoaringBitmap;
 /// Single- or multi-value follows `resolvedChildSpec`, which is what the key 
reads as on the dense side too:
 /// a declared child spec, or -- for an undeclared key -- the shape the 
segment recorded for it.
 /// `maxNumValuesPerMVEntry` is the longest value the key holds, the number 
callers size their multi-value
-/// buffers from; 0 for a single-value key.
+/// buffers from. A single-value key reports 0. Pass -1 for a multi-value key 
without recorded lengths to compute
+/// its maximum on the first call to 
[DataSourceMetadata#getMaxNumValuesPerMVEntry()].
+///
+/// A numeric, BOOLEAN or TIMESTAMP value uses the dense tier's build-time 
conversion
+/// ([PinotDataType] of the stored type in `OpenStructColumnSplitter`) on the 
raw JSON scalar.
+/// A value that conversion rejects -- text that is not a number, an object in 
a numeric key -- is dropped by the dense
+/// tier, so here it reads as absent (null, or the default with null handling 
off) and the null vector agrees. A
+/// multi-value key is absent when any element is rejected, as the dense tier 
drops the whole value. STRING, JSON and
+/// BYTES keys accept any non-null element.
 public class SparseKeyDataSource extends BaseDataSource {
+  static final int UNKNOWN_MAX_NUM_VALUES = -1;
   private final FieldSpec _fieldSpec;
 
   public SparseKeyDataSource(FieldSpec resolvedChildSpec, 
OpenStructSparseBlobReader blobReader,
       int maxNumValuesPerMVEntry) {
-    super(new SparseKeyMetadata(resolvedChildSpec, blobReader.getNumDocs(), 
maxNumValuesPerMVEntry),
-        new ColumnIndexContainer.FromMap(Map.of(
-            StandardIndexes.forward(),
-            new SparseKeyForwardIndexReader(resolvedChildSpec, blobReader),
-            StandardIndexes.nullValueVector(),
-            new LazyPresenceNullVector(resolvedChildSpec.getName(), 
blobReader))));
-    _fieldSpec = resolvedChildSpec;
+    this(resolvedChildSpec, blobReader, maxNumValuesPerMVEntry,
+        new SparseKeyForwardIndexReader(resolvedChildSpec, blobReader));
+  }
+
+  private SparseKeyDataSource(FieldSpec fieldSpec, OpenStructSparseBlobReader 
blobReader, int maxNumValuesPerMVEntry,
+      SparseKeyForwardIndexReader forwardReader) {
+    super(new SparseKeyMetadata(fieldSpec, blobReader.getNumDocs(), 
maxNumValuesPerMVEntry, forwardReader),
+        new ColumnIndexContainer.FromMap(Map.of(StandardIndexes.forward(), 
forwardReader,
+            StandardIndexes.nullValueVector(), new 
LazyPresenceNullVector(fieldSpec, blobReader))));
+    _fieldSpec = fieldSpec;
   }
 
   public FieldSpec getFieldSpec() {
@@ -67,6 +82,13 @@ public class SparseKeyDataSource extends BaseDataSource {
   }
 
   static class SparseKeyForwardIndexReader implements 
ForwardIndexReader<ForwardIndexReaderContext> {
+    private static final NumberWriter<int[]> INT_WRITER = (buffer, i, value) 
-> buffer[i] = value.intValue();
+    private static final NumberWriter<long[]> LONG_WRITER = (buffer, i, value) 
-> buffer[i] = value.longValue();
+    private static final NumberWriter<float[]> FLOAT_WRITER = (buffer, i, 
value) -> buffer[i] = value.floatValue();
+    private static final NumberWriter<double[]> DOUBLE_WRITER = (buffer, i, 
value) -> buffer[i] = value.doubleValue();
+    private static final NumberWriter<BigDecimal[]> BIG_DECIMAL_WRITER =
+        (buffer, i, value) -> buffer[i] = (BigDecimal) value;
+
     private final String _key;
     private final DataType _storedType;
     private final boolean _singleValue;
@@ -76,21 +98,25 @@ public class SparseKeyDataSource extends BaseDataSource {
     /// predicate names it -- so the two must agree, or a NOT_IN over a 
declared default can take the fast path and
     /// miss the documents that lack the key.
     private final Object _declaredDefault;
+    /// The dense tier's conversion for this key; null for a STRING, JSON or 
BYTES key, which reads any value.
+    @Nullable
+    private final PinotDataType _converter;
 
     SparseKeyForwardIndexReader(FieldSpec fieldSpec, 
OpenStructSparseBlobReader blob) {
-      this(fieldSpec.getName(), fieldSpec.getDataType().getStoredType(), 
fieldSpec.isSingleValueField(), blob,
+      this(fieldSpec.getName(), fieldSpec.getDataType(), 
fieldSpec.isSingleValueField(), blob,
           fieldSpec.getDefaultNullValue());
     }
 
-    SparseKeyForwardIndexReader(String key, DataType storedType, 
OpenStructSparseBlobReader blob) {
-      this(key, storedType, true, blob, null);
+    SparseKeyForwardIndexReader(String key, DataType dataType, 
OpenStructSparseBlobReader blob) {
+      this(key, dataType, true, blob, null);
     }
 
-    private SparseKeyForwardIndexReader(String key, DataType storedType, 
boolean singleValue,
+    private SparseKeyForwardIndexReader(String key, DataType dataType, boolean 
singleValue,
         OpenStructSparseBlobReader blob, @Nullable Object declaredDefault) {
       _declaredDefault = declaredDefault;
       _key = key;
-      _storedType = storedType;
+      _converter = converterFor(dataType);
+      _storedType = dataType.getStoredType();
       _singleValue = singleValue;
       _blob = blob;
     }
@@ -117,10 +143,19 @@ public class SparseKeyDataSource extends BaseDataSource {
 
     @Nullable
     private JsonNode valueNode(int docId, ForwardIndexReaderContext context) {
-      JsonNode node = _blob.getValue(docId, _key, context);
+      JsonNode node = _blob.getValue(docId, _key, context, _converter);
       return node == null || node.isNull() ? null : node;
     }
 
+    /// The single value converted to the key's stored type, or null when the 
document lacks the key or the dense
+    /// tier's conversion rejects the value. Callers read it through the 
getter of the key's stored type, as for any
+    /// forward index, so the numeric getters only see a converted number.
+    @Nullable
+    private Object converted(int docId, ForwardIndexReaderContext context) {
+      JsonNode node = valueNode(docId, context);
+      return node == null ? null : convert(_converter, node);
+    }
+
     private <T> T orDefault(int docId, ForwardIndexReaderContext context, 
Function<JsonNode, T> map, T defaultValue) {
       JsonNode node = valueNode(docId, context);
       return node == null ? defaultValue : map.apply(node);
@@ -135,32 +170,42 @@ public class SparseKeyDataSource extends BaseDataSource {
 
     @Override
     public int getInt(int docId, ForwardIndexReaderContext context) {
-      return orDefault(docId, context, JsonNode::asInt,
-          declaredOr(Integer.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_INT));
+      Object value = converted(docId, context);
+      return value != null
+          ? ((Number) value).intValue()
+          : declaredOr(Integer.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_INT);
     }
 
     @Override
     public long getLong(int docId, ForwardIndexReaderContext context) {
-      return orDefault(docId, context, JsonNode::asLong,
-          declaredOr(Long.class, (long) 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_LONG));
+      Object value = converted(docId, context);
+      return value != null
+          ? ((Number) value).longValue()
+          : declaredOr(Long.class, (long) 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_LONG);
     }
 
     @Override
     public float getFloat(int docId, ForwardIndexReaderContext context) {
-      return orDefault(docId, context, node -> (float) node.asDouble(),
-          declaredOr(Float.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_FLOAT));
+      Object value = converted(docId, context);
+      return value != null
+          ? ((Number) value).floatValue()
+          : declaredOr(Float.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_FLOAT);
     }
 
     @Override
     public double getDouble(int docId, ForwardIndexReaderContext context) {
-      return orDefault(docId, context, JsonNode::asDouble,
-          declaredOr(Double.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_DOUBLE));
+      Object value = converted(docId, context);
+      return value != null
+          ? ((Number) value).doubleValue()
+          : declaredOr(Double.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_DOUBLE);
     }
 
     @Override
     public BigDecimal getBigDecimal(int docId, ForwardIndexReaderContext 
context) {
-      return orDefault(docId, context, node -> new BigDecimal(node.asText()),
-          declaredOr(BigDecimal.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_BIG_DECIMAL));
+      Object value = converted(docId, context);
+      return value != null
+          ? (BigDecimal) value
+          : declaredOr(BigDecimal.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_BIG_DECIMAL);
     }
 
     @Override
@@ -188,145 +233,126 @@ public class SparseKeyDataSource extends BaseDataSource 
{
       }, absent);
     }
 
+    @FunctionalInterface
+    private interface NumberWriter<T> {
+      void set(T buffer, int index, Number value);
+    }
 
-    /// Value nodes of a multi-value key at one document: the elements of an 
array, or the value itself, so a
-    /// scalar stored on the key before it became multi-value reads back as 
the one-element value the dense side
-    /// stores for it. Null when the document does not have the key.
-    @Nullable
-    private JsonNode[] valueNodes(int docId, ForwardIndexReaderContext 
context) {
-      JsonNode node = valueNode(docId, context);
-      if (node == null) {
-        return null;
+    /// Convert directly into the caller's array. An absent key, an empty 
array, or one rejected element
+    /// makes the whole row a singleton containing the declared default.
+    private <T> int fillNumbers(@Nullable JsonNode node, T buffer, int 
capacity, NumberWriter<T> writer,
+        Number defaultValue) {
+      int count = elementCount(node);
+      if (count > capacity && !keeps(_converter, false, node)) {
+        // The buffer need only fit the logical value, which can be a 
singleton even for a long malformed array.
+        count = 0;
+      }
+      for (int i = 0; i < count; i++) {
+        Number value = (Number) convert(_converter, elementAt(node, i));
+        if (value == null) {
+          writer.set(buffer, 0, defaultValue);
+          return 1;
+        }
+        writer.set(buffer, i, value);
       }
-      if (!node.isArray()) {
-        return new JsonNode[]{node};
+      if (count == 0) {
+        writer.set(buffer, 0, defaultValue);
+        return 1;
       }
-      JsonNode[] nodes = new JsonNode[node.size()];
-      for (int i = 0; i < nodes.length; i++) {
-        nodes[i] = node.get(i);
+      return count;
+    }
+
+    private <T> T readNumbers(@Nullable JsonNode node, IntFunction<T> 
allocate, NumberWriter<T> writer,
+        Number defaultValue) {
+      int capacity = Math.max(1, elementCount(node));
+      T values = allocate.apply(capacity);
+      if (fillNumbers(node, values, capacity, writer, defaultValue) == 
capacity) {
+        return values;
       }
-      return nodes;
+      T singleton = allocate.apply(1);
+      writer.set(singleton, 0, defaultValue);
+      return singleton;
     }
 
     @Override
     public int getNumValuesMV(int docId, ForwardIndexReaderContext context) {
-      JsonNode[] nodes = valueNodes(docId, context);
-      // A document without the key reads as one element holding the default, 
which is what a materialized
-      // multi-value column stores for an absent document -- it has no empty 
state.
-      return nodes == null ? 1 : nodes.length;
+      JsonNode node = valueNode(docId, context);
+      return node != null && keeps(_converter, false, node) ? 
elementCount(node) : 1;
     }
 
     @Override
     public int[] getIntMV(int docId, ForwardIndexReaderContext context) {
-      JsonNode[] nodes = valueNodes(docId, context);
-      if (nodes == null) {
-        return new int[]{declaredOr(Integer.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_INT)};
-      }
-      int[] values = new int[nodes.length];
-      for (int i = 0; i < nodes.length; i++) {
-        values[i] = nodes[i].asInt();
-      }
-      return values;
+      return readNumbers(valueNode(docId, context), int[]::new, INT_WRITER,
+          declaredOr(Integer.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_INT));
     }
 
     @Override
     public int getIntMV(int docId, int[] valueBuffer, 
ForwardIndexReaderContext context) {
-      int[] values = getIntMV(docId, context);
-      System.arraycopy(values, 0, valueBuffer, 0, values.length);
-      return values.length;
+      return fillNumbers(valueNode(docId, context), valueBuffer, 
valueBuffer.length, INT_WRITER,
+          declaredOr(Integer.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_INT));
     }
 
     @Override
     public long[] getLongMV(int docId, ForwardIndexReaderContext context) {
-      JsonNode[] nodes = valueNodes(docId, context);
-      if (nodes == null) {
-        return new long[]{declaredOr(Long.class, (long) 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_LONG)};
-      }
-      long[] values = new long[nodes.length];
-      for (int i = 0; i < nodes.length; i++) {
-        values[i] = nodes[i].asLong();
-      }
-      return values;
+      return readNumbers(valueNode(docId, context), long[]::new, LONG_WRITER,
+          declaredOr(Long.class, (long) 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_LONG));
     }
 
     @Override
     public int getLongMV(int docId, long[] valueBuffer, 
ForwardIndexReaderContext context) {
-      long[] values = getLongMV(docId, context);
-      System.arraycopy(values, 0, valueBuffer, 0, values.length);
-      return values.length;
+      return fillNumbers(valueNode(docId, context), valueBuffer, 
valueBuffer.length, LONG_WRITER,
+          declaredOr(Long.class, (long) 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_LONG));
     }
 
     @Override
     public float[] getFloatMV(int docId, ForwardIndexReaderContext context) {
-      JsonNode[] nodes = valueNodes(docId, context);
-      if (nodes == null) {
-        return new float[]{declaredOr(Float.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_FLOAT)};
-      }
-      float[] values = new float[nodes.length];
-      for (int i = 0; i < nodes.length; i++) {
-        values[i] = (float) nodes[i].asDouble();
-      }
-      return values;
+      return readNumbers(valueNode(docId, context), float[]::new, FLOAT_WRITER,
+          declaredOr(Float.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_FLOAT));
     }
 
     @Override
     public int getFloatMV(int docId, float[] valueBuffer, 
ForwardIndexReaderContext context) {
-      float[] values = getFloatMV(docId, context);
-      System.arraycopy(values, 0, valueBuffer, 0, values.length);
-      return values.length;
+      return fillNumbers(valueNode(docId, context), valueBuffer, 
valueBuffer.length, FLOAT_WRITER,
+          declaredOr(Float.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_FLOAT));
     }
 
     @Override
     public double[] getDoubleMV(int docId, ForwardIndexReaderContext context) {
-      JsonNode[] nodes = valueNodes(docId, context);
-      if (nodes == null) {
-        return new double[]{declaredOr(Double.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_DOUBLE)};
-      }
-      double[] values = new double[nodes.length];
-      for (int i = 0; i < nodes.length; i++) {
-        values[i] = nodes[i].asDouble();
-      }
-      return values;
+      return readNumbers(valueNode(docId, context), double[]::new, 
DOUBLE_WRITER,
+          declaredOr(Double.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_DOUBLE));
     }
 
     @Override
     public int getDoubleMV(int docId, double[] valueBuffer, 
ForwardIndexReaderContext context) {
-      double[] values = getDoubleMV(docId, context);
-      System.arraycopy(values, 0, valueBuffer, 0, values.length);
-      return values.length;
+      return fillNumbers(valueNode(docId, context), valueBuffer, 
valueBuffer.length, DOUBLE_WRITER,
+          declaredOr(Double.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_DOUBLE));
     }
 
     @Override
     public BigDecimal[] getBigDecimalMV(int docId, ForwardIndexReaderContext 
context) {
-      JsonNode[] nodes = valueNodes(docId, context);
-      if (nodes == null) {
-        return new BigDecimal[]{declaredOr(BigDecimal.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_BIG_DECIMAL)};
-      }
-      BigDecimal[] values = new BigDecimal[nodes.length];
-      for (int i = 0; i < nodes.length; i++) {
-        values[i] = new BigDecimal(nodes[i].asText());
-      }
-      return values;
+      return readNumbers(valueNode(docId, context), BigDecimal[]::new, 
BIG_DECIMAL_WRITER,
+          declaredOr(BigDecimal.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_BIG_DECIMAL));
     }
 
     @Override
     public int getBigDecimalMV(int docId, BigDecimal[] valueBuffer, 
ForwardIndexReaderContext context) {
-      BigDecimal[] values = getBigDecimalMV(docId, context);
-      System.arraycopy(values, 0, valueBuffer, 0, values.length);
-      return values.length;
+      return fillNumbers(valueNode(docId, context), valueBuffer, 
valueBuffer.length, BIG_DECIMAL_WRITER,
+          declaredOr(BigDecimal.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_BIG_DECIMAL));
     }
 
     @Override
     public String[] getStringMV(int docId, ForwardIndexReaderContext context) {
-      JsonNode[] nodes = valueNodes(docId, context);
-      if (nodes == null) {
+      JsonNode node = valueNode(docId, context);
+      if (node == null || !keeps(null, false, node)) {
         return new String[]{declaredOr(String.class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_STRING)};
       }
-      String[] values = new String[nodes.length];
-      for (int i = 0; i < nodes.length; i++) {
+      int count = elementCount(node);
+      String[] values = new String[count];
+      for (int i = 0; i < count; i++) {
+        JsonNode element = elementAt(node, i);
         // Serialized for the same reason as the single-value getter: asText() 
is the empty string for a nested
         // element, which would be indistinguishable from an element that is 
genuinely "".
-        values[i] = nodes[i].isContainerNode() ? nodes[i].toString() : 
nodes[i].asText();
+        values[i] = element.isContainerNode() ? element.toString() : 
element.asText();
       }
       return values;
     }
@@ -340,13 +366,14 @@ public class SparseKeyDataSource extends BaseDataSource {
 
     @Override
     public byte[][] getBytesMV(int docId, ForwardIndexReaderContext context) {
-      JsonNode[] nodes = valueNodes(docId, context);
-      if (nodes == null) {
+      JsonNode node = valueNode(docId, context);
+      if (node == null || !keeps(null, false, node)) {
         return new byte[][]{declaredOr(byte[].class, 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_BYTES)};
       }
-      byte[][] values = new byte[nodes.length][];
-      for (int i = 0; i < nodes.length; i++) {
-        values[i] = binaryValue(nodes[i]);
+      int count = elementCount(node);
+      byte[][] values = new byte[count][];
+      for (int i = 0; i < count; i++) {
+        values[i] = binaryValue(elementAt(node, i));
       }
       return values;
     }
@@ -374,13 +401,88 @@ public class SparseKeyDataSource extends BaseDataSource {
     }
   }
 
+  /// The dense tier's conversion for a key of `dataType`: [PinotDataType] of 
its stored type, as
+  /// `OpenStructColumnSplitter` applies at build. Null for STRING, JSON and 
BYTES, which read any value as is.
+  @Nullable
+  static PinotDataType converterFor(DataType dataType) {
+    switch (dataType.getStoredType()) {
+      case INT:
+      case LONG:
+      case FLOAT:
+      case DOUBLE:
+      case BIG_DECIMAL:
+        return 
ColumnDataType.fromDataTypeSV(dataType.getStoredType()).toPinotDataType();
+      default:
+        return null;
+    }
+  }
+
+  /// `node` converted by `converter`, or null when the conversion rejects it. 
With no converter the node itself is
+  /// returned. Numeric keys cannot represent containers or nulls.
+  @Nullable
+  static Object convert(@Nullable PinotDataType converter, JsonNode node) {
+    if (converter == null) {
+      return node;
+    }
+    Object raw;
+    if (node.isNumber()) {
+      // BigInteger is classified as OBJECT by PinotDataType and would round 
through double.
+      if (converter == PinotDataType.BIG_DECIMAL) {
+        // The numeric parser keeps a DoubleNode only when this token exceeded 
BigDecimal's scale range.
+        return node.isDouble() ? null : node.decimalValue();
+      }
+      raw = node.numberValue();
+    } else if (node.isBoolean()) {
+      raw = node.booleanValue();
+    } else if (node.isTextual()) {
+      raw = node.textValue();
+    } else {
+      return null;
+    }
+    try {
+      return converter.convert(raw, PinotDataType.getSingleValueType(raw));
+    } catch (RuntimeException e) {
+      return null;
+    }
+  }
+
+  /// A scalar in a multi-value key is stored as a singleton. An empty array 
or absent key contributes no elements.
+  private static int elementCount(@Nullable JsonNode node) {
+    return node == null ? 0 : node.isArray() ? node.size() : 1;
+  }
+
+  private static JsonNode elementAt(JsonNode node, int index) {
+    return node.isArray() ? node.get(index) : node;
+  }
+
+  /// Whether the dense tier would keep this value for a key read through 
`converter`.
+  static boolean keeps(@Nullable PinotDataType converter, boolean singleValue, 
JsonNode node) {
+    if (singleValue || !node.isArray()) {
+      return converter == null || convert(converter, node) != null;
+    }
+    if (node.isEmpty()) {
+      return false;
+    }
+    for (JsonNode element : node) {
+      if (element.isNull() || (converter != null && convert(converter, 
element) == null)) {
+        return false;
+      }
+    }
+    return true;
+  }
+
   static class LazyPresenceNullVector implements NullValueVectorReader {
     private final String _key;
+    @Nullable
+    private final PinotDataType _converter;
+    private final boolean _singleValue;
     private final OpenStructSparseBlobReader _blob;
     private volatile ImmutableRoaringBitmap _nullBitmap;
 
-    LazyPresenceNullVector(String key, OpenStructSparseBlobReader blob) {
-      _key = key;
+    LazyPresenceNullVector(FieldSpec fieldSpec, OpenStructSparseBlobReader 
blob) {
+      _key = fieldSpec.getName();
+      _converter = converterFor(fieldSpec.getDataType());
+      _singleValue = fieldSpec.isSingleValueField();
       _blob = blob;
     }
 
@@ -388,7 +490,8 @@ public class SparseKeyDataSource extends BaseDataSource {
     public ImmutableRoaringBitmap getNullBitmap() {
       ImmutableRoaringBitmap bm = _nullBitmap;
       if (bm == null) {
-        ImmutableRoaringBitmap presence = _blob.computePresence(_key);
+        ImmutableRoaringBitmap presence = _blob.computePresence(_key, 
_converter,
+            node -> keeps(_converter, _singleValue, node));
         MutableRoaringBitmap nulls = new MutableRoaringBitmap();
         nulls.add(0L, _blob.getNumDocs());
         nulls.andNot(presence);
@@ -407,12 +510,15 @@ public class SparseKeyDataSource extends BaseDataSource {
   private static class SparseKeyMetadata implements DataSourceMetadata {
     private final FieldSpec _fieldSpec;
     private final int _numDocs;
-    private final int _maxNumValuesPerMVEntry;
+    private final SparseKeyForwardIndexReader _forwardReader;
+    private volatile int _maxNumValuesPerMVEntry;
 
-    SparseKeyMetadata(FieldSpec fieldSpec, int numDocs, int 
maxNumValuesPerMVEntry) {
+    SparseKeyMetadata(FieldSpec fieldSpec, int numDocs, int 
maxNumValuesPerMVEntry,
+        SparseKeyForwardIndexReader forwardReader) {
       _fieldSpec = fieldSpec;
       _numDocs = numDocs;
-      _maxNumValuesPerMVEntry = maxNumValuesPerMVEntry;
+      _forwardReader = forwardReader;
+      _maxNumValuesPerMVEntry = fieldSpec.isSingleValueField() ? 0 : 
maxNumValuesPerMVEntry;
     }
 
     @Override
@@ -437,6 +543,21 @@ public class SparseKeyDataSource extends BaseDataSource {
 
     @Override
     public int getMaxNumValuesPerMVEntry() {
+      int max = _maxNumValuesPerMVEntry;
+      return max >= 0 ? max : computeMaxNumValuesPerMVEntry();
+    }
+
+    /// Scan missing length metadata only when a caller needs it to size a 
buffer.
+    private synchronized int computeMaxNumValuesPerMVEntry() {
+      if (_maxNumValuesPerMVEntry < 0) {
+        int max = 1;
+        try (ForwardIndexReaderContext context = 
_forwardReader.createContext()) {
+          for (int docId = 0; docId < _numDocs; docId++) {
+            max = Math.max(max, _forwardReader.getNumValuesMV(docId, context));
+          }
+        }
+        _maxNumValuesPerMVEntry = max;
+      }
       return _maxNumValuesPerMVEntry;
     }
 
diff --git 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/openstruct/ImmutableOpenStructDataSourceTest.java
 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/openstruct/ImmutableOpenStructDataSourceTest.java
index 8af04da884c..e440d83ad7f 100644
--- 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/openstruct/ImmutableOpenStructDataSourceTest.java
+++ 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/openstruct/ImmutableOpenStructDataSourceTest.java
@@ -64,6 +64,10 @@ import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 import static org.testng.Assert.assertEquals;
 import static org.testng.Assert.assertFalse;
@@ -361,6 +365,29 @@ public class ImmutableOpenStructDataSourceTest {
     assertTrue(anyDs instanceof SparseKeyDataSource);
   }
 
+  @Test
+  public void testNestedMultiValueKeyWithoutLengthManifest() {
+    String[] blobs = {null, "{\"o\":{\"z\":[1,2]}}"};
+    ComplexFieldSpec spec = new ComplexFieldSpec("event", 
DataType.OPEN_STRUCT, true,
+        Map.of("o.z", new DimensionFieldSpec("o.z", DataType.LONG, false)));
+    FakeStringForwardIndex reader = spy(new FakeStringForwardIndex(blobs));
+    DataSource sparse = mock(DataSource.class);
+    doReturn(reader).when(sparse).getForwardIndex();
+    
doReturn(FakeStringForwardIndex.nullVector(blobs)).when(sparse).getNullValueVector();
+    ImmutableOpenStructDataSource ds =
+        new ImmutableOpenStructDataSource(spec, Map.of(), sparse, 
blobs.length, null, null, null);
+    DataSource key = ds.getDataSource("o.z");
+    verify(reader, never()).getString(1, null);
+    assertTrue(key.getNullValueVector().isNull(0));
+    verify(reader).getString(1, null);
+
+    long[] buffer = new 
long[key.getDataSourceMetadata().getMaxNumValuesPerMVEntry()];
+    assertEquals(key.getDataSourceMetadata().getMaxNumValuesPerMVEntry(), 2);
+    verify(reader, times(2)).getString(1, null);
+    assertEquals(key.getForwardIndex().getLongMV(1, buffer, null), 2);
+    assertEquals(buffer, new long[]{1, 2});
+  }
+
   @Test
   public void testDeclaredChildSpecDrivesVirtualType() {
     String[] blobs = {"{\"latencyMs\":42}", null};
diff --git 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/openstruct/OpenStructSparseBlobReaderTest.java
 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/openstruct/OpenStructSparseBlobReaderTest.java
index 44253c514d8..24cfbe50c38 100644
--- 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/openstruct/OpenStructSparseBlobReaderTest.java
+++ 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/openstruct/OpenStructSparseBlobReaderTest.java
@@ -19,6 +19,10 @@
 package org.apache.pinot.segment.local.segment.index.openstruct;
 
 import com.fasterxml.jackson.databind.JsonNode;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.apache.pinot.spi.data.OpenStructKeyFlattener;
+import org.apache.pinot.spi.utils.JsonUtils;
 import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
 import org.testng.annotations.Test;
 
@@ -75,6 +79,92 @@ public class OpenStructSparseBlobReaderTest {
     assertNull(blob.getValue(1, "region", null));
   }
 
+  private static OpenStructSparseBlobReader readerOf(String... blobs) {
+    return new OpenStructSparseBlobReader(new FakeStringForwardIndex(blobs), 
FakeStringForwardIndex.nullVector(blobs),
+        blobs.length);
+  }
+
+  @Test
+  public void testDottedKeyWalksNestedObjects() {
+    OpenStructSparseBlobReader blob = 
readerOf("{\"o\":{\"z\":2,\"w\":{\"x\":\"deep\"}},\"n\":5}");
+    assertEquals(blob.getValue(0, "o.z", null).asInt(), 2);
+    assertEquals(blob.getValue(0, "o.w.x", null).asText(), "deep");
+    // A path that ends on an object returns the object, like a top-level key 
does.
+    assertEquals(blob.getValue(0, "o.w", null).toString(), "{\"x\":\"deep\"}");
+    assertEquals(blob.getValue(0, "n", null).asInt(), 5);
+  }
+
+  @Test
+  public void testLiteralDottedKeyWinsOverPath() {
+    // Same rule as OpenStructKeyFlattener: a key the document carries is 
never shadowed by a path.
+    assertEquals(readerOf("{\"a.b\":100,\"a\":{\"b\":200}}").getValue(0, 
"a.b", null).asInt(), 100);
+    // The literal wins at an inner level too.
+    assertEquals(readerOf("{\"a\":{\"b.c\":1,\"b\":{\"c\":2}}}").getValue(0, 
"a.b.c", null).asInt(), 1);
+    // Two synthesized paths: the first in document order wins, as in the 
flattener.
+    assertEquals(readerOf("{\"a.b\":{\"c\":1},\"a\":{\"b.c\":2}}").getValue(0, 
"a.b.c", null).asInt(), 1);
+  }
+
+  @Test
+  public void testDottedKeyThatCannotBeWalkedIsAbsent() {
+    OpenStructSparseBlobReader blob = 
readerOf("{\"tags\":[\"x\",\"y\"],\"s\":\"text\",\"o\":{\"z\":2},\"nul\":null}");
+    assertNull(blob.getValue(0, "tags.0", null));    // arrays are not indexed 
into
+    assertNull(blob.getValue(0, "s.len", null));     // scalar intermediate
+    assertNull(blob.getValue(0, "o.missing", null)); // missing leaf
+    assertNull(blob.getValue(0, "nope.z", null));    // missing intermediate
+    assertNull(blob.getValue(0, "nul.z", null));     // null intermediate
+  }
+
+  /// Oracle: for every document, each key `OpenStructKeyFlattener` emits 
(unbounded depth) resolves to the value the
+  /// flattener emits for it, and probe paths it does not emit resolve to 
nothing. Covers literal-wins at every
+  /// level, collisions between synthesized paths, empty segments, arrays, 
nulls and scalars.
+  @Test
+  public void testResolveMatchesFlattener() throws Exception {
+    String[] docs = {
+        "{\"o\":{\"z\":2,\"w\":{\"x\":\"deep\"}},\"n\":5}",
+        "{\"a.b\":100,\"a\":{\"b\":200}}",
+        "{\"a\":{\"b.c\":1,\"b\":{\"c\":2}}}",
+        "{\"a.b\":{\"c\":1},\"a\":{\"b.c\":2}}",
+        "{\"o\":{\"\":1},\"\":{\"b\":2},\"e\":{\"\":{\"x\":3}}}",
+        
"{\"tags\":[\"x\",{\"y\":1}],\"s\":\"text\",\"nul\":null,\"o\":{\"z\":null,\"q\":{}}}",
+        "{\"a\":{\"b\":{\"c\":{\"d\":{\"e\":1}}}},\"a.b.c\":{\"d\":9}}",
+    };
+    String[] probes = {"o.missing", "tags.0", "tags.1.y", "s.len", "nul.z", 
"nope.z", "o.q.r", "a.x", "..", "x."};
+    int checked = 0;
+    for (String json : docs) {
+      JsonNode blob = JsonUtils.stringToJsonNode(json);
+      @SuppressWarnings("unchecked")
+      Map<String, Object> document = JsonUtils.stringToObject(json, Map.class);
+      Map<String, Object> emitted = new LinkedHashMap<>();
+      OpenStructKeyFlattener.flatten(document, Integer.MAX_VALUE, (path, 
value, container) -> emitted.put(path,
+          value));
+      for (Map.Entry<String, Object> entry : emitted.entrySet()) {
+        JsonNode resolved = OpenStructSparseBlobReader.resolve(blob, 
entry.getKey());
+        assertNotNull(resolved, json + " -> " + entry.getKey());
+        Object value = entry.getValue();
+        JsonNode expected = value instanceof String text && 
resolved.isContainerNode()
+            ? JsonUtils.stringToJsonNode(text) : 
JsonUtils.objectToJsonNode(value);
+        assertEquals(resolved, expected, json + " -> " + entry.getKey());
+        checked++;
+      }
+      for (String probe : probes) {
+        if (!emitted.containsKey(probe)) {
+          assertNull(OpenStructSparseBlobReader.resolve(blob, probe), json + " 
-> " + probe);
+        }
+      }
+    }
+    assertTrue(checked >= 30, "only " + checked + " flattened keys checked");
+  }
+
+  @Test
+  public void testPresenceFollowsDottedPath() {
+    OpenStructSparseBlobReader blob = readerOf("{\"o\":{\"z\":1}}", 
"{\"o\":{}}", "{\"o\":{\"z\":null}}", "{}");
+    ImmutableRoaringBitmap present = blob.computePresence("o.z");
+    assertTrue(present.contains(0));
+    assertFalse(present.contains(1));
+    assertFalse(present.contains(2)); // explicit JSON null is absent, as for 
top-level keys
+    assertFalse(present.contains(3));
+  }
+
   @Test
   public void testExplicitJsonNullIsPresentButNullNode() {
     String[] blobs = {"{\"region\":null}"};
diff --git 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/openstruct/OpenStructSparseDenseParityTest.java
 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/openstruct/OpenStructSparseDenseParityTest.java
index 3e5ca1f7995..fe226047b35 100644
--- 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/openstruct/OpenStructSparseDenseParityTest.java
+++ 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/openstruct/OpenStructSparseDenseParityTest.java
@@ -20,6 +20,7 @@ package 
org.apache.pinot.segment.local.segment.index.openstruct;
 
 import com.fasterxml.jackson.databind.node.ObjectNode;
 import java.io.File;
+import java.math.BigDecimal;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
@@ -51,6 +52,7 @@ import org.apache.pinot.spi.config.table.TableType;
 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.apache.pinot.spi.data.readers.GenericRow;
 import org.apache.pinot.spi.utils.JsonUtils;
@@ -94,11 +96,21 @@ public class OpenStructSparseDenseParityTest {
     children.put("tags", new DimensionFieldSpec("tags", 
FieldSpec.DataType.STRING, true));
     // Declared INT, only populated by 
testTypeMismatchedValueDroppedFromBothTiers.
     children.put("count", new DimensionFieldSpec("count", 
FieldSpec.DataType.INT, true));
+    for (Map.Entry<String, DataType> typed : TYPED_KEYS.entrySet()) {
+      children.put(typed.getKey(), new DimensionFieldSpec(typed.getKey(), 
typed.getValue(), true));
+    }
     return new ComplexFieldSpec(METRICS, FieldSpec.DataType.OPEN_STRUCT, true, 
children);
   }
 
+  private static final Map<String, DataType> TYPED_KEYS = Map.of("iv", 
DataType.INT, "lv", DataType.LONG,
+      "fv", DataType.FLOAT, "dv", DataType.DOUBLE, "bdv", 
DataType.BIG_DECIMAL, "bv", DataType.BOOLEAN,
+      "tv", DataType.TIMESTAMP);
+
   private static Map<String, Object> metricsForDoc(int docId) {
     Map<String, Object> m = new HashMap<>();
+    if (docId == 0 || docId == 1) {
+      m.put("bdv", new BigDecimal(docId == 0 ? "9223372036854775809" : 
"12345678901234567890.1234567890"));
+    }
     if (docId % 3 == 0) {
       m.put("region", docId % 6 == 0 ? "us" : "eu");
     }
@@ -160,6 +172,7 @@ public class OpenStructSparseDenseParityTest {
       OpenStructDataSource denseDs = (OpenStructDataSource) 
dense.getDataSource(METRICS);
       OpenStructDataSource sparseDs = (OpenStructDataSource) 
sparse.getDataSource(METRICS);
 
+      assertForwardValuesParity(denseDs, sparseDs, "bdv", 
DataType.BIG_DECIMAL);
       assertForwardValuesParity(denseDs, sparseDs, "region", 
FieldSpec.DataType.STRING);
       assertNullBitmapParity(denseDs, sparseDs, "region");
       assertForwardValuesParity(denseDs, sparseDs, "latencyMs", 
FieldSpec.DataType.LONG);
@@ -231,6 +244,8 @@ public class OpenStructSparseDenseParityTest {
         return fwd.getFloat(docId, ctx);
       case DOUBLE:
         return fwd.getDouble(docId, ctx);
+      case BIG_DECIMAL:
+        return fwd.getBigDecimal(docId, ctx);
       case STRING:
         return fwd.getString(docId, ctx);
       default:
@@ -490,6 +505,63 @@ public class OpenStructSparseDenseParityTest {
     }
   }
 
+  /// A sparse blob written outside the build (e.g. by an external source) 
holds values as they arrived, not as the
+  /// build would have converted them. Reading it must give what the dense 
tier gives for the same raw value: the
+  /// value the build's conversion produces, or absent where the build drops 
it. Oracle: the same raw values built
+  /// into dense columns, for every declared scalar type and a spread of 
fitting, lossy and unconvertible values.
+  @Test
+  public void testExternalSparseBlobReadsLikeTheDenseTier()
+      throws Exception {
+    // The decimal converts to INT 1 and LONG 9007199254740993. Parsing it as 
a double first changes both.
+    Object[] raw = {5, 7L, 1.5, 2.0, -0.0, "7", " 8 ", "1.9", "1e3", "abc", 
"", true, false, "true", 2,
+        Long.MAX_VALUE, 1.0e20, new BigDecimal("9007199254740993.1"),
+        new BigDecimal("1.000000059604644775390625000001"), "2026-01-01 
00:00:00", List.of(1, 2)};
+    List<GenericRow> rows = new ArrayList<>(raw.length);
+    String[] blobs = new String[raw.length];
+    for (int docId = 0; docId < raw.length; docId++) {
+      Map<String, Object> m = new HashMap<>();
+      for (String key : TYPED_KEYS.keySet()) {
+        m.put(key, raw[docId]);
+      }
+      GenericRow row = new GenericRow();
+      row.putValue(METRICS, m);
+      rows.add(row);
+      blobs[docId] = JsonUtils.objectToString(m);
+    }
+    OpenStructIndexConfig denseConfig =
+        new OpenStructIndexConfig(false, null, null, TYPED_KEYS.keySet(), 
null, null, null, null, null, null, null);
+    ImmutableSegment dense = buildSegment(denseConfig, "dense-typed", rows);
+    try {
+      OpenStructDataSource denseDs = (OpenStructDataSource) 
dense.getDataSource(METRICS);
+      OpenStructSparseBlobReader blob = new OpenStructSparseBlobReader(new 
FakeStringForwardIndex(blobs),
+          FakeStringForwardIndex.nullVector(blobs), blobs.length);
+      for (Map.Entry<String, DataType> typed : TYPED_KEYS.entrySet()) {
+        String key = typed.getKey();
+        assertTrue(denseDs.isMaterialized(key), key);
+        DataSource denseKey = denseDs.getDataSource(key);
+        SparseKeyDataSource sparseKey =
+            new SparseKeyDataSource(new DimensionFieldSpec(key, 
typed.getValue(), true), blob, 0);
+        DataType storedType = typed.getValue().getStoredType();
+        ForwardIndexReader<?> denseFwd = denseKey.getForwardIndex();
+        ForwardIndexReader<?> sparseFwd = sparseKey.getForwardIndex();
+        try (ForwardIndexReaderContext denseCtx = denseFwd.createContext();
+            ForwardIndexReaderContext sparseCtx = sparseFwd.createContext()) {
+          for (int docId = 0; docId < raw.length; docId++) {
+            String where = key + " (" + typed.getValue() + ") <- " + 
raw[docId];
+            boolean denseNull = denseKey.getNullValueVector().isNull(docId);
+            assertEquals(sparseKey.getNullValueVector().isNull(docId), 
denseNull, where);
+            if (!denseNull) {
+              assertEquals(readValue(sparseKey, sparseFwd, docId, storedType, 
sparseCtx),
+                  readValue(denseKey, denseFwd, docId, storedType, denseCtx), 
where);
+            }
+          }
+        }
+      }
+    } finally {
+      dense.destroy();
+    }
+  }
+
   /// A value that cannot be coerced to its key's declared type never reaches 
either tier.
   /// `OpenStructColumnSplitter#addMap` catches the `PinotDataType.convert` 
failure, rolls the doc
   /// back out of the key's presence bitmap and stores nothing — so 
`writeDenseKeyColumn` and
diff --git 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/openstruct/SparseKeyDataSourceTest.java
 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/openstruct/SparseKeyDataSourceTest.java
index f42a9cac27e..824b87aa2de 100644
--- 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/openstruct/SparseKeyDataSourceTest.java
+++ 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/openstruct/SparseKeyDataSourceTest.java
@@ -19,6 +19,7 @@
 package org.apache.pinot.segment.local.segment.index.openstruct;
 
 import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
 import org.apache.pinot.segment.spi.Constants;
 import org.apache.pinot.segment.spi.datasource.DataSourceMetadata;
 import org.apache.pinot.segment.spi.index.reader.ForwardIndexReader;
@@ -42,6 +43,221 @@ public class SparseKeyDataSourceTest {
       "{\"other\":1}",
   };
 
+  /// Numeric text converts to a number and fractions truncate for integral 
keys. Nonnumeric text, objects and
+  /// arrays are absent for these single-value numeric keys.
+  private static final String[] MIXED = {
+      "{\"k\":5}", "{\"k\":\"abc\"}", "{\"k\":1.5}", "{\"k\":2.0}", 
"{\"k\":\"7\"}", "{\"k\":{\"x\":1}}",
+      "{\"k\":true}", "{\"k\":[1,2]}", "{\"k\":9223372036854775807}",
+  };
+
+  private static SparseKeyDataSource of(DataType declaredType, String... 
blobs) {
+    OpenStructSparseBlobReader blob = new OpenStructSparseBlobReader(
+        new FakeStringForwardIndex(blobs), 
FakeStringForwardIndex.nullVector(blobs), blobs.length);
+    return new SparseKeyDataSource(new DimensionFieldSpec("k", declaredType, 
true), blob, 0);
+  }
+
+  /// A multi-value key converts each element as the dense tier does; when any 
element is rejected the dense tier drops
+  /// the whole value (its length is part of it), so the document reads as 
absent.
+  @Test
+  public void testMultiValueKeyIsAbsentWhenAnyElementIsRejected() {
+    String[] blobs = {"{\"k\":[1,\"2\"]}", "{\"k\":[1,2,\"abc\"]}", 
"{\"k\":7}", "{\"k\":[]}"};
+    OpenStructSparseBlobReader blob = new OpenStructSparseBlobReader(new 
FakeStringForwardIndex(blobs),
+        FakeStringForwardIndex.nullVector(blobs), blobs.length);
+    DimensionFieldSpec spec = new DimensionFieldSpec("k", DataType.LONG, 
false);
+    spec.setDefaultNullValue(-7L);
+    SparseKeyDataSource longs = new SparseKeyDataSource(spec, blob, 2);
+    ForwardIndexReader<?> fwd = longs.getForwardIndex();
+    assertEquals(fwd.getLongMV(0, null), new long[]{1, 2});
+    assertEquals(fwd.getNumValuesMV(1, null), 1);
+    long[] buffer = new long[1];
+    assertEquals(fwd.getLongMV(1, buffer, null), 1);
+    assertEquals(buffer[0], -7L);
+    assertEquals(fwd.getLongMV(1, null), new long[]{-7L});
+    assertEquals(fwd.getLongMV(2, null), new long[]{7});
+    assertFalse(longs.getNullValueVector().isNull(0));
+    assertTrue(longs.getNullValueVector().isNull(1));
+    assertFalse(longs.getNullValueVector().isNull(2));
+    assertTrue(longs.getNullValueVector().isNull(3));
+    assertEquals(fwd.getNumValuesMV(3, null), 1);
+    assertEquals(fwd.getLongMV(3, null), new long[]{-7L});
+  }
+
+  private static SparseKeyDataSource multiValue(DataType declaredType, 
String... blobs) {
+    OpenStructSparseBlobReader blob = new OpenStructSparseBlobReader(new 
FakeStringForwardIndex(blobs),
+        FakeStringForwardIndex.nullVector(blobs), blobs.length);
+    return new SparseKeyDataSource(new DimensionFieldSpec("k", declaredType, 
false), blob, 3);
+  }
+
+  /// Every multi-value getter converts each element to the key's stored type 
(numeric text and fractions as the dense
+  /// tier converts them), reads a document without the key as the single 
default the dense tier stores for it, reads a
+  /// scalar stored before the key became multi-value as a one-element value, 
and fills a caller's buffer.
+  @Test
+  public void testMultiValueNumericGettersConvertEachElement() {
+    String[] blobs = {"{\"k\":[1,\"2\",3.0]}", null, "{\"k\":4}"};
+
+    ForwardIndexReader<?> ints = multiValue(DataType.INT, 
blobs).getForwardIndex();
+    assertEquals(ints.getNumValuesMV(0, null), 3);
+    assertEquals(ints.getIntMV(0, null), new int[]{1, 2, 3});
+    int[] intBuffer = new int[3];
+    assertEquals(ints.getIntMV(0, intBuffer, null), 3);
+    assertEquals(intBuffer, new int[]{1, 2, 3});
+    assertEquals(ints.getIntMV(1, null), new 
int[]{FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_INT});
+    assertEquals(ints.getNumValuesMV(1, null), 1);
+    assertEquals(ints.getIntMV(2, null), new int[]{4});
+
+    ForwardIndexReader<?> longs = multiValue(DataType.LONG, 
blobs).getForwardIndex();
+    long[] longBuffer = new long[3];
+    assertEquals(longs.getLongMV(0, longBuffer, null), 3);
+    assertEquals(longBuffer, new long[]{1, 2, 3});
+
+    ForwardIndexReader<?> floats = multiValue(DataType.FLOAT, 
blobs).getForwardIndex();
+    assertEquals(floats.getFloatMV(0, null), new float[]{1f, 2f, 3f});
+    float[] floatBuffer = new float[3];
+    assertEquals(floats.getFloatMV(0, floatBuffer, null), 3);
+    assertEquals(floatBuffer, new float[]{1f, 2f, 3f});
+    assertEquals(floats.getFloatMV(1, null), new 
float[]{FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_FLOAT});
+    assertEquals(floats.getFloatMV(2, null), new float[]{4f});
+
+    ForwardIndexReader<?> doubles = multiValue(DataType.DOUBLE, 
blobs).getForwardIndex();
+    assertEquals(doubles.getDoubleMV(0, null), new double[]{1.0, 2.0, 3.0});
+    double[] doubleBuffer = new double[3];
+    assertEquals(doubles.getDoubleMV(0, doubleBuffer, null), 3);
+    assertEquals(doubleBuffer, new double[]{1.0, 2.0, 3.0});
+    assertEquals(doubles.getDoubleMV(1, null), new 
double[]{FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_DOUBLE});
+    assertEquals(doubles.getDoubleMV(2, null), new double[]{4.0});
+  }
+
+  @Test
+  public void testMultiValueBigDecimalGettersConvertEachElement() {
+    String[] blobs = {"{\"k\":[1,\"2.5\",3.25,9223372036854775809]}", null, 
"{\"k\":4}"};
+    ForwardIndexReader<?> decimals = multiValue(DataType.BIG_DECIMAL, 
blobs).getForwardIndex();
+
+    BigDecimal beyondLong = new BigDecimal("9223372036854775809");
+    BigDecimal[] values = decimals.getBigDecimalMV(0, null);
+    assertEquals(values.length, 4);
+    assertEquals(values[0].compareTo(new BigDecimal("1")), 0);
+    assertEquals(values[1].compareTo(new BigDecimal("2.5")), 0);
+    assertEquals(values[2].compareTo(new BigDecimal("3.25")), 0);
+    assertEquals(values[3].compareTo(beyondLong), 0);
+    BigDecimal[] buffer = new BigDecimal[4];
+    assertEquals(decimals.getBigDecimalMV(0, buffer, null), 4);
+    assertEquals(buffer[1].compareTo(new BigDecimal("2.5")), 0);
+    assertEquals(buffer[3].compareTo(beyondLong), 0);
+    assertEquals(decimals.getBigDecimalMV(1, null),
+        new 
BigDecimal[]{FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_BIG_DECIMAL});
+    assertEquals(decimals.getBigDecimalMV(2, null)[0].compareTo(new 
BigDecimal("4")), 0);
+  }
+
+  /// A STRING multi-value key takes every element as text (a nested element 
as JSON, not the empty string), and a
+  /// BYTES one decodes each base64 element, reading a malformed or non-binary 
element as the default.
+  @Test
+  public void testMultiValueStringAndBytesGetters() {
+    String[] stringBlobs = {"{\"k\":[\"a\",{\"x\":1},5,true]}", "{\"k\":[]}", 
"{\"k\":\"s\"}"};
+    SparseKeyDataSource stringSource = multiValue(DataType.STRING, 
stringBlobs);
+    ForwardIndexReader<?> strings = stringSource.getForwardIndex();
+    String[] expected = {"a", "{\"x\":1}", "5", "true"};
+    assertEquals(strings.getNumValuesMV(0, null), 4);
+    assertEquals(strings.getStringMV(0, null), expected);
+    String[] stringBuffer = new String[4];
+    assertEquals(strings.getStringMV(0, stringBuffer, null), 4);
+    assertEquals(stringBuffer, expected);
+    assertTrue(stringSource.getNullValueVector().isNull(1));
+    assertEquals(strings.getNumValuesMV(1, null), 1);
+    assertEquals(strings.getStringMV(1, null), new 
String[]{FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_STRING});
+    assertEquals(strings.getStringMV(2, null), new String[]{"s"});
+
+    String[] bytesBlobs = {"{\"k\":[\"aGVsbG8=\",\"!!not base64\",5]}", null};
+    ForwardIndexReader<?> bytes = multiValue(DataType.BYTES, 
bytesBlobs).getForwardIndex();
+    byte[] hello = "hello".getBytes(StandardCharsets.UTF_8);
+    byte[] absent = FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_BYTES;
+    assertEquals(bytes.getBytesMV(0, null), new byte[][]{hello, absent, 
absent});
+    byte[][] bytesBuffer = new byte[3][];
+    assertEquals(bytes.getBytesMV(0, bytesBuffer, null), 3);
+    assertEquals(bytesBuffer, new byte[][]{hello, absent, absent});
+    assertEquals(bytes.getBytesMV(1, null), new byte[][]{absent});
+  }
+
+  /// A null element takes the whole multi-value out, as the dense tier drops 
it (length is part of the value), and the
+  /// null vector agrees.
+  @Test
+  public void testMultiValueKeyWithANullElementIsAbsent() {
+    SparseKeyDataSource longs = multiValue(DataType.LONG, "{\"k\":[1,null]}", 
"{\"k\":[1,2]}");
+    assertTrue(longs.getNullValueVector().isNull(0));
+    assertFalse(longs.getNullValueVector().isNull(1));
+    assertEquals(longs.getForwardIndex().getLongMV(0, null),
+        new long[]{FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_LONG});
+    assertEquals(longs.getForwardIndex().getLongMV(1, null), new long[]{1, 2});
+
+    String withNull = "{\"k\":[\"aGVsbG8=\",null]}";
+    SparseKeyDataSource strings = multiValue(DataType.STRING, withNull);
+    assertTrue(strings.getNullValueVector().isNull(0));
+    assertEquals(strings.getForwardIndex().getNumValuesMV(0, null), 1);
+    assertEquals(strings.getForwardIndex().getStringMV(0, null),
+        new String[]{FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_STRING});
+    SparseKeyDataSource bytes = multiValue(DataType.BYTES, withNull);
+    assertTrue(bytes.getNullValueVector().isNull(0));
+    assertEquals(bytes.getForwardIndex().getBytesMV(0, null),
+        new byte[][]{FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_BYTES});
+  }
+
+  @Test
+  public void testExponentOutsideDecimalRange() {
+    for (String token : new String[]{"1e-2147483649", "1e2147483649"}) {
+      String blob = "{\"k\":1,\"other\":" + token + "}";
+      assertEquals(of(DataType.LONG, blob).getForwardIndex().getLong(0, null), 
1L);
+      assertEquals(of(DataType.BIG_DECIMAL, 
blob).getForwardIndex().getBigDecimal(0, null), BigDecimal.ONE);
+      SparseKeyDataSource missing = of(DataType.BIG_DECIMAL, "{\"k\":" + token 
+ "}");
+      assertTrue(missing.getNullValueVector().isNull(0));
+      assertEquals(missing.getForwardIndex().getBigDecimal(0, null),
+          FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_BIG_DECIMAL);
+    }
+  }
+
+  @Test
+  public void testIntOverflowFromTextIsAbsent() {
+    SparseKeyDataSource ints = of(DataType.INT, "{\"k\":\"2147483648\"}", 
"{\"k\":\"42\"}");
+    assertTrue(ints.getNullValueVector().isNull(0));
+    assertEquals(ints.getForwardIndex().getInt(1, null), 42);
+  }
+
+  private static SparseKeyDataSource mixed(DataType declaredType) {
+    OpenStructSparseBlobReader blob = new OpenStructSparseBlobReader(
+        new FakeStringForwardIndex(MIXED), 
FakeStringForwardIndex.nullVector(MIXED), MIXED.length);
+    return new SparseKeyDataSource(new DimensionFieldSpec("k", declaredType, 
true), blob, 0);
+  }
+
+  @Test
+  public void testDeclaredNumericKeyReadsOnlyValuesThatFit() {
+    // Text that is not a number, an object and an array read as absent rather 
than as an invented 0, and the null
+    // vector agrees; a fraction converts as the dense tier converts it. 
OpenStructSparseDenseParityTest checks
+    // every type against the dense tier itself.
+    SparseKeyDataSource longs = mixed(DataType.LONG);
+    ForwardIndexReader<?> fwd = longs.getForwardIndex();
+    long absent = (long) FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_LONG;
+    for (int doc : new int[]{1, 5, 7}) {
+      assertEquals(fwd.getLong(doc, null), absent, MIXED[doc]);
+      assertTrue(longs.getNullValueVector().isNull(doc), MIXED[doc]);
+    }
+    assertEquals(fwd.getLong(0, null), 5L);
+    assertEquals(fwd.getLong(2, null), 1L);
+    assertEquals(fwd.getLong(4, null), 7L);
+    assertEquals(fwd.getLong(8, null), Long.MAX_VALUE);
+    assertFalse(longs.getNullValueVector().isNull(2));
+
+    SparseKeyDataSource doubles = mixed(DataType.DOUBLE);
+    assertEquals(doubles.getForwardIndex().getDouble(2, null), 1.5);
+    assertEquals(doubles.getForwardIndex().getDouble(4, null), 7.0);
+    assertTrue(doubles.getNullValueVector().isNull(1));
+    assertTrue(doubles.getNullValueVector().isNull(5));
+    assertFalse(doubles.getNullValueVector().isNull(2));
+
+    // STRING still takes every value.
+    SparseKeyDataSource strings = mixed(DataType.STRING);
+    for (int doc = 0; doc < MIXED.length; doc++) {
+      assertFalse(strings.getNullValueVector().isNull(doc), MIXED[doc]);
+    }
+  }
+
   private static SparseKeyDataSource source(String key, DataType declaredType) 
{
     OpenStructSparseBlobReader blob = new OpenStructSparseBlobReader(
         new FakeStringForwardIndex(BLOBS), 
FakeStringForwardIndex.nullVector(BLOBS), BLOBS.length);
@@ -156,7 +372,7 @@ public class SparseKeyDataSourceTest {
     // "aGVsbG8=" is base64 for "hello"
     SparseKeyDataSource src = source("b", DataType.BYTES);
     ForwardIndexReader<?> fwd = src.getForwardIndex();
-    assertEquals(fwd.getBytes(0, null), 
"hello".getBytes(java.nio.charset.StandardCharsets.UTF_8));
+    assertEquals(fwd.getBytes(0, null), 
"hello".getBytes(StandardCharsets.UTF_8));
     assertEquals(fwd.getBytes(1, null), 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_BYTES);
     assertEquals(fwd.getBytes(2, null), 
FieldSpec.DEFAULT_DIMENSION_NULL_VALUE_OF_BYTES);
   }
diff --git 
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/datasource/OpenStructDataSource.java
 
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/datasource/OpenStructDataSource.java
index 9dfdbbe6853..4e9d9af01d2 100644
--- 
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/datasource/OpenStructDataSource.java
+++ 
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/datasource/OpenStructDataSource.java
@@ -28,6 +28,7 @@ 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.OpenStructKeyFlattener;
 
 
 /// DataSource for an OPEN_STRUCT column. Provides per-key DataSources that 
can be used for
@@ -134,4 +135,21 @@ public interface OpenStructDataSource extends DataSource {
   default JsonIndexReader getSparseJsonIndex() {
     return null;
   }
+
+  /// Returns the sparse JSON index when its postings use the same key as the 
sparse reader. A dotted key can
+  /// match several paths in a nested blob, so serving it requires knowledge 
of the physical sparse fields.
+  @Nullable
+  default JsonIndexReader getSparseJsonIndex(String key) {
+    // JSON readers interpret a leading '$' as the root and '[' as an array 
subscript. OPEN_STRUCT keys are literal.
+    if (key.startsWith("$") || key.indexOf('[') >= 0 || 
!hasUnambiguousSparseJsonPath(key)) {
+      return null;
+    }
+    return getSparseJsonIndex();
+  }
+
+  /// Whether this key's JSON index path is free of collisions when the sparse 
fields are flattened.
+  /// Without physical field metadata, only a single path segment is 
unambiguous.
+  default boolean hasUnambiguousSparseJsonPath(String key) {
+    return key.indexOf(OpenStructKeyFlattener.PATH_SEPARATOR) < 0;
+  }
 }


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

Reply via email to