redis提供了对于位图的位运算的支持,全部命令如下:
127.0.0.1:6379> help @bitmap
BITCOUNT key [start end [BYTE|BIT]]
summary: Count set bits in a string
since: 2.6.0
BITFIELD key [GET encoding offset|[OVERFLOW WRAP|SAT|FAIL] SET encoding offset value|INCRBY encoding offset increment [GET encoding offset|[OVERFLOW WRAP|SAT|FAIL] SET encoding offset value|INCRBY encoding offset increment ...]]
summary: Perform arbitrary bitfield integer operations on strings
since: 3.2.0
BITFIELD_RO key [GET encoding offset [GET encoding offset ...]]
summary: Perform arbitrary bitfield integer operations on strings. Read-only variant of BITFIELD
since: 6.0.0
BITOP operation destkey key [key ...]
summary: Perform bitwise operations between strings
since: 2.6.0
BITPOS key bit [start [end [BYTE|BIT]]]
summary: Find first bit set or clear in a string
since: 2.8.7
GETBIT key offset
summary: Returns the bit value at offset in the string value stored at key
since: 2.2.0
SETBIT key offset value
summary: Sets or clears the bit at offset in the string value stored at key
since: 2.2.0
下面挑一些命令来简述,
setbit
改变指定偏移量的位的值,偏移量的范围为从整个value的所有字节的第0个字节的第0位,到最后一个字节的最有一个比特位
127.0.0.1:6379> help setbit
SETBIT key offset value
summary: Sets or clears the bit at offset in the string value stored at key
since: 2.2.0
group: bitmap
bitpos
找到指定范围(start-end)字节/比特上,第一个满足参数bit的字节/比特的偏移量
127.0.0.1:6379> help bitpos
BITPOS key bit [start [end [BYTE|BIT]]]
summary: Find first bit set or clear in a string
since: 2.8.7
group: bitmap
bitcount
统计指定范围(start - end)里为1的字节/比特的个数。
127.0.0.1:6379> help BITCOUNT
BITCOUNT key [start end [BYTE|BIT]]
summary: Count set bits in a string
since: 2.6.0
group: bitmap
bitop
对两个key对应的value进行位运算,并将结果与destkey作为键值对存储在redis中。
127.0.0.1:6379> help bitop
BITOP operation destkey key [key ...]
summary: Perform bitwise operations between strings
since: 2.6.0
group: bitmap
下面是示例:
//在第1与第6比特位上设置为1,即0100 0010,在ascii中对应B
127.0.0.1:6379> setbit k1 1 1
(integer) 0
127.0.0.1:6379> setbit k1 6 1
(integer) 0
127.0.0.1:6379> get k1
"B"
//在第1与第7比特位上设置为1,即0100 0001,在ascii中对应A
127.0.0.1:6379> setbit k2 1 1
(integer) 0
127.0.0.1:6379> setbit k2 7 1
(integer) 0
127.0.0.1:6379> get k2
"A"
//k1与k2对应的value进行与运算,结果作为"andkey"的value
//0100 0001&0100 0010,结果为0100 0000,在ascii中对应@
127.0.0.1:6379> bitop and andkey k1 k2
(integer) 1
127.0.0.1:6379> get andkey
"@"
//k1与k2对应的value进行或运算,结果作为"orkey"的value
//0100 0001 | 0100 0010,结果为0100 0011,在ascii中对应C
127.0.0.1:6379> bitop or orkey k1 k2
(integer) 1
127.0.0.1:6379> get orkey
"C"
//统计orkey的值的0到1比特位上的1的个数。0100 0011,0到1比特位为前2位,只有1个比特位数值为1
127.0.0.1:6379> BITCOUNT orkey 0 1 bit
(integer) 1
位图的优势在于运算最快、同时也很省空间。