Skip to content

Commit

Permalink
Add TopN optimization in physical plan mapping
Browse files Browse the repository at this point in the history
  • Loading branch information
kryonix committed Mar 21, 2024
1 parent 4a1f7d9 commit 80457f7
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/execution/physical_plan/plan_limit.cpp
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
#include "duckdb/execution/operator/helper/physical_limit.hpp"
#include "duckdb/execution/operator/helper/physical_streaming_limit.hpp"
#include "duckdb/execution/operator/helper/physical_limit_percent.hpp"
#include "duckdb/execution/operator/helper/physical_streaming_limit.hpp"
#include "duckdb/execution/operator/order/physical_top_n.hpp"
#include "duckdb/execution/physical_plan_generator.hpp"
#include "duckdb/main/config.hpp"
#include "duckdb/planner/operator/logical_limit.hpp"
#include "duckdb/planner/operator/logical_order.hpp"

namespace duckdb {

Expand All @@ -12,6 +14,22 @@ unique_ptr<PhysicalOperator> PhysicalPlanGenerator::CreatePlan(LogicalLimit &op)

auto plan = CreatePlan(*op.children[0]);

if (plan->type == PhysicalOperatorType::ORDER_BY && op.limit_val.Type() == LimitNodeType::CONSTANT_VALUE &&
op.offset_val.Type() != LimitNodeType::EXPRESSION_VALUE) {
auto &order_by = plan->Cast<PhysicalOrder>();
// Can not use TopN operator if PhysicalOrder uses projections
if (order_by.projections.empty()) {
idx_t offset_val = 0;
if (op.offset_val.Type() == LimitNodeType::CONSTANT_VALUE) {
offset_val = op.offset_val.GetConstantValue();
}
auto top_n = make_uniq<PhysicalTopN>(op.types, std::move(order_by.orders), op.limit_val.GetConstantValue(),
offset_val, op.estimated_cardinality);
top_n->children.push_back(std::move(order_by.children[0]));
return std::move(top_n);
}
}

unique_ptr<PhysicalOperator> limit;
switch (op.limit_val.Type()) {
case LimitNodeType::EXPRESSION_PERCENTAGE:
Expand Down

0 comments on commit 80457f7

Please sign in to comment.