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:
- Increment and decrement numeric values.
- Modify numeric values using operations such as increments by a floating point.
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:
- After setting initial values for
count
,completion_rate
, andduration
, we perform various operations:decr('count')
decreases the value ofcount
by 1. You can also provide a second argument todecr
to decrement by a specific value:decr('count', 2)
will decrementcount
by 2. Note, thatdecr
can only be used on integer values.incrbyfloat('completion_rate', 1.5)
incrementscompletion_rate
by 1.5. Note, that this method can be used on integer and floating-point values.incr('duration')
increases theduration
by 1. You can also provide second argument toincr
to increment by a specific value:incr('duration', 5)
will incrementduration
by 5. Note, thatincr
can only be used on integer values.
- Finally, we retrieve and decode the values to display the updated state.
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!