跳到正文

Cardinality/HyperUnique 聚合器 ​

Cardinality 聚合器 ​

计算一组 Apache® Druid 维度的基数,使用 HyperLogLog 来估算基数。请注意, 该聚合器会比使用 hyperUnique 聚合器对列建立索引慢得多。该聚合器同样作用于维度列, 这意味着无法为了改善 rollup 效果而从数据集中移除该字符串维度。一般来说,如果你并不关心维度的各个具体值, 我们强烈建议使用 hyperUnique 聚合器来代替 cardinality 聚合器。

json
{
  "type": "cardinality",
  "name": "<output_name>",
  "fields": [ <dimension1>, <dimension2>, ... ],
  "byRow": <false | true> # (optional, defaults to false),
  "round": <false | true> # (optional, defaults to false)
}

"fields" 列表中的每个元素可以是 String 或 DimensionSpec。fields 列表中的 String 维度等同于 DefaultDimensionSpec(不做任何转换)。

HyperLogLog 算法生成的是带有一定误差的小数估计值。可以将 "round" 设置为 true,将估计值 四舍五入为整数。请注意,即使进行了四舍五入,基数仍然是一个估计值。"round" 字段只影响 查询时的行为,在摄取时会被忽略。

按值计算基数 ​

当 byRow 设置为 false(默认值)时,它计算的是由所有给定维度的全部维度值的并集所构成集合的基数。

  • 对于单个维度,这等同于
sql
SELECT COUNT(DISTINCT(dimension)) FROM <datasource>
  • 对于多个维度,这大致等同于
sql
SELECT COUNT(DISTINCT(value)) FROM (
  SELECT dim_1 as value FROM <datasource>
  UNION
  SELECT dim_2 as value FROM <datasource>
  UNION
  SELECT dim_3 as value FROM <datasource>
)

按行计算基数 ​

当 byRow 设置为 true 时,它按行计算基数,即不同维度组合的基数。 这大致等同于

sql
SELECT COUNT(*) FROM ( SELECT DIM1, DIM2, DIM3 FROM <datasource> GROUP BY DIM1, DIM2, DIM3 )

示例

统计人们居住或来自的不同国家的数量。

json
{
  "type": "cardinality",
  "name": "distinct_countries",
  "fields": [ "country_of_origin", "country_of_residence" ]
}

统计不同人员的数量(即名字和姓氏的不同组合)。

json
{
  "type": "cardinality",
  "name": "distinct_people",
  "fields": [ "first_name", "last_name" ],
  "byRow" : true
}

统计姓氏首字母的不同取值数量

json
{
  "type": "cardinality",
  "name": "distinct_last_name_first_char",
  "fields": [
    {
     "type" : "extraction",
     "dimension" : "last_name",
     "outputName" :  "last_name_first_char",
     "extractionFn" : { "type" : "substring", "index" : 0, "length" : 1 }
    }
  ],
  "byRow" : true
}

HyperUnique 聚合器 ​

使用 HyperLogLog 计算某个维度的估计基数,该维度在索引时已被聚合为 "hyperUnique" 指标。

json
{
  "type" : "hyperUnique",
  "name" : <output_name>,
  "fieldName" : <metric_name>,
  "isInputHyperUnique" : false,
  "round" : false
}

可以将 "isInputHyperUnique" 设置为 true,以便对预先计算好的 HLL 建立索引(输入应为 druid-hll 输出的 Base64 编码数据)。 "isInputHyperUnique" 字段只影响摄取时的行为,在查询时会被忽略。

HyperLogLog 算法生成的是带有一定误差的小数估计值。可以将 "round" 设置为 true,将估计值 四舍五入为整数。请注意,即使进行了四舍五入,基数仍然是一个估计值。"round" 字段只影响 查询时的行为,在摄取时会被忽略。

基于 Apache License 2.0 许可证发布。