Welcome back! Now that you've learned how to work with numbers in Redis, it's time to build on that knowledge and explore some basic operations with these numbers. This lesson will show you how to perform operations like incrementing, decrementing, and modifying numeric values directly in Redis.
In this lesson, you will learn how to:
Here's the code snippet that we'll be working with:
Python1import redis 2 3# Connect to Redis 4client = redis.Redis(host='localhost', port=6379, db=0) 5 6# Setting and getting string values 7client.set('count', 5) 8client.set('completion_rate', 95.5) 9client.set('duration', 0) # Ensure 'duration' is set initially 10 11client.decr('count') 12client.incrbyfloat('completion_rate', 1.5) 13client.incr('duration') 14 15count = client.get('count') 16completion_rate = client.get('completion_rate') 17duration = client.get('duration') 18 19print(f"Course count: {count.decode('utf-8')}") 20print(f"Completion rate: {completion_rate.decode('utf-8')}") 21print(f"Duration: {duration.decode('utf-8')}")
Let's break it down:
count
, completion_rate
, and duration
, we perform various operations:
decr('count')
decreases the value of count
by 1. You can also provide a second argument to decr
to decrement by a specific value: decr('count', 2)
will decrement count
by 2. Note, that decr
can only be used on integer values.incrbyfloat('completion_rate', 1.5)
increments completion_rate
by 1.5. Note, that this method can be used on integer and floating-point values.incr('duration')
increases the duration
by 1. You can also provide second argument to incr
to increment by a specific value: incr('duration', 5)
will increment duration
by 5. Note, that incr
can only be used on integer values.Understanding how to perform operations with numbers in Redis is essential for real-world applications. Imagine you're building a learning management system: you would track user progress, completion rates, and time spent on courses. Redis makes it fast and easy to update these numbers in real-time.
By the end of this lesson, you'll be comfortable with basic numeric operations in Redis, preparing you for more advanced tasks. Ready to get started? Let's dive into the practice section and enhance your Redis skills!