|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +use arrow_schema::{Field, Schema}; |
| 19 | +use datafusion::{arrow::datatypes::DataType, logical_expr::Volatility}; |
| 20 | +use datafusion_expr::function::AggregateFunctionSimplification; |
| 21 | +use datafusion_expr::simplify::SimplifyInfo; |
| 22 | + |
| 23 | +use std::{any::Any, sync::Arc}; |
| 24 | + |
| 25 | +use datafusion::arrow::{array::Float32Array, record_batch::RecordBatch}; |
| 26 | +use datafusion::error::Result; |
| 27 | +use datafusion::{assert_batches_eq, prelude::*}; |
| 28 | +use datafusion_common::cast::as_float64_array; |
| 29 | +use datafusion_expr::{ |
| 30 | + expr::{AggregateFunction, AggregateFunctionDefinition}, |
| 31 | + function::AccumulatorArgs, |
| 32 | + Accumulator, AggregateUDF, AggregateUDFImpl, GroupsAccumulator, Signature, |
| 33 | +}; |
| 34 | + |
| 35 | +/// This example shows how to use the AggregateUDFImpl::simplify API to simplify/replace user |
| 36 | +/// defined aggregate function with a different expression which is defined in the `simplify` method. |
| 37 | +
|
| 38 | +#[derive(Debug, Clone)] |
| 39 | +struct BetterAvgUdaf { |
| 40 | + signature: Signature, |
| 41 | +} |
| 42 | + |
| 43 | +impl BetterAvgUdaf { |
| 44 | + /// Create a new instance of the GeoMeanUdaf struct |
| 45 | + fn new() -> Self { |
| 46 | + Self { |
| 47 | + signature: Signature::exact(vec![DataType::Float64], Volatility::Immutable), |
| 48 | + } |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +impl AggregateUDFImpl for BetterAvgUdaf { |
| 53 | + fn as_any(&self) -> &dyn Any { |
| 54 | + self |
| 55 | + } |
| 56 | + |
| 57 | + fn name(&self) -> &str { |
| 58 | + "better_avg" |
| 59 | + } |
| 60 | + |
| 61 | + fn signature(&self) -> &Signature { |
| 62 | + &self.signature |
| 63 | + } |
| 64 | + |
| 65 | + fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { |
| 66 | + Ok(DataType::Float64) |
| 67 | + } |
| 68 | + |
| 69 | + fn accumulator(&self, _acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> { |
| 70 | + unimplemented!("should not be invoked") |
| 71 | + } |
| 72 | + |
| 73 | + fn state_fields( |
| 74 | + &self, |
| 75 | + _name: &str, |
| 76 | + _value_type: DataType, |
| 77 | + _ordering_fields: Vec<arrow_schema::Field>, |
| 78 | + ) -> Result<Vec<arrow_schema::Field>> { |
| 79 | + unimplemented!("should not be invoked") |
| 80 | + } |
| 81 | + |
| 82 | + fn groups_accumulator_supported(&self) -> bool { |
| 83 | + true |
| 84 | + } |
| 85 | + |
| 86 | + fn create_groups_accumulator(&self) -> Result<Box<dyn GroupsAccumulator>> { |
| 87 | + unimplemented!("should not get here"); |
| 88 | + } |
| 89 | + // we override method, to return new expression which would substitute |
| 90 | + // user defined function call |
| 91 | + fn simplify(&self) -> Option<AggregateFunctionSimplification> { |
| 92 | + // as an example for this functionality we replace UDF function |
| 93 | + // with build-in aggregate function to illustrate the use |
| 94 | + let simplify = |aggregate_function: datafusion_expr::expr::AggregateFunction, |
| 95 | + _: &dyn SimplifyInfo| { |
| 96 | + Ok(Expr::AggregateFunction(AggregateFunction { |
| 97 | + func_def: AggregateFunctionDefinition::BuiltIn( |
| 98 | + // yes it is the same Avg, `BetterAvgUdaf` was just a |
| 99 | + // marketing pitch :) |
| 100 | + datafusion_expr::aggregate_function::AggregateFunction::Avg, |
| 101 | + ), |
| 102 | + args: aggregate_function.args, |
| 103 | + distinct: aggregate_function.distinct, |
| 104 | + filter: aggregate_function.filter, |
| 105 | + order_by: aggregate_function.order_by, |
| 106 | + null_treatment: aggregate_function.null_treatment, |
| 107 | + })) |
| 108 | + }; |
| 109 | + |
| 110 | + Some(Box::new(simplify)) |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +// create local session context with an in-memory table |
| 115 | +fn create_context() -> Result<SessionContext> { |
| 116 | + use datafusion::datasource::MemTable; |
| 117 | + // define a schema. |
| 118 | + let schema = Arc::new(Schema::new(vec![ |
| 119 | + Field::new("a", DataType::Float32, false), |
| 120 | + Field::new("b", DataType::Float32, false), |
| 121 | + ])); |
| 122 | + |
| 123 | + // define data in two partitions |
| 124 | + let batch1 = RecordBatch::try_new( |
| 125 | + schema.clone(), |
| 126 | + vec![ |
| 127 | + Arc::new(Float32Array::from(vec![2.0, 4.0, 8.0])), |
| 128 | + Arc::new(Float32Array::from(vec![2.0, 2.0, 2.0])), |
| 129 | + ], |
| 130 | + )?; |
| 131 | + let batch2 = RecordBatch::try_new( |
| 132 | + schema.clone(), |
| 133 | + vec![ |
| 134 | + Arc::new(Float32Array::from(vec![16.0])), |
| 135 | + Arc::new(Float32Array::from(vec![2.0])), |
| 136 | + ], |
| 137 | + )?; |
| 138 | + |
| 139 | + let ctx = SessionContext::new(); |
| 140 | + |
| 141 | + // declare a table in memory. In spark API, this corresponds to createDataFrame(...). |
| 142 | + let provider = MemTable::try_new(schema, vec![vec![batch1], vec![batch2]])?; |
| 143 | + ctx.register_table("t", Arc::new(provider))?; |
| 144 | + Ok(ctx) |
| 145 | +} |
| 146 | + |
| 147 | +#[tokio::main] |
| 148 | +async fn main() -> Result<()> { |
| 149 | + let ctx = create_context()?; |
| 150 | + |
| 151 | + let better_avg = AggregateUDF::from(BetterAvgUdaf::new()); |
| 152 | + ctx.register_udaf(better_avg.clone()); |
| 153 | + |
| 154 | + let result = ctx |
| 155 | + .sql("SELECT better_avg(a) FROM t group by b") |
| 156 | + .await? |
| 157 | + .collect() |
| 158 | + .await?; |
| 159 | + |
| 160 | + let expected = [ |
| 161 | + "+-----------------+", |
| 162 | + "| better_avg(t.a) |", |
| 163 | + "+-----------------+", |
| 164 | + "| 7.5 |", |
| 165 | + "+-----------------+", |
| 166 | + ]; |
| 167 | + |
| 168 | + assert_batches_eq!(expected, &result); |
| 169 | + |
| 170 | + let df = ctx.table("t").await?; |
| 171 | + let df = df.aggregate(vec![], vec![better_avg.call(vec![col("a")])])?; |
| 172 | + |
| 173 | + let results = df.collect().await?; |
| 174 | + let result = as_float64_array(results[0].column(0))?; |
| 175 | + |
| 176 | + assert!((result.value(0) - 7.5).abs() < f64::EPSILON); |
| 177 | + println!("The average of [2,4,8,16] is {}", result.value(0)); |
| 178 | + |
| 179 | + Ok(()) |
| 180 | +} |
0 commit comments