avantgardnerio commented on code in PR #7192: URL: https://github.com/apache/arrow-datafusion/pull/7192#discussion_r1294013752
########## datafusion/core/src/physical_plan/aggregates/priority_map.rs: ########## @@ -0,0 +1,551 @@ +// 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. + +//! A memory-conscious aggregation implementation that limits group buckets to a fixed number + +use std::cmp::Ordering; +use crate::physical_plan::aggregates::{ + aggregate_expressions, evaluate_group_by, evaluate_many, group_schema, AggregateExec, + PhysicalGroupBy, +}; +use crate::physical_plan::{RecordBatchStream, SendableRecordBatchStream}; +use arrow_array::{Array, ArrayRef, Int64Array, RecordBatch, StringArray}; +use arrow_schema::{DataType, SchemaRef, SortOptions}; +use datafusion_common::DataFusionError; +use datafusion_common::Result; +use datafusion_execution::TaskContext; +use datafusion_physical_expr::PhysicalExpr; +use futures::stream::{Stream, StreamExt}; +use std::collections::{BTreeMap, btree_map}; +use std::hash::{Hash}; +use std::pin::Pin; +use std::sync::Arc; +use std::task::{Context, Poll}; +use ahash::RandomState; +use hashbrown::raw::{RawDrain, RawTable}; +use datafusion_physical_expr::hash_utils::create_hashes; + +pub struct GroupedPriorityQueueAggregateStream { + schema: SchemaRef, + input: SendableRecordBatchStream, + aggregate_arguments: Vec<Vec<Arc<dyn PhysicalExpr>>>, + group_by: PhysicalGroupBy, + aggregator: Box<dyn LimitedAggregator>, +} + +impl GroupedPriorityQueueAggregateStream { + pub fn new( + agg: &AggregateExec, + context: Arc<TaskContext>, + partition: usize, + limit: usize, + ) -> Result<Self> { + let agg_schema = Arc::clone(&agg.schema); + let agg_group_by = agg.group_by.clone(); + + let input = agg.input.execute(partition, Arc::clone(&context))?; + + let aggregate_arguments = + aggregate_expressions(&agg.aggr_expr, &agg.mode, agg_group_by.expr.len())?; + + let (val_field, descending) = agg + .get_minmax_desc() + .ok_or_else(|| DataFusionError::Execution("Min/max required".to_string()))?; + let sort = SortOptions { + descending, + nulls_first: false, + }; + + // TODO: filters + + let group_schema = group_schema(&agg_schema, agg_group_by.expr.len()); + + let id_count = group_schema.fields().len(); + let id_field = group_schema.fields().first().map(|f| f.data_type()); + let ag: Box<dyn LimitedAggregator> = + match (id_count, id_field, val_field.data_type()) { + // TODO: solve combinatorial issue + (1, Some(DataType::Utf8), DataType::Int64) => { + Box::new(StringInt64Aggregator::new(limit, descending)?) + } + _ => { + panic!("Type not implemented: {:?} {:?}", id_field, val_field.data_type()); + } + }; + + Ok(GroupedPriorityQueueAggregateStream { + schema: agg_schema, + input, + aggregate_arguments, + group_by: agg_group_by, + aggregator: ag, + }) + } +} + +impl RecordBatchStream for GroupedPriorityQueueAggregateStream { + fn schema(&self) -> SchemaRef { + self.schema.clone() + } +} + +trait LimitedAggregator: Send { + fn intern(&mut self, ids: ArrayRef, vals: &[ArrayRef]) -> Result<()>; + fn emit(&mut self) -> Result<Vec<ArrayRef>>; + fn is_empty(&self) -> bool; +} + +// TODO: macro to create for all types, see new_group_values +// TODO: solve combinatorial issue to not explode compiled binary size +struct StringInt64Aggregator { + descending: bool, + random_state: RandomState, + priority_map: PriorityMap<String, i64>, +} + +impl StringInt64Aggregator { + pub fn new(limit: usize, descending: bool) -> Result<Self> { + Ok(Self { + descending, + random_state: Default::default(), + priority_map: PriorityMap::new(limit), + }) + } +} + +impl LimitedAggregator for StringInt64Aggregator { + fn intern(&mut self, ids: ArrayRef, vals: &[ArrayRef]) -> Result<()> { + let vals = match vals { + [] => Err(DataFusionError::Execution("ID column required".to_string()))?, + [vals] => vals, + _ => Err(DataFusionError::Execution( + "One ID column required".to_string(), + ))?, + }; + let mut hashes = vec![0; ids.len()]; + let cols: Vec<ArrayRef> = vec![ids.clone()]; + create_hashes(cols.as_slice(), &self.random_state, &mut hashes)?; + + let ids = ids.as_any().downcast_ref::<StringArray>().ok_or_else(|| { + DataFusionError::Execution("Expected StringArray".to_string()) + })?; + let vals = vals.as_any().downcast_ref::<Int64Array>().ok_or_else(|| { + DataFusionError::Execution("Expected Int64Array".to_string()) + })?; + for row_idx in 0..ids.len() { + let id = ids.value(row_idx); // TODO: aggregate NULL id + let hash = hashes[row_idx]; + let val = vals.value(row_idx); + + if self.descending { + // TODO: val = Reverse(val) + } + self.priority_map.insert(id.to_string(), hash, val)?; Review Comment: I was leaving the door open for custom stuff like `Row` that needs to be converted via `row.owned()` into an `OwnedRow` which didn't fit that pattern. -- 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]
