Skip to main content

datafusion_functions_nested/
inner_product.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 inner_product function.
6
7use crate::utils::make_scalar_function;
8use arrow::array::{Array, ArrayRef, Float64Array, OffsetSizeTrait};
9use arrow::datatypes::{
10    DataType,
11    DataType::{FixedSizeList, LargeList, List, Null},
12    Field,
13};
14use datafusion_common::cast::{as_float64_array, as_generic_list_array};
15use datafusion_common::utils::{ListCoercion, coerced_type_with_base_type_only};
16use datafusion_common::{
17    Result, exec_err, internal_err, plan_err, utils::take_function_args,
18};
19use datafusion_expr::{
20    ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
21    Volatility,
22};
23use datafusion_macros::user_doc;
24use std::sync::Arc;
25
26make_udf_expr_and_func!(
27    InnerProduct,
28    inner_product,
29    array1 array2,
30    "returns the inner product (dot product) of two numeric arrays.",
31    inner_product_udf
32);
33
34#[user_doc(
35    doc_section(label = "Array Functions"),
36    description = "Returns the inner product (dot product) of two input arrays of equal length, computed as `sum(array1[i] * array2[i])`. Returns NULL if either array is NULL or contains NULL elements. Returns 0.0 for two empty arrays.",
37    syntax_example = "inner_product(array1, array2)",
38    sql_example = r#"```sql
39> select inner_product([1.0, 2.0, 3.0], [4.0, 5.0, 6.0]);
40+--------------------------------------------------------+
41| inner_product(List([1.0,2.0,3.0]),List([4.0,5.0,6.0])) |
42+--------------------------------------------------------+
43| 32.0                                                   |
44+--------------------------------------------------------+
45```"#,
46    argument(
47        name = "array1",
48        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
49    ),
50    argument(
51        name = "array2",
52        description = "Array expression. Can be a constant, column, or function, and any combination of array operators."
53    )
54)]
55#[derive(Debug, PartialEq, Eq, Hash)]
56pub struct InnerProduct {
57    signature: Signature,
58    aliases: Vec<String>,
59}
60
61impl Default for InnerProduct {
62    fn default() -> Self {
63        Self::new()
64    }
65}
66
67impl InnerProduct {
68    pub fn new() -> Self {
69        Self {
70            signature: Signature::user_defined(Volatility::Immutable),
71            aliases: vec!["dot_product".to_string()],
72        }
73    }
74}
75
76impl ScalarUDFImpl for InnerProduct {
77    fn name(&self) -> &str {
78        "inner_product"
79    }
80
81    fn signature(&self) -> &Signature {
82        &self.signature
83    }
84
85    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
86        Ok(DataType::Float64)
87    }
88
89    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
90        let [_, _] = take_function_args(self.name(), arg_types)?;
91        let coercion = Some(&ListCoercion::FixedSizedListToList);
92
93        for arg_type in arg_types {
94            if !matches!(arg_type, Null | List(_) | LargeList(_) | FixedSizeList(..)) {
95                return plan_err!("{} does not support type {arg_type}", self.name());
96            }
97        }
98
99        // If any input is `LargeList`, both sides must be widened to `LargeList`
100        // so the runtime dispatch in `inner_product_inner` sees a homogeneous
101        // pair. Follows the pattern in `ArrayConcat::coerce_types`.
102        let any_large_list = arg_types.iter().any(|t| matches!(t, LargeList(_)));
103
104        let coerced = arg_types
105            .iter()
106            .map(|arg_type| {
107                if matches!(arg_type, Null) {
108                    let field = Arc::new(Field::new_list_field(DataType::Float64, true));
109                    return if any_large_list {
110                        LargeList(field)
111                    } else {
112                        List(field)
113                    };
114                }
115                let coerced = coerced_type_with_base_type_only(
116                    arg_type,
117                    &DataType::Float64,
118                    coercion,
119                );
120                match coerced {
121                    List(field) if any_large_list => LargeList(field),
122                    other => other,
123                }
124            })
125            .collect();
126
127        Ok(coerced)
128    }
129
130    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
131        make_scalar_function(inner_product_inner)(&args.args)
132    }
133
134    fn aliases(&self) -> &[String] {
135        &self.aliases
136    }
137
138    fn documentation(&self) -> Option<&Documentation> {
139        self.doc()
140    }
141}
142
143fn inner_product_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
144    let [array1, array2] = take_function_args("inner_product", args)?;
145    match (array1.data_type(), array2.data_type()) {
146        (List(_), List(_)) => general_inner_product::<i32>(args),
147        (LargeList(_), LargeList(_)) => general_inner_product::<i64>(args),
148        (arg_type1, arg_type2) => internal_err!(
149            "inner_product received unexpected types after coercion: {arg_type1} and {arg_type2}"
150        ),
151    }
152}
153
154fn general_inner_product<O: OffsetSizeTrait>(arrays: &[ArrayRef]) -> Result<ArrayRef> {
155    let list_array1 = as_generic_list_array::<O>(&arrays[0])?;
156    let list_array2 = as_generic_list_array::<O>(&arrays[1])?;
157
158    let values1 = as_float64_array(list_array1.values())?;
159    let values2 = as_float64_array(list_array2.values())?;
160    let offsets1 = list_array1.value_offsets();
161    let offsets2 = list_array2.value_offsets();
162
163    let mut builder = Float64Array::builder(list_array1.len());
164    for row in 0..list_array1.len() {
165        if list_array1.is_null(row) || list_array2.is_null(row) {
166            builder.append_null();
167            continue;
168        }
169
170        let start1 = offsets1[row].as_usize();
171        let end1 = offsets1[row + 1].as_usize();
172        let start2 = offsets2[row].as_usize();
173        let end2 = offsets2[row + 1].as_usize();
174        let len1 = end1 - start1;
175        let len2 = end2 - start2;
176
177        if len1 != len2 {
178            return exec_err!(
179                "inner_product requires both list inputs to have the same length, got {len1} and {len2}"
180            );
181        }
182
183        let slice1 = values1.slice(start1, len1);
184        let slice2 = values2.slice(start2, len2);
185        if slice1.null_count() != 0 || slice2.null_count() != 0 {
186            builder.append_null();
187            continue;
188        }
189
190        let vals1 = slice1.values();
191        let vals2 = slice2.values();
192
193        let mut dot = 0.0;
194        for i in 0..len1 {
195            dot += vals1[i] * vals2[i];
196        }
197        builder.append_value(dot);
198    }
199
200    Ok(Arc::new(builder.finish()) as ArrayRef)
201}