forked from elastic/elasticsearch
/
Optimizer.java
1933 lines (1613 loc) · 77.2 KB
/
Optimizer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.sql.optimizer;
import org.elasticsearch.xpack.sql.SqlIllegalArgumentException;
import org.elasticsearch.xpack.sql.expression.Alias;
import org.elasticsearch.xpack.sql.expression.Attribute;
import org.elasticsearch.xpack.sql.expression.AttributeMap;
import org.elasticsearch.xpack.sql.expression.AttributeSet;
import org.elasticsearch.xpack.sql.expression.Expression;
import org.elasticsearch.xpack.sql.expression.ExpressionId;
import org.elasticsearch.xpack.sql.expression.ExpressionSet;
import org.elasticsearch.xpack.sql.expression.Expressions;
import org.elasticsearch.xpack.sql.expression.FieldAttribute;
import org.elasticsearch.xpack.sql.expression.Literal;
import org.elasticsearch.xpack.sql.expression.NamedExpression;
import org.elasticsearch.xpack.sql.expression.Order;
import org.elasticsearch.xpack.sql.expression.function.Function;
import org.elasticsearch.xpack.sql.expression.function.FunctionAttribute;
import org.elasticsearch.xpack.sql.expression.function.Functions;
import org.elasticsearch.xpack.sql.expression.function.aggregate.AggregateFunction;
import org.elasticsearch.xpack.sql.expression.function.aggregate.AggregateFunctionAttribute;
import org.elasticsearch.xpack.sql.expression.function.aggregate.ExtendedStats;
import org.elasticsearch.xpack.sql.expression.function.aggregate.ExtendedStatsEnclosed;
import org.elasticsearch.xpack.sql.expression.function.aggregate.InnerAggregate;
import org.elasticsearch.xpack.sql.expression.function.aggregate.MatrixStats;
import org.elasticsearch.xpack.sql.expression.function.aggregate.MatrixStatsEnclosed;
import org.elasticsearch.xpack.sql.expression.function.aggregate.Percentile;
import org.elasticsearch.xpack.sql.expression.function.aggregate.PercentileRank;
import org.elasticsearch.xpack.sql.expression.function.aggregate.PercentileRanks;
import org.elasticsearch.xpack.sql.expression.function.aggregate.Percentiles;
import org.elasticsearch.xpack.sql.expression.function.aggregate.Stats;
import org.elasticsearch.xpack.sql.expression.function.scalar.Cast;
import org.elasticsearch.xpack.sql.expression.function.scalar.ScalarFunction;
import org.elasticsearch.xpack.sql.expression.function.scalar.ScalarFunctionAttribute;
import org.elasticsearch.xpack.sql.expression.predicate.BinaryOperator;
import org.elasticsearch.xpack.sql.expression.predicate.BinaryOperator.Negateable;
import org.elasticsearch.xpack.sql.expression.predicate.BinaryPredicate;
import org.elasticsearch.xpack.sql.expression.predicate.IsNotNull;
import org.elasticsearch.xpack.sql.expression.predicate.Predicates;
import org.elasticsearch.xpack.sql.expression.predicate.Range;
import org.elasticsearch.xpack.sql.expression.predicate.logical.And;
import org.elasticsearch.xpack.sql.expression.predicate.logical.Not;
import org.elasticsearch.xpack.sql.expression.predicate.logical.Or;
import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparison;
import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.Equals;
import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.GreaterThan;
import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.GreaterThanOrEqual;
import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.In;
import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.LessThan;
import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.LessThanOrEqual;
import org.elasticsearch.xpack.sql.plan.logical.Aggregate;
import org.elasticsearch.xpack.sql.plan.logical.EsRelation;
import org.elasticsearch.xpack.sql.plan.logical.Filter;
import org.elasticsearch.xpack.sql.plan.logical.Limit;
import org.elasticsearch.xpack.sql.plan.logical.LocalRelation;
import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan;
import org.elasticsearch.xpack.sql.plan.logical.OrderBy;
import org.elasticsearch.xpack.sql.plan.logical.Project;
import org.elasticsearch.xpack.sql.plan.logical.SubQueryAlias;
import org.elasticsearch.xpack.sql.rule.Rule;
import org.elasticsearch.xpack.sql.rule.RuleExecutor;
import org.elasticsearch.xpack.sql.session.EmptyExecutable;
import org.elasticsearch.xpack.sql.session.SingletonExecutable;
import org.elasticsearch.xpack.sql.type.DataType;
import org.elasticsearch.xpack.sql.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import static java.util.stream.Collectors.toList;
import static org.elasticsearch.xpack.sql.expression.Literal.FALSE;
import static org.elasticsearch.xpack.sql.expression.Literal.TRUE;
import static org.elasticsearch.xpack.sql.expression.predicate.Predicates.combineAnd;
import static org.elasticsearch.xpack.sql.expression.predicate.Predicates.combineOr;
import static org.elasticsearch.xpack.sql.expression.predicate.Predicates.inCommon;
import static org.elasticsearch.xpack.sql.expression.predicate.Predicates.splitAnd;
import static org.elasticsearch.xpack.sql.expression.predicate.Predicates.splitOr;
import static org.elasticsearch.xpack.sql.expression.predicate.Predicates.subtract;
import static org.elasticsearch.xpack.sql.util.CollectionUtils.combine;
public class Optimizer extends RuleExecutor<LogicalPlan> {
public ExecutionInfo debugOptimize(LogicalPlan verified) {
return verified.optimized() ? null : executeWithInfo(verified);
}
public LogicalPlan optimize(LogicalPlan verified) {
return verified.optimized() ? verified : execute(verified);
}
@Override
protected Iterable<RuleExecutor<LogicalPlan>.Batch> batches() {
Batch resolution = new Batch("Finish Analysis",
new PruneSubqueryAliases(),
CleanAliases.INSTANCE
);
Batch aggregate = new Batch("Aggregation",
new PruneDuplicatesInGroupBy(),
new ReplaceDuplicateAggsWithReferences(),
new ReplaceAggsWithMatrixStats(),
new ReplaceAggsWithExtendedStats(),
new ReplaceAggsWithStats(),
new PromoteStatsToExtendedStats(),
new ReplaceAggsWithPercentiles(),
new ReplaceAggsWithPercentileRanks()
);
Batch operators = new Batch("Operator Optimization",
// combining
new CombineProjections(),
// folding
new ReplaceFoldableAttributes(),
new FoldNull(),
new ConstantFolding(),
// boolean
new BooleanSimplification(),
new BooleanLiteralsOnTheRight(),
new BinaryComparisonSimplification(),
// needs to occur before BinaryComparison combinations (see class)
new PropagateEquals(),
new CombineBinaryComparisons(),
// prune/elimination
new PruneFilters(),
new PruneOrderBy(),
new PruneOrderByNestedFields(),
new PruneCast(),
// order by alignment of the aggs
new SortAggregateOnOrderBy()
// requires changes in the folding
// since the exact same function, with the same ID can appear in multiple places
// see https://github.com/elastic/x-pack-elasticsearch/issues/3527
//new PruneDuplicateFunctions()
);
Batch local = new Batch("Skip Elasticsearch",
new SkipQueryOnLimitZero(),
new SkipQueryIfFoldingProjection()
);
//new BalanceBooleanTrees());
Batch label = new Batch("Set as Optimized", Limiter.ONCE,
new SetAsOptimized());
return Arrays.asList(resolution, aggregate, operators, local, label);
}
static class PruneSubqueryAliases extends OptimizerRule<SubQueryAlias> {
PruneSubqueryAliases() {
super(TransformDirection.UP);
}
@Override
protected LogicalPlan rule(SubQueryAlias alias) {
return alias.child();
}
}
static class CleanAliases extends OptimizerRule<LogicalPlan> {
private static final CleanAliases INSTANCE = new CleanAliases();
CleanAliases() {
super(TransformDirection.UP);
}
@Override
protected LogicalPlan rule(LogicalPlan plan) {
if (plan instanceof Project) {
Project p = (Project) plan;
return new Project(p.location(), p.child(), cleanExpressions(p.projections()));
}
if (plan instanceof Aggregate) {
Aggregate a = (Aggregate) plan;
// clean group expressions
List<Expression> cleanedGroups = a.groupings().stream().map(CleanAliases::trimAliases).collect(toList());
return new Aggregate(a.location(), a.child(), cleanedGroups, cleanExpressions(a.aggregates()));
}
return plan.transformExpressionsOnly(e -> {
if (e instanceof Alias) {
return ((Alias) e).child();
}
return e;
});
}
private List<NamedExpression> cleanExpressions(List<? extends NamedExpression> args) {
return args.stream().map(CleanAliases::trimNonTopLevelAliases).map(NamedExpression.class::cast)
.collect(toList());
}
static Expression trimNonTopLevelAliases(Expression e) {
if (e instanceof Alias) {
Alias a = (Alias) e;
return new Alias(a.location(), a.name(), a.qualifier(), trimAliases(a.child()), a.id());
}
return trimAliases(e);
}
private static Expression trimAliases(Expression e) {
return e.transformDown(Alias::child, Alias.class);
}
}
static class PruneDuplicatesInGroupBy extends OptimizerRule<Aggregate> {
@Override
protected LogicalPlan rule(Aggregate agg) {
List<Expression> groupings = agg.groupings();
if (groupings.isEmpty()) {
return agg;
}
ExpressionSet<Expression> unique = new ExpressionSet<>(groupings);
if (unique.size() != groupings.size()) {
return new Aggregate(agg.location(), agg.child(), new ArrayList<>(unique), agg.aggregates());
}
return agg;
}
}
static class ReplaceDuplicateAggsWithReferences extends OptimizerRule<Aggregate> {
@Override
protected LogicalPlan rule(Aggregate agg) {
List<? extends NamedExpression> aggs = agg.aggregates();
Map<Expression, NamedExpression> unique = new HashMap<>();
Map<NamedExpression, Expression> reverse = new HashMap<>();
// find duplicates by looking at the function and canonical form
for (NamedExpression ne : aggs) {
if (ne instanceof Alias) {
Alias a = (Alias) ne;
unique.putIfAbsent(a.child(), a);
reverse.putIfAbsent(ne, a.child());
}
else {
unique.putIfAbsent(ne.canonical(), ne);
reverse.putIfAbsent(ne, ne.canonical());
}
}
if (unique.size() != aggs.size()) {
List<NamedExpression> newAggs = new ArrayList<>(aggs.size());
for (NamedExpression ne : aggs) {
newAggs.add(unique.get(reverse.get(ne)));
}
return new Aggregate(agg.location(), agg.child(), agg.groupings(), newAggs);
}
return agg;
}
}
static class ReplaceAggsWithMatrixStats extends Rule<LogicalPlan, LogicalPlan> {
@Override
public LogicalPlan apply(LogicalPlan p) {
Map<Expression, MatrixStats> seen = new LinkedHashMap<>();
Map<String, AggregateFunctionAttribute> promotedFunctionIds = new LinkedHashMap<>();
p = p.transformExpressionsUp(e -> rule(e, seen, promotedFunctionIds));
// nothing found
if (seen.isEmpty()) {
return p;
}
return ReplaceAggsWithStats.updateAggAttributes(p, promotedFunctionIds);
}
@Override
protected LogicalPlan rule(LogicalPlan e) {
return e;
}
protected Expression rule(Expression e, Map<Expression, MatrixStats> seen, Map<String, AggregateFunctionAttribute> promotedIds) {
if (e instanceof MatrixStatsEnclosed) {
AggregateFunction f = (AggregateFunction) e;
Expression argument = f.field();
MatrixStats matrixStats = seen.get(argument);
if (matrixStats == null) {
matrixStats = new MatrixStats(f.location(), argument);
seen.put(argument, matrixStats);
}
InnerAggregate ia = new InnerAggregate(f.location(), f, matrixStats, f.field());
promotedIds.putIfAbsent(f.functionId(), ia.toAttribute());
return ia;
}
return e;
}
}
static class ReplaceAggsWithExtendedStats extends Rule<LogicalPlan, LogicalPlan> {
@Override
public LogicalPlan apply(LogicalPlan p) {
Map<String, AggregateFunctionAttribute> promotedFunctionIds = new LinkedHashMap<>();
Map<Expression, ExtendedStats> seen = new LinkedHashMap<>();
p = p.transformExpressionsUp(e -> rule(e, seen, promotedFunctionIds));
// nothing found
if (seen.isEmpty()) {
return p;
}
// update old agg attributes
return ReplaceAggsWithStats.updateAggAttributes(p, promotedFunctionIds);
}
@Override
protected LogicalPlan rule(LogicalPlan e) {
return e;
}
protected Expression rule(Expression e, Map<Expression, ExtendedStats> seen,
Map<String, AggregateFunctionAttribute> promotedIds) {
if (e instanceof ExtendedStatsEnclosed) {
AggregateFunction f = (AggregateFunction) e;
Expression argument = f.field();
ExtendedStats extendedStats = seen.get(argument);
if (extendedStats == null) {
extendedStats = new ExtendedStats(f.location(), argument);
seen.put(argument, extendedStats);
}
InnerAggregate ia = new InnerAggregate(f, extendedStats);
promotedIds.putIfAbsent(f.functionId(), ia.toAttribute());
return ia;
}
return e;
}
}
static class ReplaceAggsWithStats extends Rule<LogicalPlan, LogicalPlan> {
private static class Match {
final Stats stats;
int count = 1;
final Set<Class<? extends AggregateFunction>> functionTypes = new LinkedHashSet<>();
Match(Stats stats) {
this.stats = stats;
}
@Override
public String toString() {
return stats.toString();
}
}
@Override
public LogicalPlan apply(LogicalPlan p) {
Map<Expression, Match> potentialPromotions = new LinkedHashMap<>();
p.forEachExpressionsUp(e -> collect(e, potentialPromotions));
// no promotions found - skip
if (potentialPromotions.isEmpty()) {
return p;
}
// start promotion
// old functionId to new function attribute
Map<String, AggregateFunctionAttribute> promotedFunctionIds = new LinkedHashMap<>();
// 1. promote aggs to InnerAggs
p = p.transformExpressionsUp(e -> promote(e, potentialPromotions, promotedFunctionIds));
// 2. update the old agg attrs to the promoted agg functions
return updateAggAttributes(p, promotedFunctionIds);
}
@Override
protected LogicalPlan rule(LogicalPlan e) {
return e;
}
private Expression collect(Expression e, Map<Expression, Match> seen) {
if (Stats.isTypeCompatible(e)) {
AggregateFunction f = (AggregateFunction) e;
Expression argument = f.field();
Match match = seen.get(argument);
if (match == null) {
match = new Match(new Stats(f.location(), argument));
match.functionTypes.add(f.getClass());
seen.put(argument, match);
}
else {
if (match.functionTypes.add(f.getClass())) {
match.count++;
}
}
}
return e;
}
private static Expression promote(Expression e, Map<Expression, Match> seen, Map<String, AggregateFunctionAttribute> attrs) {
if (Stats.isTypeCompatible(e)) {
AggregateFunction f = (AggregateFunction) e;
Expression argument = f.field();
Match counter = seen.get(argument);
// if the stat has at least two different functions for it, promote it as stat
if (counter != null && counter.count > 1) {
InnerAggregate innerAgg = new InnerAggregate(f, counter.stats);
attrs.putIfAbsent(f.functionId(), innerAgg.toAttribute());
return innerAgg;
}
}
return e;
}
static LogicalPlan updateAggAttributes(LogicalPlan p, Map<String, AggregateFunctionAttribute> promotedFunctionIds) {
// 1. update old agg function attributes
p = p.transformExpressionsUp(e -> updateAggFunctionAttrs(e, promotedFunctionIds));
// 2. update all scalar function consumers of the promoted aggs
// since they contain the old ids in scrips and processorDefinitions that need regenerating
// 2a. collect ScalarFunctions that unwrapped refer to any of the updated aggregates
// 2b. replace any of the old ScalarFunction attributes
final Set<String> newAggIds = new LinkedHashSet<>(promotedFunctionIds.size());
for (AggregateFunctionAttribute afa : promotedFunctionIds.values()) {
newAggIds.add(afa.functionId());
}
final Map<String, ScalarFunctionAttribute> updatedScalarAttrs = new LinkedHashMap<>();
final Map<ExpressionId, ScalarFunctionAttribute> updatedScalarAliases = new LinkedHashMap<>();
p = p.transformExpressionsUp(e -> {
// replace scalar attributes of the old replaced functions
if (e instanceof ScalarFunctionAttribute) {
ScalarFunctionAttribute sfa = (ScalarFunctionAttribute) e;
// check aliases
sfa = updatedScalarAttrs.getOrDefault(sfa.functionId(), sfa);
// check scalars
sfa = updatedScalarAliases.getOrDefault(sfa.id(), sfa);
return sfa;
}
// unwrap aliases as they 'hide' functions under their own attributes
if (e instanceof Alias) {
Attribute att = Expressions.attribute(e);
if (att instanceof ScalarFunctionAttribute) {
ScalarFunctionAttribute sfa = (ScalarFunctionAttribute) att;
// the underlying function has been updated
// thus record the alias as well
if (updatedScalarAttrs.containsKey(sfa.functionId())) {
updatedScalarAliases.put(sfa.id(), sfa);
}
}
}
else if (e instanceof ScalarFunction) {
ScalarFunction sf = (ScalarFunction) e;
// if it's a unseen function check if the function children/arguments refers to any of the promoted aggs
if (!updatedScalarAttrs.containsKey(sf.functionId()) && e.anyMatch(c -> {
Attribute a = Expressions.attribute(c);
if (a instanceof FunctionAttribute) {
return newAggIds.contains(((FunctionAttribute) a).functionId());
}
return false;
})) {
// if so, record its attribute
updatedScalarAttrs.put(sf.functionId(), sf.toAttribute());
}
}
return e;
});
return p;
}
private static Expression updateAggFunctionAttrs(Expression e, Map<String, AggregateFunctionAttribute> promotedIds) {
if (e instanceof AggregateFunctionAttribute) {
AggregateFunctionAttribute ae = (AggregateFunctionAttribute) e;
AggregateFunctionAttribute promoted = promotedIds.get(ae.functionId());
if (promoted != null) {
return ae.withFunctionId(promoted.functionId(), promoted.propertyPath());
}
}
return e;
}
}
static class PromoteStatsToExtendedStats extends Rule<LogicalPlan, LogicalPlan> {
@Override
public LogicalPlan apply(LogicalPlan p) {
Map<Expression, ExtendedStats> seen = new LinkedHashMap<>();
// count the extended stats
p.forEachExpressionsUp(e -> count(e, seen));
// then if there's a match, replace the stat inside the InnerAgg
return p.transformExpressionsUp(e -> promote(e, seen));
}
@Override
protected LogicalPlan rule(LogicalPlan e) {
return e;
}
private void count(Expression e, Map<Expression, ExtendedStats> seen) {
if (e instanceof InnerAggregate) {
InnerAggregate ia = (InnerAggregate) e;
if (ia.outer() instanceof ExtendedStats) {
ExtendedStats extStats = (ExtendedStats) ia.outer();
seen.putIfAbsent(extStats.field(), extStats);
}
}
}
protected Expression promote(Expression e, Map<Expression, ExtendedStats> seen) {
if (e instanceof InnerAggregate) {
InnerAggregate ia = (InnerAggregate) e;
if (ia.outer() instanceof Stats) {
Stats stats = (Stats) ia.outer();
ExtendedStats ext = seen.get(stats.field());
if (ext != null && stats.field().equals(ext.field())) {
return new InnerAggregate(ia.inner(), ext);
}
}
}
return e;
}
}
static class ReplaceAggsWithPercentiles extends Rule<LogicalPlan, LogicalPlan> {
@Override
public LogicalPlan apply(LogicalPlan p) {
// percentile per field/expression
Map<Expression, Set<Expression>> percentsPerField = new LinkedHashMap<>();
// count gather the percents for each field
p.forEachExpressionsUp(e -> count(e, percentsPerField));
Map<Expression, Percentiles> percentilesPerField = new LinkedHashMap<>();
// create a Percentile agg for each field (and its associated percents)
percentsPerField.forEach((k, v) -> {
percentilesPerField.put(k, new Percentiles(v.iterator().next().location(), k, new ArrayList<>(v)));
});
// now replace the agg with pointer to the main ones
Map<String, AggregateFunctionAttribute> promotedFunctionIds = new LinkedHashMap<>();
p = p.transformExpressionsUp(e -> rule(e, percentilesPerField, promotedFunctionIds));
// finally update all the function references as well
return p.transformExpressionsDown(e -> ReplaceAggsWithStats.updateAggFunctionAttrs(e, promotedFunctionIds));
}
private void count(Expression e, Map<Expression, Set<Expression>> percentsPerField) {
if (e instanceof Percentile) {
Percentile p = (Percentile) e;
Expression field = p.field();
Set<Expression> percentiles = percentsPerField.get(field);
if (percentiles == null) {
percentiles = new LinkedHashSet<>();
percentsPerField.put(field, percentiles);
}
percentiles.add(p.percent());
}
}
protected Expression rule(Expression e, Map<Expression, Percentiles> percentilesPerField,
Map<String, AggregateFunctionAttribute> promotedIds) {
if (e instanceof Percentile) {
Percentile p = (Percentile) e;
Percentiles percentiles = percentilesPerField.get(p.field());
InnerAggregate ia = new InnerAggregate(p, percentiles);
promotedIds.putIfAbsent(p.functionId(), ia.toAttribute());
return ia;
}
return e;
}
@Override
protected LogicalPlan rule(LogicalPlan e) {
return e;
}
}
static class ReplaceAggsWithPercentileRanks extends Rule<LogicalPlan, LogicalPlan> {
@Override
public LogicalPlan apply(LogicalPlan p) {
// percentile per field/expression
Map<Expression, Set<Expression>> valuesPerField = new LinkedHashMap<>();
// count gather the percents for each field
p.forEachExpressionsUp(e -> count(e, valuesPerField));
Map<Expression, PercentileRanks> ranksPerField = new LinkedHashMap<>();
// create a PercentileRanks agg for each field (and its associated values)
valuesPerField.forEach((k, v) -> {
ranksPerField.put(k, new PercentileRanks(v.iterator().next().location(), k, new ArrayList<>(v)));
});
// now replace the agg with pointer to the main ones
Map<String, AggregateFunctionAttribute> promotedFunctionIds = new LinkedHashMap<>();
p = p.transformExpressionsUp(e -> rule(e, ranksPerField, promotedFunctionIds));
// finally update all the function references as well
return p.transformExpressionsDown(e -> ReplaceAggsWithStats.updateAggFunctionAttrs(e, promotedFunctionIds));
}
private void count(Expression e, Map<Expression, Set<Expression>> ranksPerField) {
if (e instanceof PercentileRank) {
PercentileRank p = (PercentileRank) e;
Expression field = p.field();
Set<Expression> percentiles = ranksPerField.get(field);
if (percentiles == null) {
percentiles = new LinkedHashSet<>();
ranksPerField.put(field, percentiles);
}
percentiles.add(p.value());
}
}
protected Expression rule(Expression e, Map<Expression, PercentileRanks> ranksPerField,
Map<String, AggregateFunctionAttribute> promotedIds) {
if (e instanceof PercentileRank) {
PercentileRank p = (PercentileRank) e;
PercentileRanks ranks = ranksPerField.get(p.field());
InnerAggregate ia = new InnerAggregate(p, ranks);
promotedIds.putIfAbsent(p.functionId(), ia.toAttribute());
return ia;
}
return e;
}
@Override
protected LogicalPlan rule(LogicalPlan e) {
return e;
}
}
static class PruneFilters extends OptimizerRule<Filter> {
@Override
protected LogicalPlan rule(Filter filter) {
if (filter.condition() instanceof Literal) {
if (TRUE.equals(filter.condition())) {
return filter.child();
}
if (FALSE.equals(filter.condition()) || FoldNull.isNull(filter.condition())) {
return new LocalRelation(filter.location(), new EmptyExecutable(filter.output()));
}
}
return filter;
}
}
static class ReplaceAliasesInHaving extends OptimizerRule<Filter> {
@Override
protected LogicalPlan rule(Filter filter) {
if (filter.child() instanceof Aggregate) {
Expression cond = filter.condition();
// resolve attributes to their actual
Expression newCondition = cond.transformDown(a -> {
return a;
}, AggregateFunctionAttribute.class);
if (newCondition != cond) {
return new Filter(filter.location(), filter.child(), newCondition);
}
}
return filter;
}
}
static class PruneOrderByNestedFields extends OptimizerRule<Project> {
private void findNested(Expression exp, Map<String, Function> functions, Consumer<FieldAttribute> onFind) {
exp.forEachUp(e -> {
if (e instanceof FunctionAttribute) {
FunctionAttribute sfa = (FunctionAttribute) e;
Function f = functions.get(sfa.functionId());
if (f != null) {
findNested(f, functions, onFind);
}
}
if (e instanceof FieldAttribute) {
FieldAttribute fa = (FieldAttribute) e;
if (fa.isNested()) {
onFind.accept(fa);
}
}
});
}
@Override
protected LogicalPlan rule(Project project) {
// check whether OrderBy relies on nested fields which are not used higher up
if (project.child() instanceof OrderBy) {
OrderBy ob = (OrderBy) project.child();
// resolve function aliases (that are hiding the target)
Map<String, Function> functions = Functions.collectFunctions(project);
// track the direct parents
Map<String, Order> nestedOrders = new LinkedHashMap<>();
for (Order order : ob.order()) {
// traverse the tree since the field might be wrapped in a function
findNested(order.child(), functions, fa -> nestedOrders.put(fa.nestedParent().name(), order));
}
// no nested fields in sort
if (nestedOrders.isEmpty()) {
return project;
}
// count the nested parents (if any) inside the parents
List<String> nestedTopFields = new ArrayList<>();
for (NamedExpression ne : project.projections()) {
// traverse the tree since the field might be wrapped in a function
findNested(ne, functions, fa -> nestedTopFields.add(fa.nestedParent().name()));
}
List<Order> orders = new ArrayList<>(ob.order());
// projection has no nested field references, remove any nested orders
if (nestedTopFields.isEmpty()) {
orders.removeAll(nestedOrders.values());
}
else {
// remove orders that are not ancestors of the nested projections
for (Entry<String, Order> entry : nestedOrders.entrySet()) {
String parent = entry.getKey();
boolean shouldKeep = false;
for (String topParent : nestedTopFields) {
if (topParent.startsWith(parent)) {
shouldKeep = true;
break;
}
}
if (!shouldKeep) {
orders.remove(entry.getValue());
}
}
}
// no orders left, eliminate it all-together
if (orders.isEmpty()) {
return new Project(project.location(), ob.child(), project.projections());
}
if (orders.size() != ob.order().size()) {
OrderBy newOrder = new OrderBy(ob.location(), ob.child(), orders);
return new Project(project.location(), newOrder, project.projections());
}
}
return project;
}
}
static class PruneOrderBy extends OptimizerRule<OrderBy> {
@Override
protected LogicalPlan rule(OrderBy ob) {
List<Order> order = ob.order();
// remove constants
List<Order> nonConstant = order.stream().filter(o -> !o.child().foldable()).collect(toList());
if (nonConstant.isEmpty()) {
return ob.child();
}
// if the sort points to an agg, consider it only if there's grouping
if (ob.child() instanceof Aggregate) {
Aggregate a = (Aggregate) ob.child();
if (a.groupings().isEmpty()) {
AttributeSet aggsAttr = new AttributeSet(Expressions.asAttributes(a.aggregates()));
List<Order> nonAgg = nonConstant.stream().filter(o -> {
if (o.child() instanceof NamedExpression) {
return !aggsAttr.contains(((NamedExpression) o.child()).toAttribute());
}
return true;
}).collect(toList());
return nonAgg.isEmpty() ? ob.child() : new OrderBy(ob.location(), ob.child(), nonAgg);
}
}
return ob;
}
}
/**
* Align the order in aggregate based on the order by.
*/
static class SortAggregateOnOrderBy extends OptimizerRule<OrderBy> {
@Override
protected LogicalPlan rule(OrderBy ob) {
List<Order> order = ob.order();
// remove constants
List<Order> nonConstant = order.stream().filter(o -> !o.child().foldable()).collect(toList());
// if the sort points to an agg, change the agg order based on the order
if (ob.child() instanceof Aggregate) {
Aggregate a = (Aggregate) ob.child();
List<Expression> groupings = new ArrayList<>(a.groupings());
boolean orderChanged = false;
for (int orderIndex = 0; orderIndex < nonConstant.size(); orderIndex++) {
Order o = nonConstant.get(orderIndex);
Expression fieldToOrder = o.child();
for (Expression group : a.groupings()) {
if (Expressions.equalsAsAttribute(fieldToOrder, group)) {
// move grouping in front
groupings.remove(group);
groupings.add(orderIndex, group);
orderChanged = true;
}
}
}
if (orderChanged) {
Aggregate newAgg = new Aggregate(a.location(), a.child(), groupings, a.aggregates());
return new OrderBy(ob.location(), newAgg, ob.order());
}
}
return ob;
}
}
static class CombineLimits extends OptimizerRule<Limit> {
@Override
protected LogicalPlan rule(Limit limit) {
if (limit.child() instanceof Limit) {
throw new UnsupportedOperationException("not implemented yet");
}
throw new UnsupportedOperationException("not implemented yet");
}
}
// NB: it is important to start replacing casts from the bottom to properly replace aliases
static class PruneCast extends Rule<LogicalPlan, LogicalPlan> {
@Override
public LogicalPlan apply(LogicalPlan plan) {
return rule(plan);
}
@Override
protected LogicalPlan rule(LogicalPlan plan) {
final Map<Attribute, Attribute> replacedCast = new LinkedHashMap<>();
// first eliminate casts inside Aliases
LogicalPlan transformed = plan.transformExpressionsUp(e -> {
// cast wrapped in an alias
if (e instanceof Alias) {
Alias as = (Alias) e;
if (as.child() instanceof Cast) {
Cast c = (Cast) as.child();
if (c.from() == c.to()) {
Alias newAs = new Alias(as.location(), as.name(), as.qualifier(), c.field(), as.id(), as.synthetic());
replacedCast.put(as.toAttribute(), newAs.toAttribute());
return newAs;
}
}
return e;
}
return e;
});
// then handle stand-alone casts (mixed together the cast rule will kick in before the alias)
transformed = transformed.transformExpressionsUp(e -> {
if (e instanceof Cast) {
Cast c = (Cast) e;
if (c.from() == c.to()) {
Expression argument = c.field();
if (argument instanceof NamedExpression) {
replacedCast.put(c.toAttribute(), ((NamedExpression) argument).toAttribute());
}
return argument;
}
}
return e;
});
// replace attributes from previous removed Casts
if (!replacedCast.isEmpty()) {
return transformed.transformUp(p -> {
List<Attribute> newProjections = new ArrayList<>();
boolean changed = false;
for (NamedExpression ne : p.projections()) {
Attribute found = replacedCast.get(ne.toAttribute());
if (found != null) {
changed = true;
newProjections.add(found);
}
else {
newProjections.add(ne.toAttribute());
}
}
return changed ? new Project(p.location(), p.child(), newProjections) : p;
}, Project.class);
}
return transformed;
}
}
static class PruneDuplicateFunctions extends Rule<LogicalPlan, LogicalPlan> {
@Override
public LogicalPlan apply(LogicalPlan p) {
List<Function> seen = new ArrayList<>();
return p.transformExpressionsUp(e -> rule(e, seen));
}
@Override
protected LogicalPlan rule(LogicalPlan e) {
return e;
}
protected Expression rule(Expression exp, List<Function> seen) {
Expression e = exp;
if (e instanceof Function) {
Function f = (Function) e;
for (Function seenFunction : seen) {
if (seenFunction != f && f.functionEquals(seenFunction)) {
return seenFunction;
}
}
seen.add(f);
}
return exp;
}
}
static class CombineProjections extends OptimizerRule<Project> {
CombineProjections() {
super(TransformDirection.UP);
}
@Override
protected LogicalPlan rule(Project project) {
LogicalPlan child = project.child();