use async_trait::async_trait;
use datafusion::prelude::*;
use serde::{Deserialize, Serialize};
use tracing::instrument;
use crate::analyzers::{Analyzer, AnalyzerError, AnalyzerResult, AnalyzerState, MetricValue};
use crate::core::current_validation_context;
#[derive(Debug, Clone)]
pub struct ApproxCountDistinctAnalyzer {
column: String,
}
impl ApproxCountDistinctAnalyzer {
pub fn new(column: impl Into<String>) -> Self {
Self {
column: column.into(),
}
}
pub fn column(&self) -> &str {
&self.column
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApproxCountDistinctState {
pub approx_distinct_count: u64,
pub total_count: u64,
}
impl ApproxCountDistinctState {
pub fn distinctness_ratio(&self) -> f64 {
if self.total_count == 0 {
1.0
} else {
self.approx_distinct_count as f64 / self.total_count as f64
}
}
}
impl AnalyzerState for ApproxCountDistinctState {
fn merge(states: Vec<Self>) -> AnalyzerResult<Self> {
let approx_distinct_count = states
.iter()
.map(|s| s.approx_distinct_count)
.max()
.unwrap_or(0);
let total_count = states.iter().map(|s| s.total_count).sum();
Ok(ApproxCountDistinctState {
approx_distinct_count,
total_count,
})
}
fn is_empty(&self) -> bool {
self.total_count == 0
}
}
#[async_trait]
impl Analyzer for ApproxCountDistinctAnalyzer {
type State = ApproxCountDistinctState;
type Metric = MetricValue;
#[instrument(skip(ctx), fields(analyzer = "approx_count_distinct", column = %self.column))]
async fn compute_state_from_data(&self, ctx: &SessionContext) -> AnalyzerResult<Self::State> {
let validation_ctx = current_validation_context();
let table_name = validation_ctx.table_name();
let sql = format!(
"SELECT APPROX_DISTINCT({0}) as approx_distinct, COUNT({0}) as total FROM {table_name}",
self.column
);
let df = ctx.sql(&sql).await?;
let batches = df.collect().await?;
let (approx_distinct_count, total_count) = if let Some(batch) = batches.first() {
if batch.num_rows() > 0 {
let approx_distinct_array = batch
.column(0)
.as_any()
.downcast_ref::<arrow::array::UInt64Array>()
.ok_or_else(|| {
AnalyzerError::invalid_data("Expected UInt64 array for approx_distinct")
})?;
let approx_distinct = approx_distinct_array.value(0);
let total_array = batch
.column(1)
.as_any()
.downcast_ref::<arrow::array::Int64Array>()
.ok_or_else(|| {
AnalyzerError::invalid_data("Expected Int64 array for total count")
})?;
let total = total_array.value(0) as u64;
(approx_distinct, total)
} else {
(0, 0)
}
} else {
(0, 0)
};
Ok(ApproxCountDistinctState {
approx_distinct_count,
total_count,
})
}
fn compute_metric_from_state(&self, state: &Self::State) -> AnalyzerResult<Self::Metric> {
Ok(MetricValue::Long(state.approx_distinct_count as i64))
}
fn name(&self) -> &str {
"approx_count_distinct"
}
fn description(&self) -> &str {
"Computes approximate count of distinct values using HyperLogLog"
}
fn metric_key(&self) -> String {
format!("{}.{}", self.name(), self.column)
}
fn columns(&self) -> Vec<&str> {
vec![&self.column]
}
}