saadtajwar commented on code in PR #23824:
URL: https://github.com/apache/datafusion/pull/23824#discussion_r3640672809


##########
datafusion/optimizer/src/replace_filter_top1.rs:
##########
@@ -0,0 +1,624 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+//! [`ReplaceFilterTop1`] rewrites a "top-1 per group" `row_number()` filter
+//! into a `first_value` aggregate.
+
+use crate::optimizer::{ApplyOrder, ApplyOrder::BottomUp};
+use crate::{OptimizerConfig, OptimizerRule};
+use std::sync::Arc;
+
+use datafusion_common::ScalarValue;
+use datafusion_common::tree_node::Transformed;
+use datafusion_common::{Column, Result};
+use datafusion_expr::{
+    Aggregate, BinaryExpr, Expr, Filter, LogicalPlan, Operator, Projection, 
SortExpr,
+};
+use datafusion_expr::{ExprFunctionExt, LogicalPlanBuilder, lit};
+
+/// Optimizer that replaces a logical `Filter` with a top-1 predicate over a
+/// `row_number()` window with an aggregate.
+///
+/// ```text
+/// SELECT * FROM (
+///     SELECT *,
+///     ROW_NUMBER() OVER (PARTITION BY p ORDER BY o DESC) AS rn
+///     FROM t
+/// ) WHERE rn = 1
+/// ```
+///
+/// Input plan:
+/// ```text
+/// Filter: rn = 1                    -- or rn <= 1, or rn < 2
+///     [Projection: ...]              -- optional passthrough projection
+///         WindowAggr: row_number() OVER (PARTITION BY p ORDER BY o DESC) AS 
rn
+/// child
+/// ```
+///
+/// Rewritten plan:
+/// ```text
+/// Projection: <original Filter output schema; rn -> literal 1>
+///     Aggregate:
+///      group_by=[p]
+///      aggr=[first_value(col_i ORDER BY o DESC) for each non-partition col_i]
+///     child
+/// ```
+///
+/// Notes:
+/// - the window function must be `row_number`
+/// - filter predicate must be "top-1" (rn = 1, <= 1, < 2)
+/// - window has a `PARTITION BY` clause
+/// - gated behind the `optimizer.enable_row_number_to_aggregate` config 
option (off by default)
+#[derive(Default, Debug)]
+pub struct ReplaceFilterTop1 {}
+
+impl ReplaceFilterTop1 {
+    #[expect(missing_docs)]
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+impl OptimizerRule for ReplaceFilterTop1 {
+    fn supports_rewrite(&self) -> bool {
+        true
+    }
+
+    fn rewrite(
+        &self,
+        plan: LogicalPlan,
+        config: &dyn OptimizerConfig,
+    ) -> Result<Transformed<LogicalPlan>> {
+        if !config.options().optimizer.enable_row_number_to_aggregate {
+            return Ok(Transformed::no(plan));
+        }
+
+        let LogicalPlan::Filter(Filter {
+            ref predicate,
+            ref input,
+            ..
+        }) = plan
+        else {
+            return Ok(Transformed::no(plan));
+        };
+
+        let Some(WindowTop1 {
+            order_by,
+            partition_by,
+            rn_col,
+            input_cols,
+            child,
+            projection,
+        }) = validate_window_input(input)
+        else {
+            return Ok(Transformed::no(plan));
+        };
+
+        // Resolve the rn name the filter references (projection alias if 
present)
+        let rn_ref_name = match projection {
+            None => rn_col.name.clone(),
+            Some(p) => match rn_passthrough_name(p, &rn_col) {
+                Some(name) => name,
+                None => return Ok(Transformed::no(plan)),
+            },
+        };
+        if !has_valid_predicate(predicate, &rn_ref_name) {
+            return Ok(Transformed::no(plan));
+        }
+
+        let is_partition = |c: &Column| {
+            partition_by.iter().any(|e| matches!(e, Expr::Column(p) if p.name 
== c.name && p.relation == c.relation))
+        };
+
+        // Group by the partition keys and take `first_value(col ORDER BY 
...)` for every other
+        // input column, aliased back to that column's qualifier+name
+        let first_value = 
config.function_registry().unwrap().udaf("first_value")?;

Review Comment:
   Oh good catch, thanks! Changed!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to