Let us discuss how to use bitmaps in Redis using this tutorial.
Redis Bitmaps
Before diving into the actual commands and store bitmaps, few things to note.
A Bitmap is not a native data type in Redis. In actuality, they are a set of bit-oriented operations built on the String type.
Bit operations are categorized into two main groups:
- Constant-time single-bit operations.
- Group bit operations.
An example of a single-bit operation is setting a bit from 1 to 0 or retrieving the value of a bit.
A group bit operation can involve a process such as getting the number of bits within a specific range.
Redis Create Bitmap
To create a key holding a bitmap in Redis, we use the SETBIT command. The command takes the name of the key, offset value, and the actual bit as arguments.
The syntax is as shown:
If the specified key does not exist, Redis will create a new one that can hold a bit at a specified offset.
The offset value must be greater than or equal to 0 but less than 2^32. This is because bitmaps are limited to 512MB.
RECAP: A bit represents the most basic unit of information and holds two possible values. In simple terms, a bit is used to describe logical stateful information such as yes/no, 1/0, +/-, etc.
Examples are shown below.
(integer) 0
127.0.0.1:6379[10]> SETBIT bitkey 2 0
(integer) 1
Redis Count Number of Set Bits
To determine the number of set bits in Redis, use the BITCOUNT command. Take the example.
127.0.0.1:6379[10]> SETBIT bitkey 4 1
127.0.0.1:6379[10]> SETBIT bitkey 5 1
127.0.0.1:6379[10]> SETBIT bitkey 6 1
127.0.0.1:6379[10]> SETBIT bitkey 7 1
To get the number of set bits, run:
127.0.0.1:6379[10]> BITCOUNT bitkey
(integer) 5
This should return the number of set bits as an integer.
NOTE: A set bit refers to any bit whose value is set to 1.
Redis Bitwise Operations
We can perform bitwise operations using the BITOP command. For example, to achieve a bitwise AND operation, we can do:
(integer) 0
In the example above, we create a new bitmap and call it bitkey2.
We can then perform the bitwise AND operation as shown:
(integer) 1
To get the keys, run:
"\x10"
Redis Retrieve Bit Value
To get the bit value stored at a specific offset, use the GETBIT command followed by the target offset.
An example is as shown:
(integer) 1
If the bit at the specified offset is not set, the command returns 0 as shown:
(integer) 0
Conclusion
In this article, we covered the fundamentals of bitmaps and how to use them in Redis. Check the docs to learn more.
Thanks for reading!!