Using Redis Bitmap Operations for Precise Statistics with PHP
This article explains Redis bitmap data structures, introduces the main bitmap commands (BITSET, BITGET, BITCOUNT), and provides a complete PHP example that demonstrates how to record user sign‑ins and count them efficiently using Redis bit operations.
Bitmaps are a data structure composed of consecutive binary bits that can store only 0 or 1, enabling efficient bit‑level operations. Redis supports bitmap commands, allowing fast creation, reading, setting, and counting of bits for precise statistical tasks.
1. Introduction to Redis Bitmap Operations
Redis provides a set of commands such as BITSET, BITGET, and BITCOUNT to manipulate bitmaps. BITSET writes a specific bit, BITGET reads a bit, and BITCOUNT returns the number of bits set to 1 within a given range.
2. Common Redis Bitmap Commands
• BITSET : Sets a bit at a given offset to 0 or 1, e.g., BITSET key 0 1 . • BITGET : Retrieves the value of a bit at a specific offset, e.g., BITGET key 0 . • BITCOUNT : Counts the number of bits set to 1 in a bitmap or a sub‑range, e.g., BITCOUNT key 0 9 .
3. Redis Bitmap Example (PHP)
The following PHP script demonstrates how to use Redis bitmap commands to implement a user sign‑in statistics feature.
<?php
/**
* Redis bitmap operation example: user sign‑in statistics
*/
// Include Predis autoloader
require 'Predis/Autoloader.php';
PredisAutoloader::register();
// Connect to Redis
$redis = new PredisClient();
// Function to record a user's sign‑in
function userSign($userId, $date)
{
global $redis;
$key = 'user_sign:' . $date;
$redis->setbit($key, $userId, 1);
}
// Function to get the total sign‑in count for a date
function getUserSignCount($date)
{
global $redis;
$key = 'user_sign:' . $date;
$count = $redis->bitcount($key);
return $count;
}
// Example usage
$user1 = 1;
$user2 = 2;
$date = date('Ymd');
userSign($user1, $date);
userSign($user2, $date);
$count = getUserSignCount($date);
echo "User sign‑in count: {$count}\n";
?>4. Explanation of the Example
The script defines userSign to set a bit representing a user's sign‑in for a specific date, and getUserSignCount uses BITCOUNT to retrieve the total number of bits set to 1, i.e., the number of users who signed in. The main program records two users and prints the resulting count.
5. Conclusion
Redis bitmap operations provide an efficient way to achieve precise statistical functions. By using BITSET/BITGET to manipulate individual bits and BITCOUNT to aggregate them, developers can implement features such as user sign‑in tracking with minimal storage and high performance, as illustrated in the PHP example.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.