es提供了一个简单的计算distinct count的去重计数api,java代码调用如下
AggregationBuilders.cardinality("columnTypeName").field("column_name")
最后生成的查询数据结构为如下
"aggs": {
"columnTypeName" : {
"cardinality" : {
"field" : "column_name"
}
}
}
在实际使用中发现,该算法实际上底层使用的HLL算法,而不是精确的distinct计算,在数据量较大的情况下会产生5%以内的误差。于是查了官方文档,发现官方文档的一段解释:
The precision_threshold options allows to trade memory for accuracy, and defines a unique count below which counts are expected to be close to accurate. Above this value, counts might become a bit more fuzzy. The maximum supported value is 40000, thresholds above this number will have the same effect as a threshold of 40000. The default value is 3000.
大意为该算法可通过调整precision_threshold参数来调整内存来提升精度,超过设定的值则准确度下降,支持的最大值为40000,默认值为3000
由此对于使用ES的去重计算情况建议几种方案:
1.小数据量的去重,可以直接使用该方式。
2.大数据量的去重,若不追求完全一样精度,可以使用该方法,视情况调整内存来使误差尽量小。
3.大数据量的去重,追求数据结果完全一致。一种是可以使用es的termsagg来进行groupby计算,最后获取其数量,该方式可能因为数据量过大而占用太多内存。另一种方案是通过GreenPlum等计算数据库来进行去重计算,es仅保留结果用于查询