blob: 41e5423472a026bc3be243773cf27fb27ba74c02 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.searchlib.aggregation.hll;
/**
* This class is responsible for merging any combinations of two {@link Sketch} instances.
*/
public class SketchMerger {
/**
* Merges one of the two sketches into the other. The merge operation is performed in-place is possible.
*
* @param left Either a {@link NormalSketch} or {@link SparseSketch}.
* @param right Either a {@link NormalSketch} or {@link SparseSketch}.
* @return The merged sketch. Is either first parameter, the other parameter or a new instance.
*/
public Sketch<?> merge(Sketch<?> left, Sketch<?> right) {
if (left instanceof NormalSketch && right instanceof NormalSketch) {
return mergeNormalWithNormal(asNormal(left), asNormal(right));
} else if (left instanceof NormalSketch && right instanceof SparseSketch) {
return mergeNormalWithSparse(asNormal(left), asSparse(right));
} else if (left instanceof SparseSketch && right instanceof NormalSketch) {
return mergeNormalWithSparse(asNormal(right), asSparse(left));
} else if (left instanceof SparseSketch && right instanceof SparseSketch) {
return mergeSparseWithSparse(asSparse(left), asSparse(right));
} else {
throw new IllegalArgumentException(
String.format("Invalid sketch types: left=%s, right=%s", right.getClass(), left.getClass()));
}
}
private Sketch<?> mergeSparseWithSparse(SparseSketch dest, SparseSketch other) {
dest.merge(other);
if (dest.size() > HyperLogLog.SPARSE_SKETCH_CONVERSION_THRESHOLD) {
NormalSketch newSketch = new NormalSketch();
newSketch.aggregate(dest.data());
return newSketch;
}
return dest;
}
private NormalSketch mergeNormalWithNormal(NormalSketch dest, NormalSketch other) {
dest.merge(other);
return dest;
}
private NormalSketch mergeNormalWithSparse(NormalSketch dest, SparseSketch other) {
NormalSketch newSketch = new NormalSketch();
newSketch.aggregate(other.data());
dest.merge(newSketch);
return dest;
}
private static NormalSketch asNormal(Sketch<?> sketch) {
return (NormalSketch) sketch;
}
private static SparseSketch asSparse(Sketch<?> sketch) {
return (SparseSketch) sketch;
}
}
|