common_function/scalars/
hll_count.rs1use std::fmt;
18use std::fmt::Display;
19
20use common_query::error::{DowncastVectorSnafu, InvalidFuncArgsSnafu, Result};
21use datafusion_expr::{Signature, Volatility};
22use datatypes::arrow::datatypes::DataType;
23use datatypes::prelude::Vector;
24use datatypes::scalars::{ScalarVector, ScalarVectorBuilder};
25use datatypes::vectors::{BinaryVector, MutableVector, UInt64VectorBuilder, VectorRef};
26use hyperloglogplus::HyperLogLog;
27use snafu::OptionExt;
28
29use crate::aggrs::approximate::hll::HllStateType;
30use crate::function::{Function, FunctionContext};
31use crate::function_registry::FunctionRegistry;
32
33const NAME: &str = "hll_count";
34
35#[derive(Debug, Default)]
42pub struct HllCalcFunction;
43
44impl HllCalcFunction {
45 pub fn register(registry: &FunctionRegistry) {
46 registry.register_scalar(HllCalcFunction);
47 }
48}
49
50impl Display for HllCalcFunction {
51 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52 write!(f, "{}", NAME.to_ascii_uppercase())
53 }
54}
55
56impl Function for HllCalcFunction {
57 fn name(&self) -> &str {
58 NAME
59 }
60
61 fn return_type(&self, _: &[DataType]) -> Result<DataType> {
62 Ok(DataType::UInt64)
63 }
64
65 fn signature(&self) -> Signature {
66 Signature::exact(vec![DataType::Binary], Volatility::Immutable)
68 }
69
70 fn eval(&self, _func_ctx: &FunctionContext, columns: &[VectorRef]) -> Result<VectorRef> {
71 if columns.len() != 1 {
72 return InvalidFuncArgsSnafu {
73 err_msg: format!("hll_count expects 1 argument, got {}", columns.len()),
74 }
75 .fail();
76 }
77
78 let hll_vec = columns[0]
79 .as_any()
80 .downcast_ref::<BinaryVector>()
81 .with_context(|| DowncastVectorSnafu {
82 err_msg: format!("expect BinaryVector, got {}", columns[0].vector_type_name()),
83 })?;
84 let len = hll_vec.len();
85 let mut builder = UInt64VectorBuilder::with_capacity(len);
86
87 for i in 0..len {
88 let hll_opt = hll_vec.get_data(i);
89
90 if hll_opt.is_none() {
91 builder.push_null();
92 continue;
93 }
94
95 let hll_bytes = hll_opt.unwrap();
96
97 let mut hll: HllStateType = match bincode::deserialize(hll_bytes) {
99 Ok(h) => h,
100 Err(e) => {
101 common_telemetry::trace!("Failed to deserialize HyperLogLogPlus: {}", e);
102 builder.push_null();
103 continue;
104 }
105 };
106
107 builder.push(Some(hll.count().round() as u64));
108 }
109
110 Ok(builder.to_vector())
111 }
112}
113
114#[cfg(test)]
115mod tests {
116 use std::sync::Arc;
117
118 use datatypes::vectors::BinaryVector;
119
120 use super::*;
121 use crate::utils::FixedRandomState;
122
123 #[test]
124 fn test_hll_count_function() {
125 let function = HllCalcFunction;
126 assert_eq!("hll_count", function.name());
127 assert_eq!(
128 DataType::UInt64,
129 function.return_type(&[DataType::UInt64]).unwrap()
130 );
131
132 let mut hll = HllStateType::new(14, FixedRandomState::new()).unwrap();
134 for i in 1..=10 {
135 hll.insert(&i.to_string());
136 }
137
138 let serialized_bytes = bincode::serialize(&hll).unwrap();
139 let args: Vec<VectorRef> = vec![Arc::new(BinaryVector::from(vec![Some(serialized_bytes)]))];
140
141 let result = function.eval(&FunctionContext::default(), &args).unwrap();
142 assert_eq!(result.len(), 1);
143
144 if let datatypes::value::Value::UInt64(v) = result.get(0) {
146 assert_eq!(v, 10);
147 } else {
148 panic!("Expected uint64 value");
149 }
150 }
151
152 #[test]
153 fn test_hll_count_function_errors() {
154 let function = HllCalcFunction;
155
156 let args: Vec<VectorRef> = vec![];
158 let result = function.eval(&FunctionContext::default(), &args);
159 assert!(result.is_err());
160 assert!(
161 result
162 .unwrap_err()
163 .to_string()
164 .contains("hll_count expects 1 argument")
165 );
166
167 let args: Vec<VectorRef> = vec![Arc::new(BinaryVector::from(vec![Some(vec![1, 2, 3])]))]; let result = function.eval(&FunctionContext::default(), &args).unwrap();
170 assert_eq!(result.len(), 1);
171 assert!(matches!(result.get(0), datatypes::value::Value::Null));
172 }
173}