redis中HLL的使用hyperloglog

redis中HLL的使用
这里给出官方文档(中文翻译版)连接,里面关于时间复杂度、返回值、命令方式、使用案例等等都有详细说明

本文对每个命令都简介总结并个人案例展示

pfadd 添加
影响基数估值则返回1否则返回0.若key不存在则创建
时间复杂度O(1)

127.0.0.1:6379> pfadd m1 1 2 3 4 1 2 3 2 2 2 2
(integer) 1

pfcount 获得基数值
得到基数值,白话就叫做去重值(1,1,2,2,3)的插入pfcount得到的是3
可一次统计多个key
时间复杂度为O(N),N为key的个数
返回值是一个带有 0.81% 标准错误(standard error)的近似值.

127.0.0.1:6379> pfadd m1 1 2 3 4 1 2 3 2 2 2 2
(integer) 1
127.0.0.1:6379> pfcount m1
(integer) 4

pfmerge 合并多个key
取多个key的并集
命令只会返回 OK.
时间复杂度为O(N)

127.0.0.1:6379> pfadd m1 1 2 3 4 1 2 3 2 2 2 2
(integer) 1
127.0.0.1:6379> pfcount m1
(integer) 4
127.0.0.1:6379> pfadd m2 3 3 3 4 4 4 5 5 5 6 6 6 1
(integer) 1
127.0.0.1:6379> pfcount m2
(integer) 5
127.0.0.1:6379> pfmerge mergeDes m1 m2
OK
127.0.0.1:6379> pfcount mergeDes
(integer) 6

应用场景
说明:

基数不大,数据量不大就用不上,会有点大材小用浪费空间
有局限性,就是只能统计基数数量,而没办法去知道具体的内容是什么
和bitmap相比,属于两种特定统计情况,简单来说,HyperLogLog 去重比 bitmap 方便很多
一般可以bitmap和hyperloglog配合使用,bitmap标识哪些用户活跃,hyperloglog计数
一般使用:

统计注册 IP 数
统计每日访问 IP 数
统计页面实时 UV 数
统计在线用户数
统计用户每天搜索不同词条的个数
参考链接
神奇的HyperLogLog算法
Redis new data structure: the HyperLogLog
原论文页:HyperLogLog: the analysis of a near-optimal
cardinality estimation algorithm
java实现HyperLogLog的github
基数估计算法概览
hyperloglog的java版使用
参考java使用案例:Probabilistic data Structures – Bloom filter and HyperLogLog for Big Data

你可能感兴趣的:(Redis)