REDIS (Usage & Application)
Redis, often described with the old lingo of an in-memory database and key-value No-SQL database, conceals a world of versatile data structures within its seemingly simple structure. In this article, we aim to unravel the layers of Redis beyond its commands and internal workings, focusing on understanding the true potential of keys and values. We’ll explore the diverse data structures supported by Redis and delve into their respective use cases, providing answers to questions you may have about what Redis can store and how it can elevate your data management strategies.
INTRODUCTION
Redis is an open source , in-memory data structure store used as a database, cache, message broker, and streaming engine. Redis has built-in replication, Lua scripting, LRU eviction, transactions, and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.
Redis also provides a variety of data structures which we are going to explore. But before that, let’s understand key-value of Redis.
Redis Keys : Redis keys can be any specific binary sequence. For simplicity, and human readablilty, we use strings
Redis Values : In Redis, the value associated with a key can be one of several data structures. Each data structure has its own set of operations and use cases. Let’s discuss those and how your application can benefit from it.
DATA STRUCTURES
- STRINGS :
- We can use it as keys, as values. Remember, string keys can contain numeric values where we can perform operations like INCR (increment)
- Storing simple key-value pairs, caching, counters, and basic string manipulation.
- Commands:
SET
,GET
,INCR
,APPEND
, etc
redis> SET numKey "10"
OK
redis> INCR numkey
11
redis> INCR numkey
22
2. Lists : Redis lists are implemented via Linked Lists. Some of its applications are as follows.
- Implement stacks and queues.
- Build queue management for background worker systems.
- Remember the latest updates posted by users into a social network.
- In many use cases we just want to use lists to store the latest items, whatever they are: social network updates, logs, or anything else.
- Redis allows us to use lists as a capped collection, only remembering the latest N items and discarding all the oldest items using the
LTRIM
command. - Commands:
LPUSH
,RPUSH
,LPOP
,RPOP
,LRANGE
, etc.
3. SETS :
- Track unique items (e.g., track all unique IP addresses accessing a given blog post).
- Represent relations (e.g., the set of all users with a given role).
- Perform common set operations such as intersection, unions, and differences.
- Commands:
SADD
,SREM
,SMEMBERS
,SUNION
,SINTER
, etc.
4. HASH : Just like an ordinary hashMap, Redis provides us with this data structure, which we can use for :
- Storing and retrieving field-value pairs, representing objects or records.
package io.redis.examples;
import redis.clients.jedis.UnifiedJedis;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HashExample {
public void run() {
try (UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379")) {
String productKey = "product:123";
// Sample product data
Map<String, String> productData = new HashMap<>();
productData.put("name", "Laptop");
productData.put("brand", "ABC");
productData.put("price", "999.99");
jedis.hset(productKey, productData);
jedis.hset(productKey, productData);
String brand = jedis.hget(productKey, "brand");
System.out.println(brand); // ABC
Map<String, String> productDataCopy = jedis.hgetAll("bike:1");
System.out.println(res4); //fetches all
}
}
}
- Commands:
HSET
,HGET
,HGETALL
,HINCRBY
, etc.
5. SORTED SET : The difference between a set and a sorted set is that each entry here is sorted based on a score. Based on this unique property, we can use it for the following :
- Leaderboards. For example, you can use sorted sets to easily maintain ordered lists of the highest scores in a massive online game.
- Rate limiters. In particular, you can use a sorted set to build a sliding-window rate limiter to prevent excessive API requests. In some other article, I would cover this aspect of using Redis.
- Commands:
ZADD
,ZREM
,ZRANGE
,ZSCORE
, etc
6. STREAMS : Redis stream is like that magical scroll in your computer. It’s a special way of keeping track of events as they happen, making sure you never forget anything, and allowing lots of people or programs to share and add to the story.
Technically speaking, streams are like an append-only log but also implements several operations to overcome some of the limits of a typical append-only log.
Use Case :
- Event sourcing (e.g., tracking user actions, clicks, etc.)
- Sensor monitoring (e.g., readings from devices in the field)
- Notifications (e.g., storing a record of each user’s notifications in a separate stream)
XADD demoStream * name test1
XADD demoStream * name test2
XADD demoStream * name test3
// We can add any type of data structure in the stream
private static void logEntry(Jedis jedis, String streamKey, String level, String message) {
Map<String, String> logData = new HashMap<>();
logData.put("level", level);
logData.put("message", message);
logData.put("timestamp", String.valueOf(System.currentTimeMillis()));
StreamEntryID entryID = jedis.xadd(streamKey, logData); //Adding in the stream
System.out.println("Logged entry with ID: " + entryID);
}
7. BITMAPS : Bitmaps are a set of bit-oriented operations defined on the String type which is treated like a bit vector.
- Efficiently representing and manipulating sets of binary values (e.g., user presence)
- Commands:
SETBIT
,GETBIT
,BITOP
, etc.
8. GEOSPATIAL INDEXES :
- Redis geospatial indexes let you store coordinates and search for them. This data structure is useful for finding nearby points within a given radius or bounding box.
- Commands:
GEOADD
,GEODIST
,GEORADIUS
, etc
9. PROBABILISTIC DATA STRUCTURE :
- There are multiple probabilistic data structures provided by Redis that be leveraged for one’s use case.
- These are HyperLogLog, Bloom Filter, Cuckoo Filter which in itself a vast topic to discuss.
In conclusion, Redis offers a powerful arsenal of data structures that can be strategically harnessed to address your specific use case. Whether it’s optimizing for speed, efficiency, or simplicity, Redis provides a robust set of tools, including hashes, lists, sets, and sorted sets, that cater to diverse data management needs. Leveraging these structures can unlock the full potential of Redis, making it a valuable asset for tailoring solutions that align seamlessly with your unique requirements. Dive into Redis and explore how these data structures can elevate the performance and responsiveness of your applications.