-
Notifications
You must be signed in to change notification settings - Fork 37
/
QueryPlanner.cpp
1818 lines (1711 loc) · 77 KB
/
QueryPlanner.cpp
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 2015, University of Freiburg,
// Chair of Algorithms and Data Structures.
// Author: Björn Buchhold (buchhold@informatik.uni-freiburg.de)
#include "./QueryPlanner.h"
#include <algorithm>
#include "../parser/ParseException.h"
#include "CountAvailablePredicates.h"
#include "Distinct.h"
#include "Filter.h"
#include "GroupBy.h"
#include "HasPredicateScan.h"
#include "IndexScan.h"
#include "Join.h"
#include "OptionalJoin.h"
#include "OrderBy.h"
#include "Sort.h"
#include "TextOperationWithFilter.h"
#include "TextOperationWithoutFilter.h"
#include "TwoColumnJoin.h"
// _____________________________________________________________________________
QueryPlanner::QueryPlanner(QueryExecutionContext* qec, bool optimizeOptionals)
: _qec(qec), _optimizeOptionals(optimizeOptionals) {}
// _____________________________________________________________________________
QueryExecutionTree QueryPlanner::createExecutionTree(ParsedQuery& pq) const {
// Create a topological sorting of the tree where children are in the list
// after their parents.
std::vector<const ParsedQuery::GraphPattern*> patternsToProcess;
std::vector<const ParsedQuery::GraphPattern*> childrenToAdd;
childrenToAdd.push_back(&pq._rootGraphPattern);
while (!childrenToAdd.empty()) {
const ParsedQuery::GraphPattern* pattern = childrenToAdd.back();
childrenToAdd.pop_back();
patternsToProcess.push_back(pattern);
childrenToAdd.insert(childrenToAdd.end(), pattern->_children.begin(),
pattern->_children.end());
}
std::vector<SubtreePlan> patternPlans;
for (size_t i = 0; i < pq._numGraphPatterns; i++) {
// Using a loop instead of resize as there is no default constructor, and
// distinct _qet values are needed.
patternPlans.emplace_back(_qec);
}
LOG(DEBUG) << "Got " << patternPlans.size() << " subplans to create."
<< std::endl;
// look for ql:has-predicate to determine if the pattern trick should be used
bool usePatternTrick = false;
SparqlTriple patternTrickTriple("", "", "");
// Check if the query has the right number of variables for aliases, select
// and group by.
if (pq._groupByVariables.size() == 1 && pq._aliases.size() == 1 &&
pq._selectedVariables.size() == 2) {
const ParsedQuery::Alias& alias = pq._aliases.back();
// Check if the alias is a non distinct count alias
if (alias._isAggregate &&
alias._function.find("DISTINCT") == std::string::npos &&
alias._function.find("distinct") == std::string::npos &&
(ad_utility::startsWith(alias._function, "COUNT") ||
ad_utility::startsWith(alias._function, "count"))) {
// look for a HAS_RELATION_PREDICATE triple
for (size_t i = 0; i < pq._rootGraphPattern._whereClauseTriples.size();
i++) {
const SparqlTriple& t = pq._rootGraphPattern._whereClauseTriples[i];
if (t._p == HAS_PREDICATE_PREDICATE && alias._inVarName == t._o &&
pq._groupByVariables[0] == t._o &&
pq._selectedVariables[0] == t._o &&
pq._selectedVariables[1] == alias._outVarName) {
LOG(DEBUG) << "Using the pattern trick to answer the query." << endl;
usePatternTrick = true;
patternTrickTriple = t;
// remove the triple from the graph
pq._rootGraphPattern._whereClauseTriples.erase(
pq._rootGraphPattern._whereClauseTriples.begin() + i);
}
}
}
}
bool doGrouping = pq._groupByVariables.size() > 0 || usePatternTrick;
if (!doGrouping) {
// if there is no group by statement, but an aggregate alias is used
// somewhere do grouping anyways.
for (const ParsedQuery::Alias& a : pq._aliases) {
if (a._isAggregate) {
doGrouping = true;
break;
}
}
}
vector<SubtreePlan*> childPlans;
while (!patternsToProcess.empty()) {
const ParsedQuery::GraphPattern* pattern = patternsToProcess.back();
patternsToProcess.pop_back();
LOG(DEBUG) << "Creating execution plan.\n";
childPlans.clear();
if (_optimizeOptionals) {
for (const ParsedQuery::GraphPattern* child : pattern->_children) {
childPlans.push_back(&patternPlans[child->_id]);
}
}
// Strategy:
// Create a graph.
// Each triple corresponds to a node, there is an edge between two nodes iff
// they share a variable.
TripleGraph tg = createTripleGraph(pattern);
// Each node/triple corresponds to a scan (more than one way possible),
// each edge corresponds to a possible join.
// Enumerate and judge possible query plans using a DP table.
// Each ExecutionTree for a sub-problem gives an estimate:
// There are estimates for cost and size ( and multiplicity per column).
// Start bottom up, i.e. with the scans for triples.
// Always merge two solutions from the table by picking one possible join.
// A join is possible, if there is an edge between the results.
// Therefore we keep track of all edges that touch a sub-result.
// When joining two sub-results, the results edges are those that belong
// to exactly one of the two input sub-trees.
// If two of them have the same target, only one out edge is created.
// All edges that are shared by both subtrees, are checked if they are
// covered by the join or if an extra filter/select is needed.
// The algorithm then creates all possible plans for 1 to n triples.
// To generate a plan for k triples, all subsets between i and k-i are
// joined.
// Filters are now added to the mix when building execution plans.
// Without them, a plan has an execution tree and a set of
// covered triple nodes.
// With them, it also has a set of covered filters.
// A filter can be applied as soon as all variables that occur in the filter
// Are covered by the query. This is also always the place where this is
// done.
// Text operations form cliques (all triples connected via the context
// cvar). Detect them and turn them into nodes with stored word part and
// edges to connected variables.
LOG(TRACE) << "Collapse text cliques..." << std::endl;
tg.collapseTextCliques();
LOG(TRACE) << "Collapse text cliques done." << std::endl;
vector<vector<SubtreePlan>> finalTab;
// Each text operation has two ways how it can be used.
// 1) As leave in the bottom row of the tab.
// According to the number of connected variables, the operation creates
// a cross product with n entities that can be used in subsequent joins.
// 2) as intermediate unary (downwards) nodes in the execution tree.
// This is a bit similar to sorts: they can be applied after each step
// and will filter on one variable.
// Cycles have to be avoided (by previously removing a triple and using it
// as a filter later on).
finalTab = fillDpTab(tg, pattern->_filters, childPlans);
// If any form of grouping is used (e.g. the pattern trick) sorting
// has to be done after the grouping.
if (pattern == &pq._rootGraphPattern && pq._orderBy.size() > 0 &&
!doGrouping) {
// If there is an order by clause, add another row to the table and
// just add an order by / sort to every previous result if needed.
// If the ordering is perfect already, just copy the plan.
finalTab.emplace_back(getOrderByRow(pq, finalTab));
}
vector<SubtreePlan>& lastRow = finalTab.back();
if (!usePatternTrick) {
// when the pattern trick is in use there is one triple that is not
// part of the triple graph, so the lastRow can be empty
AD_CHECK_GT(lastRow.size(), 0);
}
if (lastRow.size() > 0) {
size_t minCost = lastRow[0].getCostEstimate();
size_t minInd = 0;
for (size_t i = 1; i < lastRow.size(); ++i) {
size_t thisCost = lastRow[i].getCostEstimate();
if (thisCost < minCost) {
minCost = lastRow[i].getCostEstimate();
minInd = i;
}
}
lastRow[minInd]._isOptional = pattern->_optional;
patternPlans[pattern->_id] = lastRow[minInd];
}
}
if (!_optimizeOptionals) {
// join the created trees using optional joins on all of their common
// variables
// Create an inverse topological ordering of all nodes with children
std::vector<const ParsedQuery::GraphPattern*> inverseTopo;
patternsToProcess.push_back(&pq._rootGraphPattern);
while (!patternsToProcess.empty()) {
const ParsedQuery::GraphPattern* pattern = patternsToProcess.back();
patternsToProcess.pop_back();
if (pattern->_children.size() > 0) {
// queue all children for processing
patternsToProcess.insert(patternsToProcess.end(),
pattern->_children.begin(),
pattern->_children.end());
inverseTopo.push_back(pattern);
}
}
LOG(DEBUG) << inverseTopo.size() << " of the nodes have children"
<< std::endl;
if (!inverseTopo.empty()) {
std::vector<ParsedQuery::GraphPattern*> sortedChildren;
for (int i = inverseTopo.size() - 1; i >= 0; i--) {
const ParsedQuery::GraphPattern* pattern = inverseTopo[i];
sortedChildren.clear();
sortedChildren.insert(sortedChildren.end(), pattern->_children.begin(),
pattern->_children.end());
// Init the joins by taking the parent and its first child, then
// succesively join with the next child.
// ensure the children are sorted in ascending order
std::sort(sortedChildren.begin(), sortedChildren.end(),
[&patternPlans](const ParsedQuery::GraphPattern* p1,
const ParsedQuery::GraphPattern* p2) -> bool {
return patternPlans[p1->_id].getSizeEstimate() <
patternPlans[p2->_id].getSizeEstimate();
});
std::vector<SubtreePlan> plans;
plans.push_back(optionalJoin(patternPlans[pattern->_id],
patternPlans[sortedChildren[0]->_id]));
for (size_t j = 1; j < sortedChildren.size(); j++) {
SubtreePlan& plan1 = plans.back();
SubtreePlan& plan2 = patternPlans[sortedChildren[j]->_id];
plans.push_back(optionalJoin(plan1, plan2));
}
// Replace the old pattern with the new one that merges all children.
patternPlans[pattern->_id] = plans.back();
}
}
}
SubtreePlan final = patternPlans[0];
if (usePatternTrick) {
if (final._qet->getRootOperation() != nullptr) {
// Determine the column containing the subjects for which we are
// interested in their predicates.
auto it =
final._qet.get()->getVariableColumnMap().find(patternTrickTriple._s);
if (it == final._qet.get()->getVariableColumnMap().end()) {
AD_THROW(ad_semsearch::Exception::BAD_QUERY,
"The root operation of the "
"query excecution tree does "
"not contain a column for "
"variable " +
patternTrickTriple._s +
" required by the pattern "
"trick.");
}
size_t subjectColumn = it->second;
bool isSorted =
final._qet->getRootOperation()->resultSortedOn() == subjectColumn;
// a and b need to be ordered properly first
vector<pair<size_t, bool>> sortIndices = {
std::make_pair(subjectColumn, false)};
SubtreePlan orderByPlan(_qec);
std::shared_ptr<Operation> orderByOp(
new OrderBy(_qec, final._qet, sortIndices));
if (isSorted) {
orderByPlan._qet->setVariableColumns(
final._qet->getVariableColumnMap());
orderByPlan._qet->setOperation(QueryExecutionTree::ORDER_BY, orderByOp);
}
SubtreePlan patternTrickPlan(_qec);
std::shared_ptr<Operation> countPred(new CountAvailablePredicates(
_qec, isSorted ? final._qet : orderByPlan._qet, subjectColumn));
static_cast<CountAvailablePredicates*>(countPred.get())
->setVarNames(patternTrickTriple._o, pq._aliases[0]._outVarName);
QueryExecutionTree& tree = *patternTrickPlan._qet.get();
tree.setVariableColumns(
static_cast<CountAvailablePredicates*>(countPred.get())
->getVariableColumns());
tree.setOperation(QueryExecutionTree::COUNT_AVAILABLE_PREDICATES,
countPred);
final = patternTrickPlan;
std::cout << "Plan after pattern trick: " << endl
<< final._qet->asString() << endl;
} else {
// Use the pattern trick without a subtree
SubtreePlan patternTrickPlan(_qec);
std::shared_ptr<Operation> countPred(new CountAvailablePredicates(_qec));
static_cast<CountAvailablePredicates*>(countPred.get())
->setVarNames(patternTrickTriple._o, pq._aliases[0]._outVarName);
QueryExecutionTree& tree = *patternTrickPlan._qet.get();
tree.setVariableColumns(
static_cast<CountAvailablePredicates*>(countPred.get())
->getVariableColumns());
tree.setOperation(QueryExecutionTree::COUNT_AVAILABLE_PREDICATES,
countPred);
final = patternTrickPlan;
}
} else if (doGrouping) {
// Create a group by operation to determine on which columns the input
// needs to be sorted
SubtreePlan groupByPlan(_qec);
std::shared_ptr<Operation> groupBy =
std::make_shared<GroupBy>(_qec, pq._groupByVariables, pq._aliases);
QueryExecutionTree& groupByTree = *groupByPlan._qet.get();
// Then compute the sort columns
std::vector<std::pair<size_t, bool>> sortColumns =
static_cast<GroupBy*>(groupBy.get())->computeSortColumns(final._qet);
if (!sortColumns.empty() &&
!(sortColumns.size() == 1 &&
final._qet->resultSortedOn() == sortColumns[0].first)) {
// Create an order by operation as required by the group by
std::shared_ptr<Operation> orderBy =
std::make_shared<OrderBy>(_qec, final._qet, sortColumns);
SubtreePlan orderByPlan(_qec);
QueryExecutionTree& orderByTree = *orderByPlan._qet.get();
orderByTree.setVariableColumns(final._qet->getVariableColumnMap());
orderByTree.setOperation(QueryExecutionTree::ORDER_BY, orderBy);
final = orderByPlan;
}
static_cast<GroupBy*>(groupBy.get())->setSubtree(final._qet);
groupByTree.setVariableColumns(
static_cast<GroupBy*>(groupBy.get())->getVariableColumns());
groupByTree.setOperation(QueryExecutionTree::GROUP_BY, groupBy);
final = groupByPlan;
}
if (doGrouping) {
// Add the order by operation
if (pq._orderBy.size() > 0) {
SubtreePlan plan(_qec);
auto& tree = *plan._qet.get();
vector<pair<size_t, bool>> sortIndices;
for (auto& ord : pq._orderBy) {
sortIndices.emplace_back(pair<size_t, bool>{
final._qet.get()->getVariableColumn(ord._key), ord._desc});
}
std::shared_ptr<Operation> ob(new OrderBy(_qec, final._qet, sortIndices));
tree.setVariableColumns(final._qet.get()->getVariableColumnMap());
tree.setOperation(QueryExecutionTree::ORDER_BY, ob);
tree.setContextVars(final._qet.get()->getContextVars());
final = plan;
}
}
// A distinct modifier is applied in the end. This is very easy
// but not necessarily optimal.
// TODO: Adjust so that the optimal place for the operation is found.
if (pq._distinct) {
QueryExecutionTree distinctTree(*final._qet.get());
vector<size_t> keepIndices;
ad_utility::HashSet<size_t> indDone;
for (const auto& var : pq._selectedVariables) {
if (final._qet.get()->getVariableColumnMap().find(var) !=
final._qet.get()->getVariableColumnMap().end()) {
auto ind = final._qet.get()->getVariableColumnMap().find(var)->second;
if (indDone.count(ind) == 0) {
keepIndices.push_back(ind);
indDone.insert(ind);
}
} else if (ad_utility::startsWith(var, "SCORE(") ||
ad_utility::startsWith(var, "TEXT(")) {
auto varInd = var.find('?');
auto cVar = var.substr(varInd, var.rfind(')') - varInd);
if (final._qet.get()->getVariableColumnMap().find(cVar) !=
final._qet.get()->getVariableColumnMap().end()) {
auto ind =
final._qet.get()->getVariableColumnMap().find(cVar)->second;
if (indDone.count(ind) == 0) {
keepIndices.push_back(ind);
indDone.insert(ind);
}
}
}
}
if (final._qet.get()->getType() == QueryExecutionTree::SORT ||
final._qet.get()->getType() == QueryExecutionTree::ORDER_BY ||
std::find(keepIndices.begin(), keepIndices.end(),
final._qet.get()->resultSortedOn()) != keepIndices.end()) {
std::shared_ptr<Operation> distinct(
new Distinct(_qec, final._qet, keepIndices));
distinctTree.setOperation(QueryExecutionTree::DISTINCT, distinct);
} else {
if (keepIndices.size() == 1) {
std::shared_ptr<QueryExecutionTree> tree(new QueryExecutionTree(_qec));
std::shared_ptr<Operation> sort(
new Sort(_qec, final._qet, keepIndices[0]));
tree->setVariableColumns(final._qet.get()->getVariableColumnMap());
tree->setOperation(QueryExecutionTree::SORT, sort);
tree->setContextVars(final._qet.get()->getContextVars());
std::shared_ptr<Operation> distinct(
new Distinct(_qec, tree, keepIndices));
distinctTree.setOperation(QueryExecutionTree::DISTINCT, distinct);
} else {
std::shared_ptr<QueryExecutionTree> tree(new QueryExecutionTree(_qec));
vector<pair<size_t, bool>> obCols;
for (auto& i : keepIndices) {
obCols.emplace_back(std::make_pair(i, false));
}
std::shared_ptr<Operation> ob(new OrderBy(_qec, final._qet, obCols));
tree->setVariableColumns(final._qet.get()->getVariableColumnMap());
tree->setOperation(QueryExecutionTree::ORDER_BY, ob);
tree->setContextVars(final._qet.get()->getContextVars());
std::shared_ptr<Operation> distinct(
new Distinct(_qec, tree, keepIndices));
distinctTree.setOperation(QueryExecutionTree::DISTINCT, distinct);
}
}
distinctTree.setTextLimit(getTextLimit(pq._textLimit));
return distinctTree;
}
final._qet.get()->setTextLimit(getTextLimit(pq._textLimit));
LOG(DEBUG) << "Done creating execution plan.\n";
return *final._qet.get();
}
// _____________________________________________________________________________
vector<QueryPlanner::SubtreePlan> QueryPlanner::getOrderByRow(
const ParsedQuery& pq, const vector<vector<SubtreePlan>>& dpTab) const {
const vector<SubtreePlan>& previous = dpTab[dpTab.size() - 1];
vector<SubtreePlan> added;
added.reserve(previous.size());
for (size_t i = 0; i < previous.size(); ++i) {
SubtreePlan plan(_qec);
auto& tree = *plan._qet.get();
plan._idsOfIncludedNodes = previous[i]._idsOfIncludedNodes;
plan._idsOfIncludedFilters = previous[i]._idsOfIncludedFilters;
if (pq._orderBy.size() == 1 && !pq._orderBy[0]._desc) {
size_t col =
previous[i]._qet.get()->getVariableColumn(pq._orderBy[0]._key);
if (col == previous[i]._qet.get()->resultSortedOn()) {
// Already sorted perfectly
added.push_back(previous[i]);
} else {
std::shared_ptr<Operation> sort(new Sort(_qec, previous[i]._qet, col));
tree.setVariableColumns(previous[i]._qet.get()->getVariableColumnMap());
tree.setOperation(QueryExecutionTree::SORT, sort);
tree.setContextVars(previous[i]._qet.get()->getContextVars());
added.push_back(plan);
}
} else {
vector<pair<size_t, bool>> sortIndices;
for (auto& ord : pq._orderBy) {
sortIndices.emplace_back(pair<size_t, bool>{
previous[i]._qet.get()->getVariableColumn(ord._key), ord._desc});
}
std::shared_ptr<Operation> ob(
new OrderBy(_qec, previous[i]._qet, sortIndices));
tree.setVariableColumns(previous[i]._qet.get()->getVariableColumnMap());
tree.setOperation(QueryExecutionTree::ORDER_BY, ob);
tree.setContextVars(previous[i]._qet.get()->getContextVars());
added.push_back(plan);
}
}
return added;
}
// _____________________________________________________________________________
void QueryPlanner::getVarTripleMap(
const ParsedQuery& pq,
ad_utility::HashMap<string, vector<SparqlTriple>>& varToTrip,
ad_utility::HashSet<string>& contextVars) const {
for (auto& t : pq._rootGraphPattern._whereClauseTriples) {
if (isVariable(t._s)) {
varToTrip[t._s].push_back(t);
}
if (isVariable(t._p)) {
varToTrip[t._p].push_back(t);
}
if (isVariable(t._o)) {
varToTrip[t._o].push_back(t);
}
// TODO: Could use more refactoring.
// In Earlier versions there were no ql:contains... predicates but
// a symmetric <in-text> predicate. Therefore some parts are still more
// complex than need be.
if (t._p == CONTAINS_WORD_PREDICATE || t._p == CONTAINS_ENTITY_PREDICATE) {
contextVars.insert(t._s);
}
}
}
// _____________________________________________________________________________
bool QueryPlanner::isVariable(const string& elem) {
return ad_utility::startsWith(elem, "?");
}
// _____________________________________________________________________________
bool QueryPlanner::isWords(const string& elem) {
return !isVariable(elem) && elem.size() > 0 && elem[0] != '<';
}
// _____________________________________________________________________________
QueryPlanner::TripleGraph QueryPlanner::createTripleGraph(
const ParsedQuery::GraphPattern* pattern) const {
TripleGraph tg;
if (pattern->_whereClauseTriples.size() > 64) {
AD_THROW(ad_semsearch::Exception::BAD_QUERY,
"At most 64 triples allowed at the moment.");
}
if (pattern->_filters.size() > 64) {
AD_THROW(ad_semsearch::Exception::BAD_QUERY,
"At most 64 filters allowed at the moment.");
}
for (auto& t : pattern->_whereClauseTriples) {
// Add a node for the triple.
tg._nodeStorage.emplace_back(TripleGraph::Node(tg._nodeStorage.size(), t));
auto& addedNode = tg._nodeStorage.back();
tg._nodeMap[addedNode._id] = &tg._nodeStorage.back();
tg._adjLists.emplace_back(vector<size_t>());
assert(tg._adjLists.size() == tg._nodeStorage.size());
assert(tg._adjLists.size() == addedNode._id + 1);
// Now add an edge between the added node and every node sharing a var.
for (auto& addedNodevar : addedNode._variables) {
for (size_t i = 0; i < addedNode._id; ++i) {
auto& otherNode = *tg._nodeMap[i];
if (otherNode._variables.count(addedNodevar) > 0) {
// There is an edge between *it->second and the node with id "id".
tg._adjLists[addedNode._id].push_back(otherNode._id);
tg._adjLists[otherNode._id].push_back(addedNode._id);
}
}
}
}
return tg;
}
// _____________________________________________________________________________
vector<QueryPlanner::SubtreePlan> QueryPlanner::seedWithScansAndText(
const QueryPlanner::TripleGraph& tg,
const vector<QueryPlanner::SubtreePlan*>& children) const {
vector<SubtreePlan> seeds;
// add all child plans as seeds
uint32_t idShift = tg._nodeMap.size();
for (SubtreePlan* plan : children) {
SubtreePlan newIdPlan = *plan;
// give the plan a unique id bit
newIdPlan._idsOfIncludedNodes = 1 << idShift;
newIdPlan._idsOfIncludedFilters = 0;
seeds.push_back(newIdPlan);
idShift++;
}
for (size_t i = 0; i < tg._nodeMap.size(); ++i) {
const TripleGraph::Node& node = *tg._nodeMap.find(i)->second;
if (node._cvar.size() > 0) {
seeds.push_back(getTextLeafPlan(node));
} else {
if (node._variables.size() == 0) {
AD_THROW(
ad_semsearch::Exception::BAD_QUERY,
"Triples should have at least one variable. Not the case in: " +
node._triple.asString());
} else if (node._variables.size() == 1) {
// Just pick one direction, they should be equivalent.
SubtreePlan plan(_qec);
plan._idsOfIncludedNodes |= (1 << i);
auto& tree = *plan._qet.get();
if (node._triple._p == HAS_PREDICATE_PREDICATE) {
// Add a has relation scan instead of a normal IndexScan
if (isVariable(node._triple._s)) {
std::shared_ptr<Operation> scan =
std::make_shared<HasPredicateScan>(
_qec, HasPredicateScan::ScanType::FREE_S);
static_cast<HasPredicateScan*>(scan.get())
->setSubject(node._triple._s);
static_cast<HasPredicateScan*>(scan.get())
->setObject(node._triple._o);
tree.setOperation(
QueryExecutionTree::OperationType::HAS_RELATION_SCAN, scan);
tree.setVariableColumns(static_cast<HasPredicateScan*>(scan.get())
->getVariableColumns());
} else if (isVariable(node._triple._o)) {
std::shared_ptr<Operation> scan =
std::make_shared<HasPredicateScan>(
_qec, HasPredicateScan::ScanType::FREE_O);
static_cast<HasPredicateScan*>(scan.get())
->setSubject(node._triple._s);
static_cast<HasPredicateScan*>(scan.get())
->setObject(node._triple._o);
tree.setOperation(
QueryExecutionTree::OperationType::HAS_RELATION_SCAN, scan);
tree.setVariableColumns(static_cast<HasPredicateScan*>(scan.get())
->getVariableColumns());
}
} else if (isVariable(node._triple._s)) {
std::shared_ptr<Operation> scan(
new IndexScan(_qec, IndexScan::ScanType::POS_BOUND_O));
static_cast<IndexScan*>(scan.get())->setPredicate(node._triple._p);
static_cast<IndexScan*>(scan.get())->setObject(node._triple._o);
tree.setOperation(QueryExecutionTree::OperationType::SCAN, scan);
tree.setVariableColumn(node._triple._s, 0);
} else if (isVariable(node._triple._o)) {
std::shared_ptr<Operation> scan(
new IndexScan(_qec, IndexScan::ScanType::PSO_BOUND_S));
static_cast<IndexScan*>(scan.get())->setPredicate(node._triple._p);
static_cast<IndexScan*>(scan.get())->setSubject(node._triple._s);
tree.setOperation(QueryExecutionTree::OperationType::SCAN, scan);
tree.setVariableColumn(node._triple._o, 0);
} else {
std::shared_ptr<Operation> scan(
new IndexScan(_qec, IndexScan::ScanType::SOP_BOUND_O));
static_cast<IndexScan*>(scan.get())->setSubject(node._triple._s);
static_cast<IndexScan*>(scan.get())->setObject(node._triple._o);
tree.setOperation(QueryExecutionTree::OperationType::SCAN, scan);
tree.setVariableColumn(node._triple._p, 0);
}
seeds.push_back(plan);
} else if (node._variables.size() == 2) {
// Add plans for both possible scan directions.
if (node._triple._p == HAS_PREDICATE_PREDICATE) {
// Add a has relation scan instead of a normal IndexScan
SubtreePlan plan(_qec);
plan._idsOfIncludedNodes |= (1 << i);
auto& tree = *plan._qet.get();
std::shared_ptr<Operation> scan(new HasPredicateScan(
_qec, HasPredicateScan::ScanType::FULL_SCAN));
static_cast<HasPredicateScan*>(scan.get())
->setSubject(node._triple._s);
static_cast<HasPredicateScan*>(scan.get())
->setObject(node._triple._o);
tree.setOperation(
QueryExecutionTree::OperationType::HAS_RELATION_SCAN, scan);
tree.setVariableColumns(
static_cast<HasPredicateScan*>(scan.get())->getVariableColumns());
seeds.push_back(plan);
} else if (!isVariable(node._triple._p)) {
{
SubtreePlan plan(_qec);
plan._idsOfIncludedNodes |= (1 << i);
auto& tree = *plan._qet.get();
std::shared_ptr<Operation> scan(
new IndexScan(_qec, IndexScan::ScanType::PSO_FREE_S));
static_cast<IndexScan*>(scan.get())->setPredicate(node._triple._p);
static_cast<IndexScan*>(scan.get())->precomputeSizeEstimate();
tree.setOperation(QueryExecutionTree::OperationType::SCAN, scan);
tree.setVariableColumn(node._triple._s, 0);
tree.setVariableColumn(node._triple._o, 1);
seeds.push_back(plan);
}
{
SubtreePlan plan(_qec);
plan._idsOfIncludedNodes |= (1 << i);
auto& tree = *plan._qet.get();
std::shared_ptr<Operation> scan(
new IndexScan(_qec, IndexScan::ScanType::POS_FREE_O));
static_cast<IndexScan*>(scan.get())->setPredicate(node._triple._p);
static_cast<IndexScan*>(scan.get())->precomputeSizeEstimate();
tree.setOperation(QueryExecutionTree::OperationType::SCAN, scan);
tree.setVariableColumn(node._triple._o, 0);
tree.setVariableColumn(node._triple._s, 1);
seeds.push_back(plan);
}
} else if (!isVariable(node._triple._s)) {
{
SubtreePlan plan(_qec);
plan._idsOfIncludedNodes |= (1 << i);
auto& tree = *plan._qet.get();
std::shared_ptr<Operation> scan(
new IndexScan(_qec, IndexScan::ScanType::SPO_FREE_P));
static_cast<IndexScan*>(scan.get())->setSubject(node._triple._s);
static_cast<IndexScan*>(scan.get())->precomputeSizeEstimate();
tree.setOperation(QueryExecutionTree::OperationType::SCAN, scan);
tree.setVariableColumn(node._triple._p, 0);
tree.setVariableColumn(node._triple._o, 1);
seeds.push_back(plan);
}
{
SubtreePlan plan(_qec);
plan._idsOfIncludedNodes |= (1 << i);
auto& tree = *plan._qet.get();
std::shared_ptr<Operation> scan(
new IndexScan(_qec, IndexScan::ScanType::SOP_FREE_O));
static_cast<IndexScan*>(scan.get())->setSubject(node._triple._s);
static_cast<IndexScan*>(scan.get())->precomputeSizeEstimate();
tree.setOperation(QueryExecutionTree::OperationType::SCAN, scan);
tree.setVariableColumn(node._triple._o, 0);
tree.setVariableColumn(node._triple._p, 1);
seeds.push_back(plan);
}
} else if (!isVariable(node._triple._o)) {
{
SubtreePlan plan(_qec);
plan._idsOfIncludedNodes |= (1 << i);
auto& tree = *plan._qet.get();
std::shared_ptr<Operation> scan(
new IndexScan(_qec, IndexScan::ScanType::OSP_FREE_S));
static_cast<IndexScan*>(scan.get())->setObject(node._triple._o);
static_cast<IndexScan*>(scan.get())->precomputeSizeEstimate();
tree.setOperation(QueryExecutionTree::OperationType::SCAN, scan);
tree.setVariableColumn(node._triple._s, 0);
tree.setVariableColumn(node._triple._p, 1);
seeds.push_back(plan);
}
{
SubtreePlan plan(_qec);
plan._idsOfIncludedNodes |= (1 << i);
auto& tree = *plan._qet.get();
std::shared_ptr<Operation> scan(
new IndexScan(_qec, IndexScan::ScanType::OPS_FREE_P));
static_cast<IndexScan*>(scan.get())->setObject(node._triple._o);
static_cast<IndexScan*>(scan.get())->precomputeSizeEstimate();
tree.setOperation(QueryExecutionTree::OperationType::SCAN, scan);
tree.setVariableColumn(node._triple._p, 0);
tree.setVariableColumn(node._triple._s, 1);
seeds.push_back(plan);
}
}
} else {
if (!_qec || _qec->getIndex().hasAllPermutations()) {
// Add plans for all six permutations.
// SPO
{
SubtreePlan plan(_qec);
plan._idsOfIncludedNodes |= (1 << i);
auto& tree = *plan._qet.get();
std::shared_ptr<Operation> scan(
new IndexScan(_qec, IndexScan::ScanType::FULL_INDEX_SCAN_SPO));
static_cast<IndexScan*>(scan.get())->precomputeSizeEstimate();
tree.setOperation(QueryExecutionTree::OperationType::SCAN, scan);
tree.setVariableColumn(node._triple._s, 0);
tree.setVariableColumn(node._triple._p, 1);
tree.setVariableColumn(node._triple._o, 2);
seeds.push_back(plan);
}
// SOP
{
SubtreePlan plan(_qec);
plan._idsOfIncludedNodes |= (1 << i);
auto& tree = *plan._qet.get();
std::shared_ptr<Operation> scan(
new IndexScan(_qec, IndexScan::ScanType::FULL_INDEX_SCAN_SOP));
static_cast<IndexScan*>(scan.get())->precomputeSizeEstimate();
tree.setOperation(QueryExecutionTree::OperationType::SCAN, scan);
tree.setVariableColumn(node._triple._s, 0);
tree.setVariableColumn(node._triple._o, 1);
tree.setVariableColumn(node._triple._p, 2);
seeds.push_back(plan);
}
// PSO
{
SubtreePlan plan(_qec);
plan._idsOfIncludedNodes |= (1 << i);
auto& tree = *plan._qet.get();
std::shared_ptr<Operation> scan(
new IndexScan(_qec, IndexScan::ScanType::FULL_INDEX_SCAN_PSO));
static_cast<IndexScan*>(scan.get())->precomputeSizeEstimate();
tree.setOperation(QueryExecutionTree::OperationType::SCAN, scan);
tree.setVariableColumn(node._triple._p, 0);
tree.setVariableColumn(node._triple._s, 1);
tree.setVariableColumn(node._triple._o, 2);
seeds.push_back(plan);
}
// POS
{
SubtreePlan plan(_qec);
plan._idsOfIncludedNodes |= (1 << i);
auto& tree = *plan._qet.get();
std::shared_ptr<Operation> scan(
new IndexScan(_qec, IndexScan::ScanType::FULL_INDEX_SCAN_POS));
static_cast<IndexScan*>(scan.get())->precomputeSizeEstimate();
tree.setOperation(QueryExecutionTree::OperationType::SCAN, scan);
tree.setVariableColumn(node._triple._p, 0);
tree.setVariableColumn(node._triple._o, 1);
tree.setVariableColumn(node._triple._s, 2);
seeds.push_back(plan);
}
// OSP
{
SubtreePlan plan(_qec);
plan._idsOfIncludedNodes |= (1 << i);
auto& tree = *plan._qet.get();
std::shared_ptr<Operation> scan(
new IndexScan(_qec, IndexScan::ScanType::FULL_INDEX_SCAN_OSP));
static_cast<IndexScan*>(scan.get())->precomputeSizeEstimate();
tree.setOperation(QueryExecutionTree::OperationType::SCAN, scan);
tree.setVariableColumn(node._triple._o, 0);
tree.setVariableColumn(node._triple._s, 1);
tree.setVariableColumn(node._triple._p, 2);
seeds.push_back(plan);
}
// OPS
{
SubtreePlan plan(_qec);
plan._idsOfIncludedNodes |= (1 << i);
auto& tree = *plan._qet.get();
std::shared_ptr<Operation> scan(
new IndexScan(_qec, IndexScan::ScanType::FULL_INDEX_SCAN_OPS));
static_cast<IndexScan*>(scan.get())->precomputeSizeEstimate();
tree.setOperation(QueryExecutionTree::OperationType::SCAN, scan);
tree.setVariableColumn(node._triple._o, 0);
tree.setVariableColumn(node._triple._p, 1);
tree.setVariableColumn(node._triple._s, 2);
seeds.push_back(plan);
}
} else {
AD_THROW(ad_semsearch::Exception::NOT_YET_IMPLEMENTED,
"With only 2 permutations registered (no -a option), "
"triples should have at most two variables. "
"Not the case in: " +
node._triple.asString());
}
}
}
}
return seeds;
}
// _____________________________________________________________________________
QueryPlanner::SubtreePlan QueryPlanner::getTextLeafPlan(
const QueryPlanner::TripleGraph::Node& node) const {
SubtreePlan plan(_qec);
plan._idsOfIncludedNodes |= (1 << node._id);
auto& tree = *plan._qet.get();
AD_CHECK(node._wordPart.size() > 0);
// Subtract 1 for variables.size() for the context var.
std::shared_ptr<Operation> textOp(new TextOperationWithoutFilter(
_qec, node._wordPart, node._variables.size() - 1));
tree.setOperation(QueryExecutionTree::OperationType::TEXT_WITHOUT_FILTER,
textOp);
std::unordered_map<string, size_t> vcmap;
size_t index = 0;
vcmap[node._cvar] = index++;
vcmap[string("SCORE(") + node._cvar + ")"] = index++;
for (const auto& var : node._variables) {
if (var != node._cvar) {
vcmap[var] = index++;
}
}
tree.setVariableColumns(vcmap);
tree.addContextVar(node._cvar);
return plan;
}
// _____________________________________________________________________________
vector<QueryPlanner::SubtreePlan> QueryPlanner::merge(
const vector<QueryPlanner::SubtreePlan>& a,
const vector<QueryPlanner::SubtreePlan>& b,
const QueryPlanner::TripleGraph& tg) const {
// TODO: Add the following features:
// If a join is supposed to happen, always check if it happens between
// a scan with a relatively large result size
// esp. with an entire relation but also with something like is-a Person
// If that is the case look at the size estimate for the other side,
// if that is rather small, replace the join and scan by a combination.
ad_utility::HashMap<string, vector<SubtreePlan>> candidates;
// Find all pairs between a and b that are connected by an edge.
LOG(TRACE) << "Considering joins that merge " << a.size() << " and "
<< b.size() << " plans...\n";
for (size_t i = 0; i < a.size(); ++i) {
for (size_t j = 0; j < b.size(); ++j) {
if (connected(a[i], b[j], tg)) {
// Find join variable(s) / columns.
auto jcs = getJoinColumns(a[i], b[j]);
if (jcs.size() > 2 && !a[i]._isOptional && !b[j]._isOptional) {
LOG(WARN) << "Not considering possible join on "
<< "three or more columns at once.\n";
continue;
}
if (jcs.size() == 2 &&
(a[i]._qet.get()->getType() ==
QueryExecutionTree::OperationType::TEXT_WITHOUT_FILTER ||
b[j]._qet.get()->getType() ==
QueryExecutionTree::OperationType::TEXT_WITHOUT_FILTER)) {
LOG(WARN) << "Not considering possible join on "
<< "two columns, if they involve text operations.\n";
continue;
}
if (a[i]._isOptional || b[j]._isOptional) {
// Join the two optional columns using an optional join
SubtreePlan plan = optionalJoin(a[i], b[j]);
plan._idsOfIncludedNodes = a[i]._idsOfIncludedNodes;
plan.addAllNodes(b[j]._idsOfIncludedNodes);
plan._idsOfIncludedFilters = a[i]._idsOfIncludedFilters;
plan._idsOfIncludedFilters |= b[j]._idsOfIncludedFilters;
candidates[getPruningKey(plan, plan._qet->resultSortedOn())]
.emplace_back(plan);
continue;
}
if (jcs.size() == 2) {
// SPECIAL CASE: Cyclic queries -> join on exactly two columns
// Forbid a join between two dummies.
if ((a[i]._qet.get()->getType() == QueryExecutionTree::SCAN &&
a[i]._qet.get()->getRootOperation()->getResultWidth() == 3) &&
(b[j]._qet.get()->getType() == QueryExecutionTree::SCAN &&
b[j]._qet.get()->getRootOperation()->getResultWidth() == 3)) {
continue;
}
// Check if a sub-result has to be re-sorted
// Consider both ways to order join columns as primary / secondary
// Make four iterations instead of two so that first and second
// column can be swapped and more trees are constructed (of which
// the optimal solution will be picked).
// The order plays a role for the efficient implementation for
// filtering directly with a scan's result.
for (size_t n = 0; n < 4; ++n) {
size_t c = n / 2;
size_t swap = n % 2;
std::shared_ptr<QueryExecutionTree> left(
new QueryExecutionTree(_qec));
std::shared_ptr<QueryExecutionTree> right(
new QueryExecutionTree(_qec));
if (a[i]._qet.get()->resultSortedOn() == jcs[c][(0 + swap) % 2] &&
(a[i]._qet.get()->getResultWidth() == 2 ||
a[i]._qet.get()->getType() == QueryExecutionTree::SCAN)) {
left = a[i]._qet;
} else {
// Create an order by operation.
vector<pair<size_t, bool>> sortIndices;
sortIndices.emplace_back(
std::make_pair(jcs[c][(0 + swap) % 2], false));
sortIndices.emplace_back(
std::make_pair(jcs[(c + 1) % 2][(0 + swap) % 2], false));
std::shared_ptr<Operation> orderBy(
new OrderBy(_qec, a[i]._qet, sortIndices));
left->setVariableColumns(a[i]._qet->getVariableColumnMap());
left->setOperation(QueryExecutionTree::ORDER_BY, orderBy);
}
if (b[j]._qet.get()->resultSortedOn() == jcs[c][(1 + swap) % 2] &&
b[j]._qet.get()->getResultWidth() == 2) {
right = b[j]._qet;
} else {
// Create a sort operation.
// Create an order by operation.
vector<pair<size_t, bool>> sortIndices;
sortIndices.emplace_back(
std::make_pair(jcs[c][(1 + swap) % 2], false));
sortIndices.emplace_back(
std::make_pair(jcs[(c + 1) % 2][(1 + swap) % 2], false));
std::shared_ptr<Operation> orderBy(
new OrderBy(_qec, b[j]._qet, sortIndices));
right->setVariableColumns(b[j]._qet->getVariableColumnMap());
right->setOperation(QueryExecutionTree::ORDER_BY, orderBy);
}
// Create the join operation.
SubtreePlan plan(_qec);
auto& tree = *plan._qet.get();
std::shared_ptr<Operation> join(
new TwoColumnJoin(_qec, left, right, jcs));
tree.setVariableColumns(
static_cast<TwoColumnJoin*>(join.get())->getVariableColumns());
tree.setOperation(QueryExecutionTree::TWO_COL_JOIN, join);
plan._idsOfIncludedFilters = a[i]._idsOfIncludedFilters;
plan._idsOfIncludedNodes = a[i]._idsOfIncludedNodes;
plan.addAllNodes(b[j]._idsOfIncludedNodes);
candidates[getPruningKey(plan, jcs[c][(0 + swap) % 2])]
.emplace_back(plan);
}
continue;
}
// CASE: JOIN ON ONE COLUMN ONLY.
if ((a[i]._qet.get()->getType() ==
QueryExecutionTree::OperationType::TEXT_WITHOUT_FILTER ||
b[j]._qet.get()->getType() ==
QueryExecutionTree::OperationType::TEXT_WITHOUT_FILTER)) {
// If one of the join results is a text operation without filter
// also consider using the other one as filter and thus
// turning this join into a text operation with filter, instead,
bool aTextOp = true;
// If both are TextOps, the smaller one will be used as filter.
if (a[i]._qet.get()->getType() !=
QueryExecutionTree::OperationType::TEXT_WITHOUT_FILTER ||
(b[j]._qet.get()->getType() ==
QueryExecutionTree::OperationType::TEXT_WITHOUT_FILTER &&
b[j]._qet.get()->getSizeEstimate() >
a[i]._qet.get()->getSizeEstimate())) {
aTextOp = false;
}
const SubtreePlan& textPlan = aTextOp ? a[i] : b[j];
const SubtreePlan& filterPlan = aTextOp ? b[j] : a[i];
size_t otherPlanJc = aTextOp ? jcs[0][1] : jcs[0][0];
SubtreePlan plan(_qec);
plan._idsOfIncludedNodes = filterPlan._idsOfIncludedNodes;
plan._idsOfIncludedNodes |= textPlan._idsOfIncludedNodes;
plan._idsOfIncludedFilters = filterPlan._idsOfIncludedFilters;