@@ -571,7 +571,7 @@ private void resolveInferences(
571571 }
572572
573573 static PreAnalysisResult fieldNames (LogicalPlan parsed , Set <String > enrichPolicyMatchFields , PreAnalysisResult result ) {
574- if (false == parsed .anyMatch (plan -> plan instanceof Aggregate || plan instanceof Project )) {
574+ if (false == parsed .anyMatch (EsqlSession :: shouldCollectReferencedFields )) {
575575 // no explicit columns selection, for example "from employees"
576576 return result .withFieldNames (IndexResolver .ALL_FIELDS );
577577 }
@@ -592,14 +592,18 @@ static PreAnalysisResult fieldNames(LogicalPlan parsed, Set<String> enrichPolicy
592592 Holder <Boolean > hasFork = new Holder <>(false );
593593
594594 parsed .forEachDown (plan -> {
595- if (hasFork .get () == false && (plan instanceof Project || plan instanceof Aggregate )) {
595+ if (projectAll .get ()) {
596+ return ;
597+ }
598+
599+ if (hasFork .get () == false && shouldCollectReferencedFields (plan )) {
596600 projectAfterFork .set (true );
597601 }
598602
599603 if (plan instanceof Fork fork && projectAfterFork .get () == false ) {
600604 hasFork .set (true );
601605 fork .children ().forEach (child -> {
602- if (child .anyMatch (p -> p instanceof Project || p instanceof Aggregate ) == false ) {
606+ if (child .anyMatch (EsqlSession :: shouldCollectReferencedFields ) == false ) {
603607 projectAll .set (true );
604608 }
605609 });
@@ -722,6 +726,13 @@ static PreAnalysisResult fieldNames(LogicalPlan parsed, Set<String> enrichPolicy
722726 }
723727 }
724728
729+ /**
730+ * Indicates whether the given plan gives an exact list of fields that we need to collect from field_caps.
731+ */
732+ private static boolean shouldCollectReferencedFields (LogicalPlan plan ) {
733+ return plan instanceof Aggregate || plan instanceof Project ;
734+ }
735+
725736 /**
726737 * Could a plan "accidentally" override aliases?
727738 * Examples are JOIN and ENRICH, that _could_ produce fields with the same
0 commit comments