redis的bitmaps和HyperLogLog

代码:

#coding=utf-8

import redis

if 0:
    r = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
else:
    pool = redis.ConnectionPool(host='localhost', port=6379, db=0, decode_responses=True)
    r = redis.Redis(connection_pool=pool)

# 设置用户ID为5的用户已读状态
r.setbit('article_read', 5, 1)  # 5是用户ID,1表示已读
r.setbit('article_read', 4, 1)  # 4是用户ID,1表示已读
r.setbit('article_read', 11, 1)  # 11是用户ID,1表示已读
r.setbit('article_read', 12, 0)  # 12是用户ID,1表示已读

is_read = r.getbit('article_read', 5)  # 获取用户ID为5的用户是否已读状态
print("用户5读取文档的状态:", bool(is_read))

read_count = r.bitcount('article_read')  # 计算已读用户数量
print("统计已读用户数量:", read_count)


r.setbit('article_a_read', 12, 1)
r.setbit('article_b_read', 12, 1)
r.setbit('article_a_read', 11, 1)
r.setbit('article_b_read', 11, 0)
r.setbit('article_a_read', 10, 0)
r.setbit('article_b_read', 10, 1)

# 假设文章A和文章B的Bitmaps分别为 article_a_read 和 article_b_read
# 使用BITOP AND来找出同时阅读了A和B的用户
r.bitop('AND', 'article_both_read', 'article_a_read', 'article_b_read')
 
# 查看同时阅读了A和B的用户数量
both_read_count = r.bitcount('article_both_read')
print("查看同时阅读了A和B的用户数量:", both_read_count)

 

输出:

用户5读取文档的状态: True
统计已读用户数量: 3
查看同时阅读了A和B的用户数量: 1

 

代码:

#coding=utf-8

import redis

if 0:
    r = redis.StrictRedis(host='localhost', port=6381, db=0, decode_responses=True)
else:
    pool = redis.ConnectionPool(host='localhost', port=6381, db=0, decode_responses=True)
    r = redis.Redis(connection_pool=pool)

# 添加一个元素到HyperLogLog
r.pfadd('my_hll', 'element1')
r.pfadd('my_hll', 'element2')

# 计算HyperLogLog中元素的近似数量
approx_count = r.pfcount('my_hll')
print(f"my_hll中元素的数量: {approx_count}")

# 假设还有另一个HyperLogLog 'another_hll'
r.pfadd('another_hll', 'element2')
r.pfadd('another_hll', 'element3')

# 计算HyperLogLog中元素的近似数量
approx_count = r.pfcount('another_hll')
print(f"another_hll中元素的数量: {approx_count}")

# 合并两个HyperLogLogs并获取近似计数
merged_count = r.pfcount('my_hll', 'another_hll')
print(f"my_hll和another_hll中元素的数量: {merged_count}")

 

输出:

my_hll中元素的数量: 2
another_hll中元素的数量: 2
my_hll和another_hll中元素的数量: 3

 

posted @ 2025-05-23 17:58  河北大学-徐小波  阅读(270)  评论(0)    收藏  举报