Repository navigation
Closed
2 / 22 of 2 issues completed
Copy link
Description
What is the bug?
When a PPL command produces a MAP-typed column (e.g., spath auto-extract), downstream commands that reference nested values via dotted paths like doc.user.name fail in many commands. See Technical Deep Dive for more details.
How can one reproduce the bug?
- Create an index with a JSON string field and enable Calcite:
PUT /test/_doc/1 {"doc": "{\"user\":{\"name\":\"John\",\"age\":30,\"city\":\"NYC\"}}"}
PUT /test/_doc/2 {"doc": "{\"user\":{\"name\":\"Alice\",\"age\":25,\"city\":\"LA\"}}"}
- Run any of these queries (see Impact Analysis):
# Field name matching failures (Category A):
source=test | spath input=doc | rename doc.user.name as username | fields username
source=test | spath input=doc | fillnull using doc.user.name = 'N/A'
source=test | spath input=doc | replace 'John' WITH 'Jonathan' IN doc.user.name
source=test | spath input=doc | top 1 doc.user.name by doc.user.city
source=test | spath input=doc | rare doc.user.name by doc.user.city
source=test | spath input=doc | fields - doc.user.name
source=test | spath input=doc | rename doc.user.* as extracted.*
# Projection naming failures (Category B):
source=test | spath input=doc | top 2 doc.user.name
source=test | spath input=doc | rare doc.user.name
source=test | spath input=doc
| inner join left=a, right=b ON a.doc.user.name = b.name other_index
What is the expected behavior?
Path navigation expression, such as doc.user.name, should work uniformly across all PPL commands when root field type (doc) is a MAP/STRUCT column.
What is your host/environment?
- PPL Calcite V3 engine
Do you have any screenshots?
N/A
Do you have any additional context?
-
User-side workarounds
- Generic workaround: materialize nested MAP values via
eval, then reference the materialized columns downstream.
Example:eval username = doc.user.name, age = doc.user.age - spath-specific workaround: fall back to chained
spathpath mode per field.
Example:spath input=doc path=user.name output=uname | spath input=doc path=user.age output=age | ...
- Generic workaround: materialize nested MAP values via
-
PRs related:
Metadata
Metadata
Assignees
Type
Projects
- StatusShow more project fieldsDone
Activity
dai-chen commentedon Feb 17, 2026
Impact Analysis
Impacted Commands (10 total)
getRowType().getFieldNames()or uses string-basedrelBuilder.field(name)lookup; MAP sub-paths likedoc.user.nameare invisible because onlydocexists in the row type.rexVisitor.analyze()correctly, but output column gets wrong name because AST lacksAliaswrapping.visitChildren()or uses string-basedrelBuilder.field(name)in internal helpers that run after materialization, so centralized path resolution is never reached.Category A — Symbol-based commands (6 commands)
matchFieldNames()misses MAP paths. Wildcarddoc.user.*unsolvable at plan timerexVisitor.analyze()fallback, project ITEM() with new alias. Wildcard: document as limitationequalsIgnoreCase()on field list skipsdoc.user.namesilentlyrexVisitor.analyze()+ COALESCE on ITEM()relBuilder.field(name)throws andcontains()misses MAP sub-pathsrexVisitor.analyze(), apply replace on ITEM() resultprojectExceptreceives AS(ITEM()) which doesn't match any physical field by identity, so nothing gets excluded (silent no-op). WC:expandWildcardPatternmisses MAP pathsshouldAggregateFieldstring match miss MAP sub-pathsrexVisitor.analyze()isInputRef()check fails because ITEM() is not an InputRefCategory B — Missing Alias wrapping (1 command)
getGroupByList()returns raw Fields withoutAliaswrapping, so output columns get auto-generated namesAliasinAstBuilder.getGroupByList(), matchinggetPartitionExprList()patternCategory C — Fragmented resolve API (3 commands)
analyzeFieldsForLookUp()usesrelBuilder.field(2, stackPos, fieldName)which is string-based. Source-side materialization viagetOperands()works, but the string-based lookup inaddJoinForLookUpstill failsanalyzeFieldsForLookUpwithrexVisitor.analyze()orQualifiedNameResolverfor source-side fieldsextractGroupFieldName()gets raw string name, thenrelBuilder.field(groupName)fails. AffectsbuildGroupFilter()andbuildRequiredLeft(). Default window-function path is saferelBuilder.field()withrexVisitor.analyze()inbuildGroupFilterandbuildRequiredLeftchildren.forEach(c -> analyze(c, context))bypassesvisitChildren()entirely.buildJoinConditionByFieldName→analyzeFieldsForLookUpuses string-based lookup. Both sides need materializationvisitChildren()or add per-side materialization; replace string-based field lookup in join condition builderSeparate Issues (not MAP path resolution)
shouldOverrideFieldincorrectly removes MAP root columndocwhen addingdoc.user.namebecause"doc.user.name".startsWith("doc.")matchesdoc), not the spath-transformed pipeline (MAPdoc).INTERNAL_ITEMrejects STRING inputConfirmed Safe Commands (19 total)
All of these correctly resolve MAP sub-paths via
rexVisitor.analyze()andQualifiedNameResolver:rexVisitor.analyze()Alias-wrapped by parser. Multiple dotted paths fail due to separateshouldOverrideFieldbug (see above)getPartitionExprList()wraps group-by inAliasrexVisitor.analyze()rexVisitor.analyze()spathcommand #5149, ITEM aliased at projectiongetPartitionExprList()wraps inAlias; group-by usesrexVisitor.analyze()(notextractGroupFieldName)visitAggregationwithgetPartitionExprList()(Alias-wrapped); tested and confirmed workingrexVisitor.analyze(), output names from regex groupsrexVisitor.analyze()Alias-wrapped, pattern field is flatrexVisitor.analyze()rexVisitor.analyze()flatten doc(MAP root) works correctly. Flatten on MAP sub-path is semantically invalid (value is VARCHAR, not struct)fieldsprojects MAP sub-paths as flat columns. Direct transpose on MAP column fails due to MAP-to-VARCHAR type incompatibility, not path resolution(RexInputRef)cast error is a code quality issue but fixing it just changes the error messageNote:
fieldsummarydoes not exist in the Calcite engine (no visitor method).dai-chen commentedon Feb 18, 2026
Technical Deep Dive
Summary
The following table summarizes the root cause and potential solutions for each of the three failure categories identified in the Impact Analysis above:
doc), so MAP sub-paths likedoc.user.nameare never matched.rename,replace,fillnull,fields -,addtotals,mvcombineRexNode, write back viaITEM_SET)2. Central symbol-table API (
QualifiedNameResolver) that resolves dotted paths against MAP roots3. Pre-materialize MAP paths as temporary columns before command logic
4. Document as unsupported; users materialize with
evalor per-fieldspathFieldnodes returned withoutAliaswrapping, so output columns get auto-generated names instead of the user-visible dotted path.top,rareAlias(name, field)ingetGroupByList(), matching the pattern already used bygetPartitionExprList()2. Pre-materialize MAP paths (A-3) also fixes this by making sub-paths available as top-level columns
relBuilder.field(name)directly, so centralized path resolution never triggers.join(field-list),streamstats(correlate path),lookupbuildJoinConditionByFieldName,buildGroupFilter,analyzeFieldsForLookUp)2. Pre-materialize MAP paths (A-3) also fixes this by ensuring sub-paths exist as top-level columns before any command runs
Category A — Semantic mismatch in symbol-based commands
rename,replace, andfillnulltreat their field arguments as symbols that must already exist as top-level schema fields. Afterspathauto-extract, only the MAP root (for example,doc) exists in the row schema. This is why exposingelement_at(...)/ bracket access doesn't help.ALTER ... column), while PPL has more pipeline commands that manipulate field-symbol lists directly.Failure example: replace command
// Schema after spath: getFieldNames() = ["doc"] (doc is MAP) // User query: replace 'John' WITH 'Jonathan' IN doc.user.name @Override public RelNode visitReplace(Replace node, CalcitePlanContext context) { List fieldNames = context.relBuilder.peek().getRowType().getFieldNames(); // fieldNames = ["doc"] for (String fieldToReplace : fieldsToReplace) { context.relBuilder.field(fieldToReplace); // throws: "doc.user.name" not in schema } // Even if validation passed, this loop also fails for (String fieldName : fieldNames) { // iterates ["doc"] if (fieldsToReplace.contains(fieldName)) { // "doc.user.name".contains("doc") → false RexNode fieldRef = context.relBuilder.field(fieldName); // ... apply replacement ... projectList.add(fieldRef); } else { projectList.add(context.relBuilder.field(fieldName)); } } context.relBuilder.project(projectList, fieldNames); }Potential solutions
Idea: Refactor commands like
rename/replace/fillnullto resolve field references as expressions (RexNode) instead of requiring field symbols, so MAP paths can be handled natively.Pros & Cons: Future-proof (aligns symbol-based commands with expression-capable behavior, but requires per-command refactoring and can be costly for commands deeply built around field-name lists or
RexInputRefassumptions.if (fieldExpr.getKind() == SqlKind.ITEM) { // Write back into MAP: doc = ITEM_SET(doc, 'user.name', replaced) RexNode mapRoot = ((RexCall) fieldExpr).getOperands().get(0); // doc RexNode path = ((RexCall) fieldExpr).getOperands().get(1); // 'user.name' RexNode updated = rexBuilder.makeCall(ITEM_SET, mapRoot, path, replaced); // Project: override "doc" column with updated MAP projectPlusOverriding(context, updated, "doc"); } else { // Flat field: project in-place as today projectList.add(replaced); }Idea: Keep command semantics symbol-oriented, but stop doing ad hoc field-name iteration/string lookup in each command; instead, use a shared API that can resolve top-level fields and path-backed “virtual fields” consistently.
Pros & Cons: Improves consistency and maintainability across commands, but still requires each command migration to the shared API, and it does not prevent future commands that bypass it unintentionally.
for (field in fieldList) { // BEFORE: string equality — fails when userField="doc.user.name", field.getName()="doc" // if (field.getName().equalsIgnoreCase(userField)) { // if (fieldsToReplace.contains(field.getName())) { // AFTER: resolve API — matches "doc.user.name" against "doc" via MAP path resolution Optional resolved = QualifiedNameResolver.resolve(userField, field.getName(), context); if (resolved.isPresent()) { RexNode target = resolved.get(); // ITEM(doc, 'user.name') or direct fieldRef }Idea: Internally resolve required paths (for example,
doc.user.name), project them to temporary columns, then run the existing symbol-based logic on those temporary fields.Cons: Adds extra projections and temporary-column complexity, and can become a workaround-heavy design if overused.
// In UnresolvedPlan: /** * Returns the input expressions this command operates on. * Each command returns its full operand expressions — the consumer * decides how to interpret them. */ public abstract List<UnresolvedExpression> getOperands(); // Rename — returns the Map (origin→target pairs): @Override public List getOperands() { return renameList.stream().map(m -> (UnresolvedExpression) m).collect(toList()); } // In CalciteRelNodeVisitor: @Override public RelNode visitChildren(Node node, CalcitePlanContext context) { RelNode result = super.visitChildren(node, context); if (node instanceof UnresolvedPlan plan) { materializeMapPathsIfNeeded(plan, context); } return result; }Idea: Document the limitation clearly and rely on user-side workarounds (
evalmaterialization / chainedspath).Pros & Cons: Fastest and lowest-risk option with clear boundaries, but preserves UX inconsistency and leaves users with command-specific behavior differences.
Category B — Missing Alias wrapping causes wrong output column names
Commands like
top,rare, andchartresolve MAP sub-paths correctly viarexVisitor.analyze()during aggregation, but the output columns get auto-generated names instead of the user-visible dotted path. The root cause is inAstBuilder.getGroupByList()which returns rawFieldnodes withoutAliaswrapping, unlikegetPartitionExprList()used bystats/eventstatswhich wraps each field inAlias(name, field).Failure example: top command
// User query: source=t | spath input=doc | top 2 doc.user.name // In AstBuilder — getGroupByList() returns raw Fields (no Alias): private List<UnresolvedExpression> getGroupByList(ByClauseContext ctx) { return ctx.fieldList().fieldExpression().stream() .map(this::internalVisitExpression) // ← raw Field, no Alias wrapping .collect(Collectors.toList()); }Potential solutions
Solution 1 — Wrap group-by fields in
Alias(direct fix)Idea: In
AstBuilder.getGroupByList(), wrap each field expression withAlias(name, field)before returning, matching the pattern already used bygetPartitionExprList().Pros & Cons: Minimal, surgical one-line change using a proven pattern that already works for
stats/eventstats. However, it only fixes column naming for this specific code path and doesn't prevent similar raw-field issues in future commands.Solution 2 — Pre-materialize MAP paths (A-3)
Idea: Temporary columns are projected with correct names before command logic runs, so even raw
Fieldnodes resolve to properly named top-level columns.Pros & Cons: Fixes naming and resolution uniformly across all commands in one shot, but is a heavier approach for what is otherwise a one-line Alias fix and adds extra projection steps.
Category C — Fragmented resolve API bypasses centralized path resolution
Some commands bypass the standard
visitChildren()→materializeMapPathsIfNeeded()flow by callinganalyze(child, context)directly on their children, or by using string-basedrelBuilder.field(name)in internal helper methods that run after the materialization step. This means even ifgetOperands()is implemented, the materialization never triggers or the command's internal logic still uses raw string lookups.Affected commands:
children.forEach(c -> analyze(c, context))bypassesvisitChildren()entirely;buildJoinConditionByFieldName→analyzeFieldsForLookUpuses string-basedrelBuilder.field(2, pos, name)extractGroupFieldName()extracts raw string name, thenbuildGroupFilter/buildRequiredLeftuserelBuilder.field(name)string lookup against post-transformation schemaanalyze(node.getLookupRelation(), context)bypassesvisitChildren()for the lookup table side;analyzeFieldsForLookUpuses string-basedrelBuilder.field(2, pos, name)for both sidesFailure example: streamstats command
// User query: source=t | spath input=doc // | streamstats window=2 global=true count() as cnt by doc.user.name // buildGroupFilter uses string-based lookup: private RexNode buildGroupFilter(...) { groupList.stream().map(expr -> { String groupName = extractGroupFieldName(expr); // "doc.user.name" RexNode rightGroup = context.relBuilder.field(groupName); // throws: not in schema RexNode outerGroup = context.relBuilder.field(correl, groupName); return context.relBuilder.equals(rightGroup, outerGroup); }); }Potential solutions
Solution 1 — Route through centralized resolve API (direct fix)
Idea: Replace direct
relBuilder.field(name)calls in each bypassing helper with the centralized resolver, so MAP paths are resolved consistently.Pros & Cons: Fixes the root cause per-command and keeps resolution logic in one place. However, requires per-command refactoring since each helper has different call patterns (
field(2, pos, name)in join/lookup vsfield(name)in streamstats vs correlate variables).Solution 2 — Pre-materialize MAP paths (A-3)
Idea: Because materialization happens before command logic, even direct
relBuilder.field("doc.user.name")succeeds since the column now exists as a top-level field in the schema.Pros & Cons: Bypassing helpers work as-is without any per-command changes, but adds extra projection steps and leave the command as is (technical debt remains even if functional behavior is correct).
evaloverwrites MAP root field when assigning multiple dotted-path names #5185appendcolsubquery cannot resolve MAP sub-paths #5186dai-chen commentedon Feb 27, 2026
Proof of Concept: Pre-materializing MAP Paths
Summary
This proof of concept validates that pre-materializing referenced MAP sub-paths before command-specific planning (Solution A3 above). The PoC shows that this approach is technically viable and provides a uniform behavioral fix. However, it also reveals an architectural limitation: PPL V3 currently lacks a dedicated analysis phase.
As a result, the PoC places a new operand-declaration contract on AST nodes as well as schema-enrichment inside the RelNode visitor. While this is effective as a practical workaround, it is not an ideal long-term design. Based on these findings, the current decision is to minimize code changes on existing command implementation and defer broader architectural follow-up to future design work:
PoC Approach
In this PoC, each AST node declares its input field operands through
getOperands(). DuringCalciteRelNodeVisitor.visitChildren(), and before a command-specific visitXxx() method runs, a resolver performs the following steps:getOperandsAPI.QualifiedNameResolverand check whether it resolves to anITEM()expression.PoC Results
As a result, downstream command logic can continue to work against an enriched schema where referenced MAP sub-paths appear as ordinary fields. The PoC fixes all three failure categories in a consistent way below.
Category A: Symbol-based command - replace
Category B: Missing alias wrapping - top/rare
Category C: Fragmented resolve API - join
Implementation Options
Part 1: How to Extract Field Operands from AST Nodes
The materializer needs to know which
Fieldreferences a command operates on.Two approaches:
extractFieldOperandsmethod inMapPathPreMaterializerpattern-matches on the concreteUnresolvedPlansubclass and calls the appropriate gettergetFieldOperands()contract on AST nodes — Each command node exposes its referenced fields via a common interface methodgetFieldOperands()default method toUnresolvedPlan(returningList.of()) and override it in each command that references symbol-based fieldsSqlCall.getOperandList(), which provides a uniform way to access operands across all SQL call typesUnresolvedPlansubclass inherits the method (even if irrelevant); extraction logic is scattered across AST classes instead of centralized; some commands have non-trivial extraction (e.g.,Renameneedsm.getOrigin(),Projectonly when excluded) which may not fit a simpleList<Field>return type cleanlyPart 2: Where to Trigger Materialization
visitChildrento auto-materialize for every nodevisitChildreninCalciteRelNodeVisitor; callmaterializePaths()aftersuper.visitChildren()returnsinstanceof UnresolvedPlan+ per-command switch inextractFieldOperandsvisitChildrento be pure traversalextractFieldOperandsreturns empty for unrecognized commandsvisit*method calls the materializer directlyvisitChildrenoverride; addmapPathMaterializer.materializePaths(node, context)aftervisitChildren(node, context)in each of the 6 affected methods (visitRename,visitFillNull,visitReplace,visitProject,visitAddTotals,visitMvCombine)visitChildrenstays pure; no overhead for unrelated commandsextractFieldOperandsswitchvisitChildrenWithMaterialization(UnresolvedPlan, CalcitePlanContext)helper that callsvisitChildrenthenmaterializePathsvisit*method calls this helper instead ofvisitChildrendirectlyvisitChildrenstays pure (no override); materialization is opt-in per command; logic centralized in one helper +MapPathPreMaterializer; easy to discover via grep