Skip to main content

datafusion_functions_nested/
distance.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! [ScalarUDFImpl] definitions for array_distance function.
6
7use crate::utils::{make_scalar_function, needs_norm_scale, norm_scale};
8use arrow::array::{Array, ArrayRef, Float64Array, OffsetSizeTrait};
9use arrow::datatypes::{
10    DataType,
11    DataType::{FixedSizeList, LargeList, List, Null},
12};
13use datafusion_common::cast::{
14    as_float32_array, as_float64_array, as_generic_list_array, as_int32_array,
15    as_int64_array,
16};
17use datafusion_common::utils::{ListCoercion, coerced_type_with_base_type_only};
18use datafusion_common::{Result, exec_err, plan_err, utils::take_function_args};
19use datafusion_expr::{
20    ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
21    Volatility,
22};
23use datafusion_macros::user_doc;
24use itertools::Itertools;
25use std::sync::Arc;
26
27make_udf_expr_and_func!(
28    ArrayDistance,
29    array_distance,
30    array,
31    "returns the Euclidean distance between two one-dimensional numeric arrays.",
32    array_distance_udf
33);
34
35#[user_doc(
36    doc_section(label = "Array Functions"),
37    description = "Returns the Euclidean distance between two one-dimensional input arrays of equal length.",
38    syntax_example = "array_distance(array1, array2)",
39    sql_example = r#"```sql
40> select array_distance([1, 2], [1, 4]);
41+------------------------------------+
42| array_distance(List([1,2], [1,4])) |
43+------------------------------------+
44| 2.0                                |
45+------------------------------------+
46```"#,
47    argument(
48        name = "array1",
49        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
50    ),
51    argument(
52        name = "array2",
53        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
54    )
55)]
56#[derive(Debug, PartialEq, Eq, Hash)]
57pub struct ArrayDistance {
58    signature: Signature,
59    aliases: Vec<String>,
60}
61
62impl Default for ArrayDistance {
63    fn default() -> Self {
64        Self::new()
65    }
66}
67
68impl ArrayDistance {
69    pub fn new() -> Self {
70        Self {
71            signature: Signature::user_defined(Volatility::Immutable),
72            aliases: vec!["list_distance".to_string()],
73        }
74    }
75}
76
77impl ScalarUDFImpl for ArrayDistance {
78    fn name(&self) -> &str {
79        "array_distance"
80    }
81
82    fn signature(&self) -> &Signature {
83        &self.signature
84    }
85
86    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
87        Ok(DataType::Float64)
88    }
89
90    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
91        let [_, _] = take_function_args(self.name(), arg_types)?;
92        let coercion = Some(&ListCoercion::FixedSizedListToList);
93        let arg_types = arg_types.iter().map(|arg_type| match arg_type {
94            Null => Ok(coerced_type_with_base_type_only(
95                arg_type,
96                &DataType::Float64,
97                coercion,
98            )),
99            List(field) | LargeList(field) | FixedSizeList(field, _) => {
100                // Distance between nested lists is not supported
101                if matches!(
102                    field.data_type(),
103                    List(_) | LargeList(_) | FixedSizeList(..)
104                ) {
105                    return plan_err!(
106                        "{} only supports one-dimensional arrays, got {arg_type}",
107                        self.name()
108                    );
109                }
110                Ok(coerced_type_with_base_type_only(
111                    arg_type,
112                    &DataType::Float64,
113                    coercion,
114                ))
115            }
116            _ => plan_err!("{} does not support type {arg_type}", self.name()),
117        });
118
119        arg_types.try_collect()
120    }
121
122    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
123        make_scalar_function(array_distance_inner)(&args.args)
124    }
125
126    fn aliases(&self) -> &[String] {
127        &self.aliases
128    }
129
130    fn documentation(&self) -> Option<&Documentation> {
131        self.doc()
132    }
133}
134
135fn array_distance_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
136    let [array1, array2] = take_function_args("array_distance", args)?;
137    match (array1.data_type(), array2.data_type()) {
138        (List(_), List(_)) => general_array_distance::<i32>(args),
139        (LargeList(_), LargeList(_)) => general_array_distance::<i64>(args),
140        (arg_type1, arg_type2) => {
141            exec_err!("array_distance does not support types {arg_type1} and {arg_type2}")
142        }
143    }
144}
145
146fn general_array_distance<O: OffsetSizeTrait>(arrays: &[ArrayRef]) -> Result<ArrayRef> {
147    let list_array1 = as_generic_list_array::<O>(&arrays[0])?;
148    let list_array2 = as_generic_list_array::<O>(&arrays[1])?;
149
150    let result = list_array1
151        .iter()
152        .zip(list_array2.iter())
153        .map(|(arr1, arr2)| compute_array_distance(arr1, arr2))
154        .collect::<Result<Float64Array>>()?;
155
156    Ok(Arc::new(result) as ArrayRef)
157}
158
159/// Computes the Euclidean distance between two arrays
160fn compute_array_distance(
161    arr1: Option<ArrayRef>,
162    arr2: Option<ArrayRef>,
163) -> Result<Option<f64>> {
164    let Some(value1) = arr1 else { return Ok(None) };
165    let Some(value2) = arr2 else { return Ok(None) };
166
167    // Check for NULL values inside the arrays
168    if value1.null_count() != 0 || value2.null_count() != 0 {
169        return Ok(None);
170    }
171
172    let values1 = convert_to_f64_array(&value1)?;
173    let values2 = convert_to_f64_array(&value2)?;
174
175    if values1.len() != values2.len() {
176        return exec_err!("Both arrays must have the same length");
177    }
178
179    let diffs = || {
180        values1
181            .values()
182            .iter()
183            .zip(values2.values().iter())
184            .map(|(v1, v2)| v1 - v2)
185    };
186
187    let sum_squares: f64 = diffs().map(|diff| diff * diff).sum();
188    if !needs_norm_scale(sum_squares, values1.len()) {
189        return Ok(Some(sum_squares.sqrt()));
190    }
191
192    let distance = match norm_scale(diffs()) {
193        Some(scale) => {
194            let scaled_sum_squares: f64 = diffs()
195                .map(|diff| {
196                    let scaled = diff * scale;
197                    scaled * scaled
198                })
199                .sum();
200            scaled_sum_squares.sqrt() / scale
201        }
202        None => sum_squares.sqrt(),
203    };
204
205    Ok(Some(distance))
206}
207
208/// Converts an array of any numeric type to a Float64Array.
209fn convert_to_f64_array(array: &ArrayRef) -> Result<Float64Array> {
210    match array.data_type() {
211        DataType::Float64 => Ok(as_float64_array(array)?.clone()),
212        DataType::Float32 => {
213            let array = as_float32_array(array)?;
214            let converted: Float64Array =
215                array.iter().map(|v| v.map(|v| v as f64)).collect();
216            Ok(converted)
217        }
218        DataType::Int64 => {
219            let array = as_int64_array(array)?;
220            let converted: Float64Array =
221                array.iter().map(|v| v.map(|v| v as f64)).collect();
222            Ok(converted)
223        }
224        DataType::Int32 => {
225            let array = as_int32_array(array)?;
226            let converted: Float64Array =
227                array.iter().map(|v| v.map(|v| v as f64)).collect();
228            Ok(converted)
229        }
230        _ => exec_err!("Unsupported array type for conversion to Float64Array"),
231    }
232}