alamb commented on code in PR #7192: URL: https://github.com/apache/arrow-datafusion/pull/7192#discussion_r1284750607
########## datafusion/core/src/physical_optimizer/limit_aggregation.rs: ########## @@ -0,0 +1,88 @@ +// 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. + +//! An optimizer rule that detects aggregate operations that could use a limited bucket count + +use crate::physical_optimizer::PhysicalOptimizerRule; +use crate::physical_plan::aggregates::AggregateExec; +use crate::physical_plan::sorts::sort::SortExec; +use crate::physical_plan::ExecutionPlan; +use datafusion_common::config::ConfigOptions; +use datafusion_common::{DataFusionError, Result}; +use std::sync::Arc; + +pub struct LimitAggregation {} + +impl LimitAggregation { + pub fn new() -> Self { + Self {} + } + + fn recurse(plan: Arc<dyn ExecutionPlan>) -> Result<Arc<dyn ExecutionPlan>> { Review Comment: I think the standard DataFusion pattern is add or extend one of the existing physical optimizer rules to recognize the specific pattern this operator handles Something like https://github.com/apache/arrow-datafusion/blob/main/datafusion/core/src/physical_optimizer/replace_with_order_preserving_variants.rs perhaps The rewriting is handled by treenode/treenode rewriters: https://docs.rs/datafusion/latest/datafusion/common/tree_node/index.html ########## datafusion/core/src/physical_optimizer/limit_aggregation.rs: ########## @@ -0,0 +1,67 @@ +use std::sync::Arc; +use datafusion_common::config::ConfigOptions; +use crate::physical_optimizer::PhysicalOptimizerRule; +use crate::physical_plan::ExecutionPlan; +use crate::physical_plan::sorts::sort::SortExec; +use datafusion_common::{DataFusionError, Result}; +use crate::physical_plan::aggregates::AggregateExec; + +pub struct LimitAggregation { + +} + +impl LimitAggregation { + pub fn new() -> Self { + Self {} + } + + fn recurse(plan: Arc<dyn ExecutionPlan>) -> Result<Arc<dyn ExecutionPlan>> { + if let Some(sort) = plan.as_any().downcast_ref::<SortExec>() { + let children = sort.children(); + let child = match children.as_slice() { + [] => Err(DataFusionError::Execution("Sorts should have children".to_string()))?, + [child] => child, + _ => Err(DataFusionError::Execution("Sorts should have 1 child".to_string()))?, + }; + let binding = (*child).as_any(); + if let Some(aggr) = binding.downcast_ref::<AggregateExec>() { Review Comment: I filed https://github.com/apache/arrow-datafusion/issues/7198 to try and describe what the end usecase is so maybe that can help focus this conversation I also think it might end up being a very special operator for MIN/MAX w/ limit @comphead had the following pointer https://github.com/apache/arrow-datafusion/issues/6899#issuecomment-1631660067 for prior art > Spark does the similar way: it sorts and limits data per partition then sends the output to single partition where final sort/limit performed. Spark has the logic encapsulated in separate operator and looks like https://github.com/apache/spark/blob/master/sql/core/src/main/scala/org/apache/spark/sql/execution/limit.scala#L311 > it also contains optimization like if tuples already ordered it will skip the excessive ordering, the same happens for projection ########## datafusion/core/src/physical_plan/aggregates/priority_queue.rs: ########## @@ -0,0 +1,235 @@ +use uuid::Uuid; +use std::collections::{BTreeMap, HashMap}; +use std::pin::Pin; +use std::sync::Arc; +use std::task::{Context, Poll}; +use arrow::row::{OwnedRow, RowConverter, SortField}; +use arrow::util::pretty::print_batches; +use arrow_array::{RecordBatch}; +use arrow_schema::{DataType, SchemaRef, SortOptions}; +use futures::stream::{Stream, StreamExt}; +use hashbrown::HashSet; +use datafusion_common::DataFusionError; +use datafusion_execution::TaskContext; +use datafusion_physical_expr::{PhysicalExpr}; +use crate::physical_plan::aggregates::{aggregate_expressions, AggregateExec, evaluate_group_by, evaluate_many, group_schema, PhysicalGroupBy}; +use crate::physical_plan::{RecordBatchStream, SendableRecordBatchStream}; +use datafusion_common::Result; +use datafusion_physical_expr::expressions::{Max, Min}; + +pub(crate) struct GroupedPriorityQueueAggregateStream { + schema: SchemaRef, + input: SendableRecordBatchStream, + aggregate_arguments: Vec<Vec<Arc<dyn PhysicalExpr>>>, + group_by: PhysicalGroupBy, + group_converter: RowConverter, + value_converter: RowConverter, // TODO: use accumulators + group_to_val: HashMap<OwnedRow, OwnedRow>, // TODO: BTreeMap->BinaryHeap, OwnedRow->Rows + val_to_group: BTreeMap<OwnedRow, HashSet<OwnedRow>>, Review Comment: BinaryHeap sounds good -- 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]
