xiedeyantu commented on code in PR #21088: URL: https://github.com/apache/datafusion/pull/21088#discussion_r2969599296
########## datafusion/optimizer/src/multi_distinct_count_rewrite.rs: ########## @@ -0,0 +1,436 @@ +// 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. + +//! Rewrites a single [`Aggregate`] that contains multiple `COUNT(DISTINCT ...)` +//! into a join of smaller aggregates so each distinct is computed with one +//! accumulator set, reducing peak memory for high-cardinality distincts. + +use std::sync::Arc; + +use crate::optimizer::ApplyOrder; +use crate::{OptimizerConfig, OptimizerRule}; + +use datafusion_common::{ + Column, JoinConstraint, NullEquality, Result, tree_node::Transformed, +}; +use datafusion_expr::builder::project; +use datafusion_expr::expr::{AggregateFunction, AggregateFunctionParams, ScalarFunction}; +use datafusion_expr::logical_plan::{ + Aggregate, Join, JoinType, LogicalPlan, SubqueryAlias, +}; +use datafusion_expr::{Expr, col, lit, logical_plan::LogicalPlanBuilder}; + +const MAX_DISTINCT_REWRITE_BRANCHES: usize = 8; + +/// Optimizer rule: multiple `COUNT(DISTINCT ...)` → join of per-distinct sub-aggregates. +#[derive(Default, Debug)] +pub struct MultiDistinctCountRewrite {} + +impl MultiDistinctCountRewrite { + /// Create a new rule instance. + pub fn new() -> Self { + Self {} + } + + fn is_simple_count_distinct( + e: &Expr, + ) -> Option<(Arc<datafusion_expr::AggregateUDF>, Expr)> { + if let Expr::AggregateFunction(AggregateFunction { func, params }) = e { + let AggregateFunctionParams { + distinct, + args, + filter, + order_by, + .. + } = ¶ms; + if func.name().eq_ignore_ascii_case("count") + && *distinct + && args.len() == 1 + && filter.is_none() + && order_by.is_empty() + { + let arg = args.first().cloned()?; + if Self::is_safe_distinct_arg(&arg) { + return Some((Arc::clone(func), arg)); + } + } + } + None + } + + fn is_safe_distinct_arg(e: &Expr) -> bool { + if e.is_volatile() { + return false; + } + match e { + Expr::Column(_) => true, + Expr::ScalarFunction(ScalarFunction { func, args }) => { + matches!(func.name().to_ascii_lowercase().as_str(), "lower" | "upper") + && args.len() == 1 + && matches!(args.first(), Some(Expr::Column(_))) + } + Expr::Cast(cast) => matches!(cast.expr.as_ref(), Expr::Column(_)), + _ => false, + } + } + + fn is_simple_group_expr(e: &Expr) -> bool { + matches!(e, Expr::Column(_)) + } + + fn contains_grouping_set(group_expr: &[Expr]) -> bool { + group_expr + .first() + .is_some_and(|e| matches!(e, Expr::GroupingSet(_))) + } +} + +impl OptimizerRule for MultiDistinctCountRewrite { + fn name(&self) -> &str { + "multi_distinct_count_rewrite" + } + + fn apply_order(&self) -> Option<ApplyOrder> { + Some(ApplyOrder::BottomUp) + } + + fn rewrite( + &self, + plan: LogicalPlan, + config: &dyn OptimizerConfig, + ) -> Result<Transformed<LogicalPlan>> { + let LogicalPlan::Aggregate(Aggregate { + input, + aggr_expr, + schema, + group_expr, + .. + }) = plan + else { + return Ok(Transformed::no(plan)); + }; + + if Self::contains_grouping_set(&group_expr) { + return Ok(Transformed::no(LogicalPlan::Aggregate(Aggregate::try_new( + input, group_expr, aggr_expr, + )?))); + } + + if !group_expr.iter().all(Self::is_simple_group_expr) { + return Ok(Transformed::no(LogicalPlan::Aggregate(Aggregate::try_new( + input, group_expr, aggr_expr, + )?))); + } + + let group_size = group_expr.len(); + let mut distinct_list: Vec<(Expr, usize, Arc<datafusion_expr::AggregateUDF>)> = + vec![]; + let mut other_list: Vec<(Expr, usize)> = vec![]; + + for (i, e) in aggr_expr.iter().enumerate() { + if let Some((func, arg)) = Self::is_simple_count_distinct(e) { Review Comment: Could you simulate a query like SELECT g, COUNT(DISTINCT lower(b)), ... GROUP BY g where the values of b are 'Abc' and 'aBC'? I understand that cast presents a similar issue. For instance, when casting a double to an int, the original double values might be 1.2 and 1.3. -- 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]
