Skip to main content

HllUnion

Struct HllUnion 

Source
pub struct HllUnion { /* private fields */ }
Expand description

Merges multiple HllSketches into one, e.g. combining per-shard or per-day counts into a total distinct count across all of them.

Implementations§

Source§

impl HllUnion

Source

pub fn new(lg_max_k: u8) -> Result<Self, SketchError>

Creates a new, empty union with the given maximum lg_config_k (4..=21) — the union’s result will use at most this lg_config_k, even if a merged-in sketch used a larger one. Returns SketchError::InvalidConfig if lg_max_k is out of range.

Examples found in repository?
examples/hll.rs (line 52)
7fn main() {
8    // A sketch estimates the number of distinct items seen, using bounded
9    // memory regardless of how many items are added. `lg_config_k` (4..=21)
10    // trades memory for accuracy: higher values are more accurate but use
11    // more space.
12    let mut sketch = HllSketch::new(12, TargetHllType::Hll4).expect("valid lg_config_k");
13
14    for i in 0..10_000u64 {
15        sketch.update_u64(i);
16    }
17    // Duplicates don't affect the distinct count.
18    for i in 0..5_000u64 {
19        sketch.update_u64(i);
20    }
21    sketch.update_str("some-key");
22    sketch.update_bytes(b"raw bytes work too");
23
24    println!("distinct count estimate: {:.1}", sketch.get_estimate());
25    println!(
26        "95% confidence interval: [{:.1}, {:.1}]",
27        sketch.get_lower_bound(2).unwrap(),
28        sketch.get_upper_bound(2).unwrap()
29    );
30
31    // Sketches can be serialized to bytes (e.g. to store or send over the
32    // network) and reconstructed later.
33    let bytes = sketch.serialize_compact();
34    let restored = HllSketch::deserialize(&bytes).expect("valid sketch bytes");
35    assert_eq!(sketch.get_estimate(), restored.get_estimate());
36    println!(
37        "serialized to {} bytes and restored successfully",
38        bytes.len()
39    );
40
41    // HllUnion merges multiple sketches into one, e.g. combining
42    // per-shard/per-day counts into a total distinct count.
43    let mut shard_a = HllSketch::new(12, TargetHllType::Hll4).unwrap();
44    for i in 0..10_000u64 {
45        shard_a.update_u64(i);
46    }
47    let mut shard_b = HllSketch::new(12, TargetHllType::Hll4).unwrap();
48    for i in 5_000..15_000u64 {
49        shard_b.update_u64(i);
50    }
51
52    let mut union = HllUnion::new(12).expect("valid lg_max_k");
53    union.update_sketch(&shard_a);
54    union.update_sketch(&shard_b);
55
56    let merged = union.get_result(TargetHllType::Hll4);
57    println!(
58        "merged distinct count across two overlapping shards (true count = 15000): {:.1}",
59        merged.get_estimate()
60    );
61}
Source

pub fn update_sketch(&mut self, sketch: &HllSketch)

Merges the given sketch’s state into this union.

Examples found in repository?
examples/hll.rs (line 53)
7fn main() {
8    // A sketch estimates the number of distinct items seen, using bounded
9    // memory regardless of how many items are added. `lg_config_k` (4..=21)
10    // trades memory for accuracy: higher values are more accurate but use
11    // more space.
12    let mut sketch = HllSketch::new(12, TargetHllType::Hll4).expect("valid lg_config_k");
13
14    for i in 0..10_000u64 {
15        sketch.update_u64(i);
16    }
17    // Duplicates don't affect the distinct count.
18    for i in 0..5_000u64 {
19        sketch.update_u64(i);
20    }
21    sketch.update_str("some-key");
22    sketch.update_bytes(b"raw bytes work too");
23
24    println!("distinct count estimate: {:.1}", sketch.get_estimate());
25    println!(
26        "95% confidence interval: [{:.1}, {:.1}]",
27        sketch.get_lower_bound(2).unwrap(),
28        sketch.get_upper_bound(2).unwrap()
29    );
30
31    // Sketches can be serialized to bytes (e.g. to store or send over the
32    // network) and reconstructed later.
33    let bytes = sketch.serialize_compact();
34    let restored = HllSketch::deserialize(&bytes).expect("valid sketch bytes");
35    assert_eq!(sketch.get_estimate(), restored.get_estimate());
36    println!(
37        "serialized to {} bytes and restored successfully",
38        bytes.len()
39    );
40
41    // HllUnion merges multiple sketches into one, e.g. combining
42    // per-shard/per-day counts into a total distinct count.
43    let mut shard_a = HllSketch::new(12, TargetHllType::Hll4).unwrap();
44    for i in 0..10_000u64 {
45        shard_a.update_u64(i);
46    }
47    let mut shard_b = HllSketch::new(12, TargetHllType::Hll4).unwrap();
48    for i in 5_000..15_000u64 {
49        shard_b.update_u64(i);
50    }
51
52    let mut union = HllUnion::new(12).expect("valid lg_max_k");
53    union.update_sketch(&shard_a);
54    union.update_sketch(&shard_b);
55
56    let merged = union.get_result(TargetHllType::Hll4);
57    println!(
58        "merged distinct count across two overlapping shards (true count = 15000): {:.1}",
59        merged.get_estimate()
60    );
61}
Source

pub fn update_u64(&mut self, value: u64)

Adds a u64 value directly to the union, as if it were added to every sketch merged into it.

Source

pub fn update_i64(&mut self, value: i64)

Adds an i64 value directly to the union. See Self::update_u64.

Source

pub fn update_f64(&mut self, value: f64)

Adds an f64 value directly to the union. See Self::update_u64.

Source

pub fn update_str(&mut self, value: &str)

Adds a string value directly to the union. See Self::update_u64.

Source

pub fn update_bytes(&mut self, value: &[u8])

Adds an arbitrary byte slice directly to the union. See Self::update_u64.

Source

pub fn get_result(&self, tgt_type: TargetHllType) -> HllSketch

Returns the current merged result as a standalone HllSketch of the given TargetHllType.

Examples found in repository?
examples/hll.rs (line 56)
7fn main() {
8    // A sketch estimates the number of distinct items seen, using bounded
9    // memory regardless of how many items are added. `lg_config_k` (4..=21)
10    // trades memory for accuracy: higher values are more accurate but use
11    // more space.
12    let mut sketch = HllSketch::new(12, TargetHllType::Hll4).expect("valid lg_config_k");
13
14    for i in 0..10_000u64 {
15        sketch.update_u64(i);
16    }
17    // Duplicates don't affect the distinct count.
18    for i in 0..5_000u64 {
19        sketch.update_u64(i);
20    }
21    sketch.update_str("some-key");
22    sketch.update_bytes(b"raw bytes work too");
23
24    println!("distinct count estimate: {:.1}", sketch.get_estimate());
25    println!(
26        "95% confidence interval: [{:.1}, {:.1}]",
27        sketch.get_lower_bound(2).unwrap(),
28        sketch.get_upper_bound(2).unwrap()
29    );
30
31    // Sketches can be serialized to bytes (e.g. to store or send over the
32    // network) and reconstructed later.
33    let bytes = sketch.serialize_compact();
34    let restored = HllSketch::deserialize(&bytes).expect("valid sketch bytes");
35    assert_eq!(sketch.get_estimate(), restored.get_estimate());
36    println!(
37        "serialized to {} bytes and restored successfully",
38        bytes.len()
39    );
40
41    // HllUnion merges multiple sketches into one, e.g. combining
42    // per-shard/per-day counts into a total distinct count.
43    let mut shard_a = HllSketch::new(12, TargetHllType::Hll4).unwrap();
44    for i in 0..10_000u64 {
45        shard_a.update_u64(i);
46    }
47    let mut shard_b = HllSketch::new(12, TargetHllType::Hll4).unwrap();
48    for i in 5_000..15_000u64 {
49        shard_b.update_u64(i);
50    }
51
52    let mut union = HllUnion::new(12).expect("valid lg_max_k");
53    union.update_sketch(&shard_a);
54    union.update_sketch(&shard_b);
55
56    let merged = union.get_result(TargetHllType::Hll4);
57    println!(
58        "merged distinct count across two overlapping shards (true count = 15000): {:.1}",
59        merged.get_estimate()
60    );
61}
Source

pub fn serialize_compact(&self, tgt_type: TargetHllType) -> Vec<u8>

Serializes get_result(tgt_type) in compact form. A union has no serializable state of its own upstream (only the result sketch does) — to resume accumulating after deserializing, use HllSketch::deserialize and feed the sketch back in via update_sketch.

Source

pub fn serialize_updatable(&self, tgt_type: TargetHllType) -> Vec<u8>

Serializes get_result(tgt_type) in updatable form. See Self::serialize_compact for why HllUnion has no deserialize.

Source

pub fn get_estimate(&self) -> f64

Returns the current estimate of the number of distinct items merged into this union so far.

Source

pub fn get_lower_bound(&self, num_std_dev: u8) -> Result<f64, SketchError>

Returns the lower bound of the confidence interval around Self::get_estimate. See HllSketch::get_lower_bound for the meaning of num_std_dev.

Source

pub fn get_upper_bound(&self, num_std_dev: u8) -> Result<f64, SketchError>

Returns the upper bound of the confidence interval around Self::get_estimate. See HllSketch::get_lower_bound for the meaning of num_std_dev.

Source

pub fn is_empty(&self) -> bool

Returns true if no sketch or item has been merged into this union.

Source

pub fn reset(&mut self)

Resets this union to its initial, empty state.

Trait Implementations§

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.