/
IndexJoinOptimizer.java
479 lines (416 loc) · 22.5 KB
/
IndexJoinOptimizer.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
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.planner.optimizations;
import com.facebook.presto.Session;
import com.facebook.presto.index.IndexManager;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.metadata.ResolvedIndex;
import com.facebook.presto.spi.ColumnHandle;
import com.facebook.presto.spi.TupleDomain;
import com.facebook.presto.sql.planner.DomainTranslator;
import com.facebook.presto.sql.planner.PlanNodeIdAllocator;
import com.facebook.presto.sql.planner.Symbol;
import com.facebook.presto.sql.planner.SymbolAllocator;
import com.facebook.presto.sql.planner.plan.AggregationNode;
import com.facebook.presto.sql.planner.plan.FilterNode;
import com.facebook.presto.sql.planner.plan.IndexJoinNode;
import com.facebook.presto.sql.planner.plan.IndexSourceNode;
import com.facebook.presto.sql.planner.plan.JoinNode;
import com.facebook.presto.sql.planner.plan.PlanNode;
import com.facebook.presto.sql.planner.plan.PlanRewriter;
import com.facebook.presto.sql.planner.plan.PlanVisitor;
import com.facebook.presto.sql.planner.plan.ProjectNode;
import com.facebook.presto.sql.planner.plan.SortNode;
import com.facebook.presto.sql.planner.plan.TableScanNode;
import com.facebook.presto.sql.tree.BooleanLiteral;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.QualifiedNameReference;
import com.google.common.base.Functions;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.facebook.presto.sql.tree.BooleanLiteral.TRUE_LITERAL;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Predicates.in;
import static java.util.Objects.requireNonNull;
public class IndexJoinOptimizer
extends PlanOptimizer
{
private final IndexManager indexManager;
private final Metadata metadata;
public IndexJoinOptimizer(Metadata metadata, IndexManager indexManager)
{
this.metadata = requireNonNull(metadata, "metadata is null");
this.indexManager = requireNonNull(indexManager, "indexManager is null");
}
@Override
public PlanNode optimize(PlanNode plan, Session session, Map<Symbol, com.facebook.presto.spi.type.Type> types, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator)
{
checkNotNull(plan, "plan is null");
checkNotNull(session, "session is null");
checkNotNull(types, "types is null");
checkNotNull(symbolAllocator, "symbolAllocator is null");
checkNotNull(idAllocator, "idAllocator is null");
return PlanRewriter.rewriteWith(new Rewriter(symbolAllocator, idAllocator, indexManager, metadata, session), plan, null);
}
private static class Rewriter
extends PlanRewriter<Void>
{
private final IndexManager indexManager;
private final SymbolAllocator symbolAllocator;
private final PlanNodeIdAllocator idAllocator;
private final Metadata metadata;
private final Session session;
private Rewriter(SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator, IndexManager indexManager, Metadata metadata, Session session)
{
this.symbolAllocator = requireNonNull(symbolAllocator, "symbolAllocator is null");
this.idAllocator = requireNonNull(idAllocator, "idAllocator is null");
this.indexManager = requireNonNull(indexManager, "indexManager is null");
this.metadata = requireNonNull(metadata, "metadata is null");
this.session = requireNonNull(session, "session is null");
}
@Override
public PlanNode visitJoin(JoinNode node, RewriteContext<Void> context)
{
PlanNode leftRewritten = context.rewrite(node.getLeft());
PlanNode rightRewritten = context.rewrite(node.getRight());
if (!node.getCriteria().isEmpty()) { // Index join only possible with JOIN criteria
List<Symbol> leftJoinSymbols = Lists.transform(node.getCriteria(), JoinNode.EquiJoinClause::getLeft);
List<Symbol> rightJoinSymbols = Lists.transform(node.getCriteria(), JoinNode.EquiJoinClause::getRight);
Optional<PlanNode> leftIndexCandidate = IndexSourceRewriter.rewriteWithIndex(
leftRewritten,
ImmutableSet.copyOf(leftJoinSymbols),
indexManager,
symbolAllocator,
idAllocator,
metadata,
session);
if (leftIndexCandidate.isPresent()) {
// Sanity check that we can trace the path for the index lookup key
Map<Symbol, Symbol> trace = IndexKeyTracer.trace(leftIndexCandidate.get(), ImmutableSet.copyOf(leftJoinSymbols));
checkState(!trace.isEmpty() && leftJoinSymbols.containsAll(trace.keySet()));
}
Optional<PlanNode> rightIndexCandidate = IndexSourceRewriter.rewriteWithIndex(
rightRewritten,
ImmutableSet.copyOf(rightJoinSymbols),
indexManager,
symbolAllocator,
idAllocator,
metadata,
session);
if (rightIndexCandidate.isPresent()) {
// Sanity check that we can trace the path for the index lookup key
Map<Symbol, Symbol> trace = IndexKeyTracer.trace(rightIndexCandidate.get(), ImmutableSet.copyOf(rightJoinSymbols));
checkState(!trace.isEmpty() && rightJoinSymbols.containsAll(trace.keySet()));
}
switch (node.getType()) {
case INNER:
// Prefer the right candidate over the left candidate
if (rightIndexCandidate.isPresent()) {
return new IndexJoinNode(idAllocator.getNextId(), IndexJoinNode.Type.INNER, leftRewritten, rightIndexCandidate.get(), createEquiJoinClause(leftJoinSymbols, rightJoinSymbols), Optional.empty(), Optional.empty());
}
else if (leftIndexCandidate.isPresent()) {
return new IndexJoinNode(idAllocator.getNextId(), IndexJoinNode.Type.INNER, rightRewritten, leftIndexCandidate.get(), createEquiJoinClause(rightJoinSymbols, leftJoinSymbols), Optional.empty(), Optional.empty());
}
break;
case LEFT:
if (rightIndexCandidate.isPresent()) {
return new IndexJoinNode(idAllocator.getNextId(), IndexJoinNode.Type.SOURCE_OUTER, leftRewritten, rightIndexCandidate.get(), createEquiJoinClause(leftJoinSymbols, rightJoinSymbols), Optional.empty(), Optional.empty());
}
break;
case RIGHT:
if (leftIndexCandidate.isPresent()) {
return new IndexJoinNode(idAllocator.getNextId(), IndexJoinNode.Type.SOURCE_OUTER, rightRewritten, leftIndexCandidate.get(), createEquiJoinClause(rightJoinSymbols, leftJoinSymbols), Optional.empty(), Optional.empty());
}
break;
default:
throw new IllegalArgumentException("Unknown type: " + node.getType());
}
}
if (leftRewritten != node.getLeft() || rightRewritten != node.getRight()) {
return new JoinNode(node.getId(), node.getType(), leftRewritten, rightRewritten, node.getCriteria(), node.getLeftHashSymbol(), node.getRightHashSymbol());
}
return node;
}
private static List<IndexJoinNode.EquiJoinClause> createEquiJoinClause(List<Symbol> probeSymbols, List<Symbol> indexSymbols)
{
checkArgument(probeSymbols.size() == indexSymbols.size());
ImmutableList.Builder<IndexJoinNode.EquiJoinClause> builder = ImmutableList.builder();
for (int i = 0; i < probeSymbols.size(); i++) {
builder.add(new IndexJoinNode.EquiJoinClause(probeSymbols.get(i), indexSymbols.get(i)));
}
return builder.build();
}
}
private static Symbol referenceToSymbol(Expression expression)
{
checkArgument(expression instanceof QualifiedNameReference);
return Symbol.fromQualifiedName(((QualifiedNameReference) expression).getName());
}
/**
* Tries to rewrite a PlanNode tree with an IndexSource instead of a TableScan
*/
private static class IndexSourceRewriter
extends PlanRewriter<IndexSourceRewriter.Context>
{
private final IndexManager indexManager;
private final SymbolAllocator symbolAllocator;
private final PlanNodeIdAllocator idAllocator;
private final Metadata metadata;
private final Session session;
private IndexSourceRewriter(IndexManager indexManager, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator, Metadata metadata, Session session)
{
this.metadata = requireNonNull(metadata, "metadata is null");
this.symbolAllocator = checkNotNull(symbolAllocator, "symbolAllocator is null");
this.idAllocator = checkNotNull(idAllocator, "idAllocator is null");
this.indexManager = checkNotNull(indexManager, "indexManager is null");
this.session = requireNonNull(session, "session is null");
}
public static Optional<PlanNode> rewriteWithIndex(
PlanNode planNode,
Set<Symbol> lookupSymbols,
IndexManager indexManager,
SymbolAllocator symbolAllocator,
PlanNodeIdAllocator idAllocator,
Metadata metadata,
Session session)
{
AtomicBoolean success = new AtomicBoolean();
IndexSourceRewriter indexSourceRewriter = new IndexSourceRewriter(indexManager, symbolAllocator, idAllocator, metadata, session);
PlanNode rewritten = PlanRewriter.rewriteWith(indexSourceRewriter, planNode, new Context(lookupSymbols, success));
if (success.get()) {
return Optional.of(rewritten);
}
return Optional.empty();
}
@Override
public PlanNode visitPlan(PlanNode node, RewriteContext<Context> context)
{
// We don't know how to process this PlanNode in the context of an IndexJoin, so just give up by returning something
return node;
}
@Override
public PlanNode visitTableScan(TableScanNode node, RewriteContext<Context> context)
{
return planTableScan(node, BooleanLiteral.TRUE_LITERAL, context.get());
}
@NotNull
private PlanNode planTableScan(TableScanNode node, Expression predicate, Context context)
{
TupleDomain<ColumnHandle> constraint = DomainTranslator.fromPredicate(metadata, session, predicate, symbolAllocator.getTypes())
.getTupleDomain()
.transform(node.getAssignments()::get)
.intersect(node.getCurrentConstraint());
checkState(node.getOutputSymbols().containsAll(context.getLookupSymbols()));
Set<ColumnHandle> lookupColumns = FluentIterable.from(context.getLookupSymbols())
.transform(Functions.forMap(node.getAssignments()))
.toSet();
Optional<ResolvedIndex> optionalResolvedIndex = indexManager.resolveIndex(node.getTable(), lookupColumns, constraint);
if (!optionalResolvedIndex.isPresent()) {
// No index available, so give up by returning something
return node;
}
ResolvedIndex resolvedIndex = optionalResolvedIndex.get();
Map<ColumnHandle, Symbol> inverseAssignments = ImmutableBiMap.copyOf(node.getAssignments()).inverse();
Expression unresolvedExpression = DomainTranslator.toPredicate(resolvedIndex.getUnresolvedTupleDomain().transform(inverseAssignments::get), symbolAllocator.getTypes());
PlanNode source = new IndexSourceNode(
idAllocator.getNextId(),
resolvedIndex.getIndexHandle(),
node.getTable(),
context.getLookupSymbols(),
node.getOutputSymbols(),
node.getAssignments(),
constraint);
if (!unresolvedExpression.equals(TRUE_LITERAL)) {
// todo it is likely we end up with redundant filters here because the predicate push down has already been run... the fix is to run predicate push down again
source = new FilterNode(idAllocator.getNextId(), source, unresolvedExpression);
}
context.markSuccess();
return source;
}
@Override
public PlanNode visitProject(ProjectNode node, RewriteContext<Context> context)
{
// Rewrite the lookup symbols in terms of only the pre-projected symbols that have direct translations
Set<Symbol> newLookupSymbols = FluentIterable.from(context.get().getLookupSymbols())
.transform(Functions.forMap(node.getAssignments()))
.filter(QualifiedNameReference.class::isInstance)
.transform(IndexJoinOptimizer::referenceToSymbol)
.toSet();
if (newLookupSymbols.isEmpty()) {
return node;
}
return context.defaultRewrite(node, new Context(newLookupSymbols, context.get().getSuccess()));
}
@Override
public PlanNode visitFilter(FilterNode node, RewriteContext<Context> context)
{
if (node.getSource() instanceof TableScanNode) {
TableScanNode tableScan = (TableScanNode) node.getSource();
return new FilterNode(
node.getId(),
planTableScan(tableScan, node.getPredicate(), context.get()),
node.getPredicate());
}
return context.defaultRewrite(node, new Context(context.get().getLookupSymbols(), context.get().getSuccess()));
}
@Override
public PlanNode visitIndexSource(IndexSourceNode node, RewriteContext<Context> context)
{
throw new IllegalStateException("Should not be trying to generate an Index on something that has already been determined to use an Index");
}
@Override
public PlanNode visitIndexJoin(IndexJoinNode node, RewriteContext<Context> context)
{
// Lookup symbols can only be passed through the probe side of an index join
Set<Symbol> probeLookupSymbols = FluentIterable.from(context.get().getLookupSymbols())
.filter(in(node.getProbeSource().getOutputSymbols()))
.toSet();
if (probeLookupSymbols.isEmpty()) {
return node;
}
PlanNode rewrittenProbeSource = context.rewrite(node.getProbeSource(), new Context(probeLookupSymbols, context.get().getSuccess()));
PlanNode source = node;
if (rewrittenProbeSource != node.getProbeSource()) {
source = new IndexJoinNode(node.getId(), node.getType(), rewrittenProbeSource, node.getIndexSource(), node.getCriteria(), node.getProbeHashSymbol(), node.getIndexHashSymbol());
}
return source;
}
@Override
public PlanNode visitAggregation(AggregationNode node, RewriteContext<Context> context)
{
// Lookup symbols can only be passed through if they are part of the group by columns
Set<Symbol> groupByLookupSymbols = FluentIterable.from(context.get().getLookupSymbols())
.filter(in(node.getGroupBy()))
.toSet();
if (groupByLookupSymbols.isEmpty()) {
return node;
}
return context.defaultRewrite(node, new Context(groupByLookupSymbols, context.get().getSuccess()));
}
@Override
public PlanNode visitSort(SortNode node, RewriteContext<Context> context)
{
// Sort has no bearing when building an index, so just ignore the sort
return context.rewrite(node.getSource(), context.get());
}
public static class Context
{
private final Set<Symbol> lookupSymbols;
private final AtomicBoolean success;
public Context(Set<Symbol> lookupSymbols, AtomicBoolean success)
{
checkArgument(!lookupSymbols.isEmpty(), "lookupSymbols can not be empty");
this.lookupSymbols = ImmutableSet.copyOf(checkNotNull(lookupSymbols, "lookupSymbols is null"));
this.success = checkNotNull(success, "success is null");
}
public Set<Symbol> getLookupSymbols()
{
return lookupSymbols;
}
public AtomicBoolean getSuccess()
{
return success;
}
public void markSuccess()
{
checkState(success.compareAndSet(false, true), "Can only have one success per context");
}
}
}
/**
* Identify the mapping from the lookup symbols used at the top of the index plan to
* the actual symbols produced by the IndexSource. Note that multiple top-level lookup symbols may share the same
* underlying IndexSource symbol. Also note that lookup symbols that do not correspond to underlying index source symbols
* will be omitted from the returned Map.
*/
public static class IndexKeyTracer
{
public static Map<Symbol, Symbol> trace(PlanNode node, Set<Symbol> lookupSymbols)
{
return node.accept(new Visitor(), lookupSymbols);
}
private static class Visitor
extends PlanVisitor<Set<Symbol>, Map<Symbol, Symbol>>
{
@Override
protected Map<Symbol, Symbol> visitPlan(PlanNode node, Set<Symbol> lookupSymbols)
{
throw new UnsupportedOperationException("Node not expected to be part of Index pipeline: " + node);
}
@Override
public Map<Symbol, Symbol> visitProject(ProjectNode node, Set<Symbol> lookupSymbols)
{
// Map from output Symbols to source Symbols
Map<Symbol, Symbol> directSymbolTranslationOutputMap = Maps.transformValues(Maps.filterValues(node.getAssignments(), QualifiedNameReference.class::isInstance), IndexJoinOptimizer::referenceToSymbol);
Map<Symbol, Symbol> outputToSourceMap = FluentIterable.from(lookupSymbols)
.filter(in(directSymbolTranslationOutputMap.keySet()))
.toMap(Functions.forMap(directSymbolTranslationOutputMap));
checkState(!outputToSourceMap.isEmpty(), "No lookup symbols were able to pass through the projection");
// Map from source Symbols to underlying index source Symbols
Map<Symbol, Symbol> sourceToIndexMap = node.getSource().accept(this, ImmutableSet.copyOf(outputToSourceMap.values()));
// Generate the Map the connects lookup symbols to underlying index source symbols
Map<Symbol, Symbol> outputToIndexMap = Maps.transformValues(Maps.filterValues(outputToSourceMap, in(sourceToIndexMap.keySet())), Functions.forMap(sourceToIndexMap));
return ImmutableMap.copyOf(outputToIndexMap);
}
@Override
public Map<Symbol, Symbol> visitFilter(FilterNode node, Set<Symbol> lookupSymbols)
{
return node.getSource().accept(this, lookupSymbols);
}
@Override
public Map<Symbol, Symbol> visitIndexJoin(IndexJoinNode node, Set<Symbol> lookupSymbols)
{
Set<Symbol> probeLookupSymbols = FluentIterable.from(lookupSymbols)
.filter(in(node.getProbeSource().getOutputSymbols()))
.toSet();
checkState(!probeLookupSymbols.isEmpty(), "No lookup symbols were able to pass through the index join probe source");
return node.getProbeSource().accept(this, probeLookupSymbols);
}
@Override
public Map<Symbol, Symbol> visitAggregation(AggregationNode node, Set<Symbol> lookupSymbols)
{
Set<Symbol> groupByLookupSymbols = FluentIterable.from(lookupSymbols)
.filter(in(node.getGroupBy()))
.toSet();
checkState(!groupByLookupSymbols.isEmpty(), "No lookup symbols were able to pass through the aggregation group by");
return node.getSource().accept(this, groupByLookupSymbols);
}
@Override
public Map<Symbol, Symbol> visitSort(SortNode node, Set<Symbol> lookupSymbols)
{
return node.getSource().accept(this, lookupSymbols);
}
@Override
public Map<Symbol, Symbol> visitIndexSource(IndexSourceNode node, Set<Symbol> lookupSymbols)
{
checkState(node.getLookupSymbols().equals(lookupSymbols), "lookupSymbols must be the same as IndexSource lookup symbols");
return FluentIterable.from(lookupSymbols)
.toMap(Functions.<Symbol>identity());
}
}
}
}