Skip to main content

micromegas_analytics/properties/
jsonb_dictionary.rs

1use crate::arrow_properties::serialize_property_set_to_jsonb;
2use crate::properties::property_set::PropertySet;
3use anyhow::Result;
4use datafusion::arrow::array::{BinaryArray, DictionaryArray, Int32Array};
5use datafusion::arrow::datatypes::Int32Type;
6use datafusion::common::DataFusionError;
7use std::collections::HashMap;
8use std::sync::Arc;
9
10/// JSONB property sets deduplicated by content. Index 0 is the empty set.
11///
12/// Unlike `PropertySetJsonbDictionaryBuilder`, nothing here depends on the address of a parse
13/// arena, so one dictionary can span several blocks.
14#[derive(Debug)]
15pub struct JsonbDictionary {
16    values: Vec<Vec<u8>>,
17    index: HashMap<Vec<u8>, i32>,
18}
19
20impl JsonbDictionary {
21    pub fn new() -> Self {
22        let empty = serialize_property_set_to_jsonb(&PropertySet::empty())
23            .expect("serializing the empty property set");
24        let mut index = HashMap::new();
25        index.insert(empty.clone(), 0);
26        Self {
27            values: vec![empty],
28            index,
29        }
30    }
31
32    /// Returns the index of `jsonb`, adding it if it is new.
33    pub fn intern(&mut self, jsonb: &[u8]) -> i32 {
34        if let Some(&i) = self.index.get(jsonb) {
35            return i;
36        }
37        let i = self.values.len() as i32;
38        self.values.push(jsonb.to_vec());
39        self.index.insert(jsonb.to_vec(), i);
40        i
41    }
42
43    pub fn values(&self) -> &[Vec<u8>] {
44        &self.values
45    }
46
47    /// Builds the column from one dictionary index per row.
48    pub fn finish(self, keys: Vec<i32>) -> Result<DictionaryArray<Int32Type>> {
49        let byte_slices: Vec<&[u8]> = self.values.iter().map(|v| v.as_slice()).collect();
50        let values = Arc::new(BinaryArray::from_vec(byte_slices));
51        DictionaryArray::try_new(Int32Array::from(keys), values)
52            .map_err(|e| DataFusionError::ArrowError(Box::new(e), None).into())
53    }
54}
55
56impl Default for JsonbDictionary {
57    fn default() -> Self {
58        Self::new()
59    }
60}