Redis从入门到放弃08——HyperLogLog数据类型

251 阅读2分钟

Redis从入门到放弃08——HyperLogLog数据类型

HyperLogLog数据类型(官网原文)

HyperLogLog is a probabilistic data structure that estimates the cardinality of a set.

HyperLogLog is a probabilistic data structure that estimates the cardinality of a set. As a probabilistic data structure, HyperLogLog trades perfect accuracy for efficient space utilization.

The Redis HyperLogLog implementation uses up to 12 KB and provides a standard error of 0.81%


HyperLogLog是一种概率数据结构,用于估计集合的基数。

HyperLogLog是一种概率数据结构,用于估计集合的基数。作为一种概率数据结构,HyperLogLog以完美的准确性换取有效的空间利用

Redis HyperLogLog实现最多使用12 KB,标准误差为0.81%。

基数:一种数据集,去重复后的真实个数;如果 全集 U={1,2,2,3,4,55,4,7,3} , 基数=去重之后的集合{1,2,3,4,55,7} 中元素的个数 = 6

HyperLogLog数据类型 常用命令

查看HyperLogLog数据类型下所有命令 :help @hyperloglog

127.0.0.1:6379> help @hyperloglog

  PFADD key [element [element ...]]
  summary: Adds the specified elements to the specified HyperLogLog.
  since: 2.8.9

  PFCOUNT key [key ...]
  summary: Return the approximated cardinality of the set(s) observed by the HyperLogLog at key(s).
  since: 2.8.9

  PFDEBUG 
  summary: Internal commands for debugging HyperLogLog values
  since: 2.8.9

  PFMERGE destkey sourcekey [sourcekey ...]
  summary: Merge N different HyperLogLogs into a single one.
  since: 2.8.9

  PFSELFTEST 
  summary: An internal command for testing HyperLogLog values
  since: 2.8.9

PFADD key [element [element ...]]:添加一个元素到hyperloglog 中

127.0.0.1:6379> pfadd m2 111 222 333 444 555
(integer) 1

PFCOUNT key [key ...]:返回给定hyperloglog 的基数估算值

127.0.0.1:6379> pfadd m2 111 222 333 444 555
(integer) 1
127.0.0.1:6379> pfcount m2
(integer) 5
-- 只统计不重复的
127.0.0.1:6379> pfadd m1 11 22 11 33 22 44
(integer) 1
127.0.0.1:6379> pfcount m1
(integer) 4

PFDEBUG :PFDEBUG命令是一个内部命令。它是用来开发和测试Redis的。

PFMERGE destkey sourcekey [sourcekey ...]:将多个hyperloglog 合并为一个hyperloglog

127.0.0.1:6379> pfadd m1 11 22 33 44 44 33 22 11
(integer) 1
127.0.0.1:6379> pfadd m2 1 2 2 33 4
(integer) 1
127.0.0.1:6379> pfmerge m3 m1 m2
OK
127.0.0.1:6379> pfcount m3
(integer) 7

PFSELFTEST :PFSELFTEST命令是一个内部命令。它是用来开发和测试Redis的。

应用场景

  • 统计网站的UV(UNIQUE VISITOR:独立访客):

  • 用户搜索网站关键词的数量

  • 统计用户每天搜索词条的数量 -有多少独立用户播放过这首歌? -有多少独立用户观看了这个视频?