-
Notifications
You must be signed in to change notification settings - Fork 1.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
implement lead and lag built-in window function #429
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,181 @@ | ||
// 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. | ||
|
||
//! Defines physical expression for `lead` and `lag` that can evaluated | ||
//! at runtime during query execution | ||
|
||
use crate::error::{DataFusionError, Result}; | ||
use crate::physical_plan::window_functions::PartitionEvaluator; | ||
use crate::physical_plan::{window_functions::BuiltInWindowFunctionExpr, PhysicalExpr}; | ||
use arrow::array::ArrayRef; | ||
use arrow::compute::kernels::window::shift; | ||
use arrow::datatypes::{DataType, Field}; | ||
use arrow::record_batch::RecordBatch; | ||
use std::any::Any; | ||
use std::ops::Range; | ||
use std::sync::Arc; | ||
|
||
/// window shift expression | ||
#[derive(Debug)] | ||
pub struct WindowShift { | ||
name: String, | ||
data_type: DataType, | ||
shift_offset: i64, | ||
expr: Arc<dyn PhysicalExpr>, | ||
} | ||
|
||
/// lead() window function | ||
pub fn lead( | ||
name: String, | ||
data_type: DataType, | ||
expr: Arc<dyn PhysicalExpr>, | ||
) -> WindowShift { | ||
WindowShift { | ||
name, | ||
data_type, | ||
shift_offset: -1, | ||
expr, | ||
} | ||
} | ||
|
||
/// lag() window function | ||
pub fn lag( | ||
name: String, | ||
data_type: DataType, | ||
expr: Arc<dyn PhysicalExpr>, | ||
) -> WindowShift { | ||
WindowShift { | ||
name, | ||
data_type, | ||
shift_offset: 1, | ||
expr, | ||
} | ||
} | ||
|
||
impl BuiltInWindowFunctionExpr for WindowShift { | ||
/// Return a reference to Any that can be used for downcasting | ||
fn as_any(&self) -> &dyn Any { | ||
self | ||
} | ||
|
||
fn field(&self) -> Result<Field> { | ||
let nullable = true; | ||
Ok(Field::new(&self.name, self.data_type.clone(), nullable)) | ||
} | ||
|
||
fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> { | ||
vec![self.expr.clone()] | ||
} | ||
|
||
fn name(&self) -> &str { | ||
&self.name | ||
} | ||
|
||
fn create_evaluator( | ||
&self, | ||
batch: &RecordBatch, | ||
) -> Result<Box<dyn PartitionEvaluator>> { | ||
let values = self | ||
.expressions() | ||
.iter() | ||
.map(|e| e.evaluate(batch)) | ||
.map(|r| r.map(|v| v.into_array(batch.num_rows()))) | ||
.collect::<Result<Vec<_>>>()?; | ||
Ok(Box::new(WindowShiftEvaluator { | ||
shift_offset: self.shift_offset, | ||
values, | ||
})) | ||
} | ||
} | ||
|
||
pub(crate) struct WindowShiftEvaluator { | ||
shift_offset: i64, | ||
values: Vec<ArrayRef>, | ||
} | ||
|
||
impl PartitionEvaluator for WindowShiftEvaluator { | ||
fn evaluate_partition(&self, partition: Range<usize>) -> Result<ArrayRef> { | ||
let value = &self.values[0]; | ||
let value = value.slice(partition.start, partition.end - partition.start); | ||
shift(value.as_ref(), self.shift_offset).map_err(DataFusionError::ArrowError) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
use crate::error::Result; | ||
use crate::physical_plan::expressions::Column; | ||
use arrow::record_batch::RecordBatch; | ||
use arrow::{array::*, datatypes::*}; | ||
|
||
fn test_i32_result(expr: WindowShift, expected: Int32Array) -> Result<()> { | ||
let arr: ArrayRef = Arc::new(Int32Array::from(vec![1, -2, 3, -4, 5, -6, 7, 8])); | ||
let values = vec![arr]; | ||
let schema = Schema::new(vec![Field::new("arr", DataType::Int32, false)]); | ||
let batch = RecordBatch::try_new(Arc::new(schema), values.clone())?; | ||
let result = expr.create_evaluator(&batch)?.evaluate(vec![0..8])?; | ||
assert_eq!(1, result.len()); | ||
let result = result[0].as_any().downcast_ref::<Int32Array>().unwrap(); | ||
assert_eq!(expected, *result); | ||
Ok(()) | ||
} | ||
|
||
#[test] | ||
fn lead_lag_window_shift() -> Result<()> { | ||
test_i32_result( | ||
lead( | ||
"lead".to_owned(), | ||
DataType::Float32, | ||
Arc::new(Column::new("c3", 0)), | ||
), | ||
vec![ | ||
Some(-2), | ||
Some(3), | ||
Some(-4), | ||
Some(5), | ||
Some(-6), | ||
Some(7), | ||
Some(8), | ||
None, | ||
] | ||
.iter() | ||
.collect::<Int32Array>(), | ||
)?; | ||
|
||
test_i32_result( | ||
lag( | ||
"lead".to_owned(), | ||
DataType::Float32, | ||
Arc::new(Column::new("c3", 0)), | ||
), | ||
vec![ | ||
None, | ||
Some(1), | ||
Some(-2), | ||
Some(3), | ||
Some(-4), | ||
Some(5), | ||
Some(-6), | ||
Some(7), | ||
] | ||
.iter() | ||
.collect::<Int32Array>(), | ||
)?; | ||
Ok(()) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
29 changes: 29 additions & 0 deletions
29
integration-tests/sqls/partitioned_window_built_in_functions.sql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
-- 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. | ||
|
||
SELECT | ||
c9, | ||
row_number() OVER (PARTITION BY c2 ORDER BY c9) row_num, | ||
lead(c9) OVER (PARTITION BY c2 ORDER BY c9) lead_c9, | ||
lag(c9) OVER (PARTITION BY c2 ORDER BY c9) lag_c9, | ||
first_value(c9) OVER (PARTITION BY c2 ORDER BY c9) first_c9, | ||
first_value(c9) OVER (PARTITION BY c2 ORDER BY c9 DESC) first_c9_desc, | ||
last_value(c9) OVER (PARTITION BY c2 ORDER BY c9) last_c9, | ||
last_value(c9) OVER (PARTITION BY c2 ORDER BY c9 DESC) last_c9_desc, | ||
nth_value(c9, 2) OVER (PARTITION BY c2 ORDER BY c9) second_c9, | ||
nth_value(c9, 2) OVER (PARTITION BY c2 ORDER BY c9 DESC) second_c9_desc | ||
FROM test | ||
ORDER BY c9; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
do you need to restrict the window to the partition bounds? If the input array had 10 rows in 2 partitions, wouldn't this code produce 2 output partitions of 10 rows each (rather than 2 output partitions of 5 rows each)?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@alamb good catch, this is fixed and add with integration tests.