Advanced Redis Data Types: Geospatial, HyperLogLog, and Bitmaps
Geospatial Data
Redis handles geographic coordinates using Sorted Sets. Longitude and latitude are encoded into a 52-bit GeoHash value, which serves as the score, while the location identifier acts as the member. This enables efficient spatial queries and distance computations.
Key Commands
- GEOADD: Stores geographic coordinates into a key.
GEOADD cities -122.4194 37.7749 "SanFrancisco" -118.2437 34.0522 "LosAngeles"- GEODIST: Computes the distance between two members.
GEODIST cities "SanFrancisco" "LosAngeles" mi- GEOPOS: Retrieves the coordinates for specified members.
GEOPOS cities "SanFrancisco" "LosAngeles"- GEORADIUS: Queries members within a radius from a central coordinate.
GEORADIUS cities -122.0 37.0 100 mi- GEORADIUSBYMEMBER: Queries members within a radius from an existing member.
GEORADIUSBYMEMBER cities "SanFrancisco" 100 miPractical Applications
- Proximity detection for ride-sharing or dating apps to find nearby users.
- Location-based services, such as locating nearby stores or points of interest on a map.
HyperLogLog
HyperLogLog provides a probabilistic approach to cardinality estimation. Instead of storing every unique element, it uses hashing to estimate the number of distinct items. This guarantees a constant memory footprint of roughly 12KB, regardless of the number of elements counted, at the cost of a small standard error rate.
Key Commands
- PFADD: Inserts elements into the HyperLogLog.
PFADD unique_visits userA userB userC- PFCOUNT: Returns the approximate cardinality of the observed set.
PFCOUNT unique_visits- PFMERGE: Combines multiple HyperLogLogs into a single one.
PFMERGE total_visits q1_visits q2_visitsPractical Applications
- Calculating unique visitor counts across distributed systems without high memory overhead.
- Tracking Daily Active Users (DAU) or Monthly Active Users (MAU) for platforms.
- Estimating unique page views or event occurrences in high-traffic scenarios.
Bitmaps
Bitmaps are not an intrinsic data type but a set of bit-oriented operations applied to the String data type. They allow setting or retrieving bits at specific offsets, enabling highly memory-efficient representation of binary states.
Key Commands
- SETBIT: Assigns a bit value (0 or 1) at a given offset.
SETBIT user:login:status 1001 1- GETBIT: Fetches the bit value at a specific offset.
GETBIT user:login:status 1001- BITCOUNT: Counts the number of set bits (1s) in a range.
BITCOUNT user:login:status 0 100Practical Applications
- Tracking boolean states like user online/offline presence, where the offset represents the user ID.
- Feature flag management, toggling features on or off for specific users.
- Performing fast aggregate calculations, such as counting daily logins.
- Serving as the underlying mechanism for Bloom filters to check for potential set membership.