common_function/scalars/
hll_count.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Implementation of the scalar function `hll_count`.
16
17use 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/// HllCalcFunction implements the scalar function `hll_count`.
36///
37/// It accepts one argument:
38/// 1. The serialized HyperLogLogPlus state, as produced by the aggregator (binary).
39///
40/// For each row, it deserializes the sketch and returns the estimated cardinality.
41#[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        // Only argument: HyperLogLogPlus state (binary)
67        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            // Deserialize the HyperLogLogPlus from its bincode representation
98            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        // Create a test HLL
133        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        // Test cardinality estimate
145        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        // Test with invalid number of arguments
157        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        // Test with invalid binary data
168        let args: Vec<VectorRef> = vec![Arc::new(BinaryVector::from(vec![Some(vec![1, 2, 3])]))]; // Invalid binary data
169        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}