datafusion_functions_nested/
cosine_distance.rs1use 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 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 CosineDistance,
28 cosine_distance,
29 array1 array2,
30 "returns the cosine distance between two numeric arrays.",
31 cosine_distance_udf
32);
33
34#[user_doc(
35 doc_section(label = "Array Functions"),
36 description = "Returns the cosine distance between two input arrays of equal length. The cosine distance is defined as 1 - cosine_similarity, i.e. `1 - dot(a,b) / (||a|| * ||b||)`. Returns NULL if either array is NULL or contains only zeros.",
37 syntax_example = "cosine_distance(array1, array2)",
38 sql_example = r#"```sql
39> select cosine_distance([1.0, 0.0], [0.0, 1.0]);
40+--------------------------------------------------+
41| cosine_distance(List([1.0,0.0]),List([0.0,1.0])) |
42+--------------------------------------------------+
43| 1.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 CosineDistance {
57 signature: Signature,
58}
59
60impl Default for CosineDistance {
61 fn default() -> Self {
62 Self::new()
63 }
64}
65
66impl CosineDistance {
67 pub fn new() -> Self {
68 Self {
69 signature: Signature::user_defined(Volatility::Immutable),
70 }
71 }
72}
73
74impl ScalarUDFImpl for CosineDistance {
75 fn name(&self) -> &str {
76 "cosine_distance"
77 }
78
79 fn signature(&self) -> &Signature {
80 &self.signature
81 }
82
83 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
84 Ok(DataType::Float64)
85 }
86
87 fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
88 let [_, _] = take_function_args(self.name(), arg_types)?;
89 let coercion = Some(&ListCoercion::FixedSizedListToList);
90
91 for arg_type in arg_types {
92 if !matches!(arg_type, Null | List(_) | LargeList(_) | FixedSizeList(..)) {
93 return plan_err!("{} does not support type {arg_type}", self.name());
94 }
95 }
96
97 let any_large_list = arg_types.iter().any(|t| matches!(t, LargeList(_)));
101
102 let coerced = arg_types
103 .iter()
104 .map(|arg_type| {
105 if matches!(arg_type, Null) {
106 let field = Arc::new(Field::new_list_field(DataType::Float64, true));
107 return if any_large_list {
108 LargeList(field)
109 } else {
110 List(field)
111 };
112 }
113 let coerced = coerced_type_with_base_type_only(
114 arg_type,
115 &DataType::Float64,
116 coercion,
117 );
118 match coerced {
119 List(field) if any_large_list => LargeList(field),
120 other => other,
121 }
122 })
123 .collect();
124
125 Ok(coerced)
126 }
127
128 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
129 make_scalar_function(cosine_distance_inner)(&args.args)
130 }
131
132 fn documentation(&self) -> Option<&Documentation> {
133 self.doc()
134 }
135}
136
137fn cosine_distance_inner(args: &[ArrayRef]) -> Result<ArrayRef> {
138 let [array1, array2] = take_function_args("cosine_distance", args)?;
139 match (array1.data_type(), array2.data_type()) {
140 (List(_), List(_)) => general_cosine_distance::<i32>(args),
141 (LargeList(_), LargeList(_)) => general_cosine_distance::<i64>(args),
142 (arg_type1, arg_type2) => internal_err!(
143 "cosine_distance received unexpected types after coercion: {arg_type1} and {arg_type2}"
144 ),
145 }
146}
147
148fn general_cosine_distance<O: OffsetSizeTrait>(arrays: &[ArrayRef]) -> Result<ArrayRef> {
149 let list_array1 = as_generic_list_array::<O>(&arrays[0])?;
150 let list_array2 = as_generic_list_array::<O>(&arrays[1])?;
151
152 let values1 = as_float64_array(list_array1.values())?;
153 let values2 = as_float64_array(list_array2.values())?;
154 let offsets1 = list_array1.value_offsets();
155 let offsets2 = list_array2.value_offsets();
156
157 let mut builder = Float64Array::builder(list_array1.len());
158 for row in 0..list_array1.len() {
159 if list_array1.is_null(row) || list_array2.is_null(row) {
160 builder.append_null();
161 continue;
162 }
163
164 let start1 = offsets1[row].as_usize();
165 let end1 = offsets1[row + 1].as_usize();
166 let start2 = offsets2[row].as_usize();
167 let end2 = offsets2[row + 1].as_usize();
168 let len1 = end1 - start1;
169 let len2 = end2 - start2;
170
171 if len1 != len2 {
172 return exec_err!(
173 "cosine_distance requires both list inputs to have the same length, got {len1} and {len2}"
174 );
175 }
176
177 let slice1 = values1.slice(start1, len1);
178 let slice2 = values2.slice(start2, len2);
179 if slice1.null_count() != 0 || slice2.null_count() != 0 {
180 builder.append_null();
181 continue;
182 }
183
184 let vals1 = slice1.values();
185 let vals2 = slice2.values();
186
187 let (mut dot, mut sq1, mut sq2) = dot_and_squares(vals1, vals2, 1.0, 1.0);
188 let rescale_both = !dot.is_finite();
194 let scale1 = if rescale_both || needs_norm_scale(sq1, len1) {
195 norm_scale(vals1.iter().copied())
196 } else {
197 None
198 };
199 let scale2 = if rescale_both || needs_norm_scale(sq2, len1) {
200 norm_scale(vals2.iter().copied())
201 } else {
202 None
203 };
204 if scale1.is_some() || scale2.is_some() {
205 (dot, sq1, sq2) = dot_and_squares(
206 vals1,
207 vals2,
208 scale1.unwrap_or(1.0),
209 scale2.unwrap_or(1.0),
210 );
211 }
212
213 if sq1 == 0.0 || sq2 == 0.0 {
214 builder.append_null();
215 } else {
216 let sim = (dot / (sq1.sqrt() * sq2.sqrt())).clamp(-1.0, 1.0);
217 builder.append_value((1.0 - sim).clamp(0.0, 2.0));
218 }
219 }
220
221 Ok(Arc::new(builder.finish()) as ArrayRef)
222}
223
224#[inline]
227fn dot_and_squares(
228 vals1: &[f64],
229 vals2: &[f64],
230 scale1: f64,
231 scale2: f64,
232) -> (f64, f64, f64) {
233 let mut dot = 0.0;
234 let mut sq1 = 0.0;
235 let mut sq2 = 0.0;
236 for (a, b) in vals1.iter().zip(vals2) {
237 let a = a * scale1;
238 let b = b * scale2;
239 dot += a * b;
240 sq1 += a * a;
241 sq2 += b * b;
242 }
243 (dot, sq1, sq2)
244}