Bitmap operations bitmap

Bitmap operations bitmap

A definition of

1, the bitmap is not a true data type, which is defined in the character string type
2, the value of a string type can store up to 512M bytes of content, the upper limit of bits: 2 ^ 32
1MB = 1024KB
1KB = 1024Byte (bytes )
1Byte 8bit = (bits)

Two strong points

Real-time statistics can be extremely space-saving. Official under simulated 100 million 28 million user simulation environment, on a MacBookPro, typical statistics such as "number of days users' consumption of time is less than 50ms, 16MB memory footprint

Three settings on a certain (setbit)

# Set values on a certain (offset is the offset from zero) 
SetBit Key offset value
 # acquires a certain value 
GETBIT Key offset
 # statistical value of the key corresponding to how many. 1   
bitCount Key (bitCount key)

Examples

# The default extension bits filled with zeros 
127.0.0.1:6379> the SET MyKey ab
OK
127.0.0.1:6379> get mykey
"ab"
127.0.0.1:6379> SETBIT mykey 0 1
(integer) 0
127.0.0.1:6379> get mykey
"\xe1b"
127.0.0.1:6379> 

Gets the value of a four on a

  GETBIT key offset

127.0.0.1:6379> GETBIT mykey 3
(integer) 0
127.0.0.1:6379> GETBIT mykey 0
(integer) 1

Five bitcount

Statistical key value corresponding to the number of 1 in

127.0.0.1:6379> SETBIT user001 1 1
(integer) 0
127.0.0.1:6379> SETBIT user001 30 1
(integer) 0
127.0.0.1:6379> bitcount user001
(integer) 2

Case scenarios

The number of users on-line website statistics (look for active users)

User name key, as the day on the line offset, is set to 1 on the line

Example: User name user001 of this first line of the sky, the sky line 30

SETBIT user1:login 1 1

SETBIT user1:login 30 1

BITCOUNT user1:login

import redis

r = redis.Redis(host='192.168.43.49',port=6379,db=0)

# User1, the year the first day and 5 days to log 
r.setbit ( ' user1: the Login ' , 1, 1 )
r.setbit ( ' user1: the Login ' , 5,1 )
 # user2, the year of 100 days and 200 days Login 
r.setbit ( ' user2: the Login ' , 100,1 )
r.setbit ( ' user2: the Login ' , 200, 1 )
 # USER3, the year several days Login 
for i in the Range (0,365,2 ):
    r.setbit ( ' USER3: the Login ' , i, 1 )
 # user4, the year several days Login 
for i in the Range (0,365,3 ):
    r.setbit('user4:login',i,1)

user_list = r.keys('user*')
print(user_list)

# Of active users 
ACTIVE_USERS = []
 # inactive users 
noactive_user = []

for the User in user_list:
     # statistics the number of bitmap 1 
    login_count = r.bitcount (the User)
     IF login_count> = 100 :
       active_users.append((user,login_count))
    else:
      noactive_user.append((user,login_count))

# Print active users 
for the Active in ACTIVE_USERS:
     Print ( ' active users: ' , the Active)

 

Guess you like

Origin www.cnblogs.com/maplethefox/p/11311821.html