What is Bitmap in Redis: Explanation and Usage
bitmap is a data structure that stores bits (0s and 1s) efficiently inside a string value. It allows you to set, clear, and query individual bits, making it useful for tracking boolean states or flags in a compact way.How It Works
Think of a bitmap in Redis like a long row of light switches, where each switch can be either ON (1) or OFF (0). Instead of storing full numbers or text, Redis stores these switches as bits inside a string, which saves space when you only need to track simple yes/no or true/false states.
Each bit in the bitmap has a position, starting from 0. You can turn a bit ON or OFF by setting it to 1 or 0. Redis provides commands to manipulate these bits directly, so you can quickly check if a bit is set or count how many bits are ON. This is very fast and uses very little memory compared to other data types.
Example
This example shows how to set and get bits in a Redis bitmap to track user activity on days of a month.
SETBIT user:activity 0 1 SETBIT user:activity 1 0 SETBIT user:activity 2 1 GETBIT user:activity 0 GETBIT user:activity 1 BITCOUNT user:activity
When to Use
Use Redis bitmaps when you need to track many boolean flags efficiently, such as:
- Tracking user logins or activity days in a month
- Implementing feature flags or toggles
- Counting unique events or states with minimal memory
- Performing fast bitwise operations like AND, OR, XOR on sets of flags
Bitmaps are ideal when you want to save memory and perform quick checks on large sets of binary data.
Key Points
- Bitmaps store bits inside Redis strings for compact boolean data.
- Commands like
SETBIT,GETBIT, andBITCOUNTmanipulate bits efficiently. - Useful for tracking flags, user activity, and performing bitwise operations.
- Very memory efficient compared to storing full values for each flag.