datafusion_functions_aggregate_common/
merge_arrays.rs

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
18use arrow::compute::SortOptions;
19use datafusion_common::utils::compare_rows;
20use datafusion_common::{exec_err, ScalarValue};
21use std::cmp::Ordering;
22use std::collections::{BinaryHeap, VecDeque};
23
24/// This is a wrapper struct to be able to correctly merge `ARRAY_AGG` data from
25/// multiple partitions using `BinaryHeap`. When used inside `BinaryHeap`, this
26/// struct returns smallest `CustomElement`, where smallest is determined by
27/// `ordering` values (`Vec<ScalarValue>`) according to `sort_options`.
28#[derive(Debug, PartialEq, Eq)]
29struct CustomElement<'a> {
30    /// Stores the partition this entry came from
31    branch_idx: usize,
32    /// Values to merge
33    value: ScalarValue,
34    // Comparison "key"
35    ordering: Vec<ScalarValue>,
36    /// Options defining the ordering semantics
37    sort_options: &'a [SortOptions],
38}
39
40impl<'a> CustomElement<'a> {
41    fn new(
42        branch_idx: usize,
43        value: ScalarValue,
44        ordering: Vec<ScalarValue>,
45        sort_options: &'a [SortOptions],
46    ) -> Self {
47        Self {
48            branch_idx,
49            value,
50            ordering,
51            sort_options,
52        }
53    }
54
55    fn ordering(
56        &self,
57        current: &[ScalarValue],
58        target: &[ScalarValue],
59    ) -> datafusion_common::Result<Ordering> {
60        // Calculate ordering according to `sort_options`
61        compare_rows(current, target, self.sort_options)
62    }
63}
64
65// Overwrite ordering implementation such that
66// - `self.ordering` values are used for comparison,
67// - When used inside `BinaryHeap` it is a min-heap.
68impl Ord for CustomElement<'_> {
69    fn cmp(&self, other: &Self) -> Ordering {
70        // Compares according to custom ordering
71        self.ordering(&self.ordering, &other.ordering)
72            // Convert max heap to min heap
73            .map(|ordering| ordering.reverse())
74            // This function return error, when `self.ordering` and `other.ordering`
75            // have different types (such as one is `ScalarValue::Int64`, other is `ScalarValue::Float32`)
76            // Here this case won't happen, because data from each partition will have same type
77            .unwrap()
78    }
79}
80
81impl PartialOrd for CustomElement<'_> {
82    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
83        Some(self.cmp(other))
84    }
85}
86
87/// This functions merges `values` array (`&[Vec<ScalarValue>]`) into single array `Vec<ScalarValue>`
88/// Merging done according to ordering values stored inside `ordering_values` (`&[Vec<Vec<ScalarValue>>]`)
89/// Inner `Vec<ScalarValue>` in the `ordering_values` can be thought as ordering information for the
90/// each `ScalarValue` in the `values` array.
91/// Desired ordering specified by `sort_options` argument (Should have same size with inner `Vec<ScalarValue>`
92/// of the `ordering_values` array).
93///
94/// As an example
95/// values can be \[
96///      \[1, 2, 3, 4, 5\],
97///      \[1, 2, 3, 4\],
98///      \[1, 2, 3, 4, 5, 6\],
99/// \]
100/// In this case we will be merging three arrays (doesn't have to be same size)
101/// and produce a merged array with size 15 (sum of 5+4+6)
102/// Merging will be done according to ordering at `ordering_values` vector.
103/// As an example `ordering_values` can be [
104///      \[(1, a), (2, b), (3, b), (4, a), (5, b) \],
105///      \[(1, a), (2, b), (3, b), (4, a) \],
106///      \[(1, b), (2, c), (3, d), (4, e), (5, a), (6, b) \],
107/// ]
108/// For each ScalarValue in the `values` we have a corresponding `Vec<ScalarValue>` (like timestamp of it)
109/// for the example above `sort_options` will have size two, that defines ordering requirement of the merge.
110/// Inner `Vec<ScalarValue>`s of the `ordering_values` will be compared according `sort_options` (Their sizes should match)
111pub fn merge_ordered_arrays(
112    // We will merge values into single `Vec<ScalarValue>`.
113    values: &mut [VecDeque<ScalarValue>],
114    // `values` will be merged according to `ordering_values`.
115    // Inner `Vec<ScalarValue>` can be thought as ordering information for the
116    // each `ScalarValue` in the values`.
117    ordering_values: &mut [VecDeque<Vec<ScalarValue>>],
118    // Defines according to which ordering comparisons should be done.
119    sort_options: &[SortOptions],
120) -> datafusion_common::Result<(Vec<ScalarValue>, Vec<Vec<ScalarValue>>)> {
121    // Keep track the most recent data of each branch, in binary heap data structure.
122    let mut heap = BinaryHeap::<CustomElement>::new();
123
124    if values.len() != ordering_values.len()
125        || values
126            .iter()
127            .zip(ordering_values.iter())
128            .any(|(vals, ordering_vals)| vals.len() != ordering_vals.len())
129    {
130        return exec_err!(
131            "Expects values arguments and/or ordering_values arguments to have same size"
132        );
133    }
134    let n_branch = values.len();
135    let mut merged_values = vec![];
136    let mut merged_orderings = vec![];
137    // Continue iterating the loop until consuming data of all branches.
138    loop {
139        let minimum = if let Some(minimum) = heap.pop() {
140            minimum
141        } else {
142            // Heap is empty, fill it with the next entries from each branch.
143            for branch_idx in 0..n_branch {
144                if let Some(orderings) = ordering_values[branch_idx].pop_front() {
145                    // Their size should be same, we can safely .unwrap here.
146                    let value = values[branch_idx].pop_front().unwrap();
147                    // Push the next element to the heap:
148                    heap.push(CustomElement::new(
149                        branch_idx,
150                        value,
151                        orderings,
152                        sort_options,
153                    ));
154                }
155                // If None, we consumed this branch, skip it.
156            }
157
158            // Now we have filled the heap, get the largest entry (this will be
159            // the next element in merge).
160            if let Some(minimum) = heap.pop() {
161                minimum
162            } else {
163                // Heap is empty, this means that all indices are same with
164                // `end_indices`. We have consumed all of the branches, merge
165                // is completed, exit from the loop:
166                break;
167            }
168        };
169        let CustomElement {
170            branch_idx,
171            value,
172            ordering,
173            ..
174        } = minimum;
175        // Add minimum value in the heap to the result
176        merged_values.push(value);
177        merged_orderings.push(ordering);
178
179        // If there is an available entry, push next entry in the most
180        // recently consumed branch to the heap.
181        if let Some(orderings) = ordering_values[branch_idx].pop_front() {
182            // Their size should be same, we can safely .unwrap here.
183            let value = values[branch_idx].pop_front().unwrap();
184            // Push the next element to the heap:
185            heap.push(CustomElement::new(
186                branch_idx,
187                value,
188                orderings,
189                sort_options,
190            ));
191        }
192    }
193
194    Ok((merged_values, merged_orderings))
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    use std::collections::VecDeque;
202    use std::sync::Arc;
203
204    use arrow::array::{ArrayRef, Int64Array};
205
206    use datafusion_common::utils::get_row_at_idx;
207    use datafusion_common::{Result, ScalarValue};
208
209    #[test]
210    fn test_merge_asc() -> Result<()> {
211        let lhs_arrays: Vec<ArrayRef> = vec![
212            Arc::new(Int64Array::from(vec![0, 0, 1, 1, 2])),
213            Arc::new(Int64Array::from(vec![0, 1, 2, 3, 4])),
214        ];
215        let n_row = lhs_arrays[0].len();
216        let lhs_orderings = (0..n_row)
217            .map(|idx| get_row_at_idx(&lhs_arrays, idx))
218            .collect::<Result<VecDeque<_>>>()?;
219
220        let rhs_arrays: Vec<ArrayRef> = vec![
221            Arc::new(Int64Array::from(vec![0, 0, 1, 1, 2])),
222            Arc::new(Int64Array::from(vec![0, 1, 2, 3, 4])),
223        ];
224        let n_row = rhs_arrays[0].len();
225        let rhs_orderings = (0..n_row)
226            .map(|idx| get_row_at_idx(&rhs_arrays, idx))
227            .collect::<Result<VecDeque<_>>>()?;
228        let sort_options = vec![
229            SortOptions {
230                descending: false,
231                nulls_first: false,
232            },
233            SortOptions {
234                descending: false,
235                nulls_first: false,
236            },
237        ];
238
239        let lhs_vals_arr = Arc::new(Int64Array::from(vec![0, 1, 2, 3, 4])) as ArrayRef;
240        let lhs_vals = (0..lhs_vals_arr.len())
241            .map(|idx| ScalarValue::try_from_array(&lhs_vals_arr, idx))
242            .collect::<Result<VecDeque<_>>>()?;
243
244        let rhs_vals_arr = Arc::new(Int64Array::from(vec![0, 1, 2, 3, 4])) as ArrayRef;
245        let rhs_vals = (0..rhs_vals_arr.len())
246            .map(|idx| ScalarValue::try_from_array(&rhs_vals_arr, idx))
247            .collect::<Result<VecDeque<_>>>()?;
248        let expected =
249            Arc::new(Int64Array::from(vec![0, 0, 1, 1, 2, 2, 3, 3, 4, 4])) as ArrayRef;
250        let expected_ts = vec![
251            Arc::new(Int64Array::from(vec![0, 0, 0, 0, 1, 1, 1, 1, 2, 2])) as ArrayRef,
252            Arc::new(Int64Array::from(vec![0, 0, 1, 1, 2, 2, 3, 3, 4, 4])) as ArrayRef,
253        ];
254
255        let (merged_vals, merged_ts) = merge_ordered_arrays(
256            &mut [lhs_vals, rhs_vals],
257            &mut [lhs_orderings, rhs_orderings],
258            &sort_options,
259        )?;
260        let merged_vals = ScalarValue::iter_to_array(merged_vals.into_iter())?;
261        let merged_ts = (0..merged_ts[0].len())
262            .map(|col_idx| {
263                ScalarValue::iter_to_array(
264                    (0..merged_ts.len())
265                        .map(|row_idx| merged_ts[row_idx][col_idx].clone()),
266                )
267            })
268            .collect::<Result<Vec<_>>>()?;
269
270        assert_eq!(&merged_vals, &expected);
271        assert_eq!(&merged_ts, &expected_ts);
272
273        Ok(())
274    }
275
276    #[test]
277    fn test_merge_desc() -> Result<()> {
278        let lhs_arrays: Vec<ArrayRef> = vec![
279            Arc::new(Int64Array::from(vec![2, 1, 1, 0, 0])),
280            Arc::new(Int64Array::from(vec![4, 3, 2, 1, 0])),
281        ];
282        let n_row = lhs_arrays[0].len();
283        let lhs_orderings = (0..n_row)
284            .map(|idx| get_row_at_idx(&lhs_arrays, idx))
285            .collect::<Result<VecDeque<_>>>()?;
286
287        let rhs_arrays: Vec<ArrayRef> = vec![
288            Arc::new(Int64Array::from(vec![2, 1, 1, 0, 0])),
289            Arc::new(Int64Array::from(vec![4, 3, 2, 1, 0])),
290        ];
291        let n_row = rhs_arrays[0].len();
292        let rhs_orderings = (0..n_row)
293            .map(|idx| get_row_at_idx(&rhs_arrays, idx))
294            .collect::<Result<VecDeque<_>>>()?;
295        let sort_options = vec![
296            SortOptions {
297                descending: true,
298                nulls_first: false,
299            },
300            SortOptions {
301                descending: true,
302                nulls_first: false,
303            },
304        ];
305
306        // Values (which will be merged) doesn't have to be ordered.
307        let lhs_vals_arr = Arc::new(Int64Array::from(vec![0, 1, 2, 1, 2])) as ArrayRef;
308        let lhs_vals = (0..lhs_vals_arr.len())
309            .map(|idx| ScalarValue::try_from_array(&lhs_vals_arr, idx))
310            .collect::<Result<VecDeque<_>>>()?;
311
312        let rhs_vals_arr = Arc::new(Int64Array::from(vec![0, 1, 2, 1, 2])) as ArrayRef;
313        let rhs_vals = (0..rhs_vals_arr.len())
314            .map(|idx| ScalarValue::try_from_array(&rhs_vals_arr, idx))
315            .collect::<Result<VecDeque<_>>>()?;
316        let expected =
317            Arc::new(Int64Array::from(vec![0, 0, 1, 1, 2, 2, 1, 1, 2, 2])) as ArrayRef;
318        let expected_ts = vec![
319            Arc::new(Int64Array::from(vec![2, 2, 1, 1, 1, 1, 0, 0, 0, 0])) as ArrayRef,
320            Arc::new(Int64Array::from(vec![4, 4, 3, 3, 2, 2, 1, 1, 0, 0])) as ArrayRef,
321        ];
322        let (merged_vals, merged_ts) = merge_ordered_arrays(
323            &mut [lhs_vals, rhs_vals],
324            &mut [lhs_orderings, rhs_orderings],
325            &sort_options,
326        )?;
327        let merged_vals = ScalarValue::iter_to_array(merged_vals.into_iter())?;
328        let merged_ts = (0..merged_ts[0].len())
329            .map(|col_idx| {
330                ScalarValue::iter_to_array(
331                    (0..merged_ts.len())
332                        .map(|row_idx| merged_ts[row_idx][col_idx].clone()),
333                )
334            })
335            .collect::<Result<Vec<_>>>()?;
336
337        assert_eq!(&merged_vals, &expected);
338        assert_eq!(&merged_ts, &expected_ts);
339        Ok(())
340    }
341}