3

【redis进阶(2)】大数据量模糊计数

 3 years ago
source link: https://segmentfault.com/a/1190000040611711
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

【redis进阶(2)】大数据量模糊计数

HyperLogLog 提供不精确的去重计数方案,用于记录大数据量的计数(如,网站的uv),虽然不精确但是也不是非常不精确,标准误差是 0.81%。

HyperLogLog 提供了两个指令 pfadd 和 pfcount,根据字面意义很好理解,一个是增加计数,一个是获取计数。pfadd 用法和 set 集合的 sadd 是一样的,来一个用户 ID,就将用户 ID 塞进去就是。pfcount 和 scard 用法是一样的,直接获取计数值。

127.0.0.1:6379> pfadd codehole user1 user2 user3
(integer) 3
127.0.0.1:6379> pfcount codehole
(integer) 3

接下来我们使用脚本,往里面灌更多的数据,看看它是否还可以继续精确下去,如果不能精确,差距有多大。

import redis

client = redis.StrictRedis()
for i in range(100000):
    client.pfadd("codehole", "user%d" % i)
print 100000, client.pfcount("codehole")
> python pftest.py 100000 99723

pfmerge

HyperLogLog 除了上面的 pfadd 和 pfcount 之外,还提供了第三个指令 pfmerge,用于将多个 pf 计数值累加在一起形成一个新的 pf 值。

比如在网站中我们有两个内容差不多的页面,运营说需要这两个页面的数据进行合并。其中页面的 UV 访问量也需要合并,那这个时候 pfmerge 就可以派上用场了。

# 合并三个key到第一个key:test_uv
127.0.0.1:6379> PFMERGE test_uv test_uv2 test_uv3
OK
127.0.0.1:6379> pfcount test_uv
5

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK