It’s time to explore Redis (REmote DIctionary Service), a high-speed, in-memory NoSQL data store. Redis is often called a ‘data structure server’ because it can store and manipulate different data types like strings, lists, sets, and hashes, not just simple key-value pairs. Because it keeps its entire dataset in RAM, Redis is exceptionally fast, making it a popular choice for caching, real-time analytics, and message queues.
Table of Contents
💻 Redis Data Types
Redis’s power comes from its versatile data types. The most common include:
- Strings: The most basic type, which can store text or binary data up to 512MB.
- Lists: A list of strings, sorted by insertion order. You can push elements to the head (
LPUSH
) or tail (RPUSH
). - Sets: An unordered collection of unique strings. You can perform powerful operations like unions and intersections.
- Hashes: A map between string fields and string values, perfect for storing objects.
- Sorted Sets: Similar to sets, but each member has an associated score, which is used to keep the set ordered.
💻 Interacting with Redis via CLI
You can interact with Redis directly from your terminal using the redis-cli
tool. It provides an interactive shell for running commands.
# Start the Redis client
$ redis-cli
127.0.0.1:6379>
# Set a string value
127.0.0.1:6379> SET aKey "Mihalis"
OK
# Get a string value
127.0.0.1:6379> GET aKey
"Mihalis"
# Push items to a list
127.0.0.1:6379> LPUSH aList "123"
(integer) 1
127.0.0.1:6379> RPUSH aList "Tsoukalos"
(integer) 2
# Get a range of items from a list
127.0.0.1:6379> LRANGE aList 0 -1
1) "123"
2) "Tsoukalos"
💻 Using Redis with Python
To use Redis in your Python applications, you’ll need to install the official client library. The code is simple and maps directly to the Redis commands.
- Install the Library:
pip install redis
- Connect and Use in Python:
import redis
# Connect to the Redis server
r = redis.StrictRedis(host='localhost', port=6379, db=0)
# Set and get a value
r.set('One', 'Two')
myVal = r.get('One')
# rpush returns the new length of the list
r.rpush('telephone', '123', 'Mihalis', 'Tsoukalos')
# lrange returns a list of values
aList = r.lrange('telephone', 0, -1)
print(aList)
More Topics
- Riak NoSQL Guide: What’s the Big Deal?
- MongoDB Guide: Build a Blog with Python and Bottle
- MongoDB Guide: An Admin’s Guide to Maximum Power
- MongoDB Guide: Using Native Drivers with Python and Ruby
- MariaDB Guide: The Open Source MySQL Alternative
- SQLite3 Guide: Getting Started with Python
- A Beginner’s Guide to Go: Explore Functions