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:
JavaScript1import { createClient } from 'redis'; 2 3const client = createClient(); 4client.on('error', (err) => console.log('Redis Client Error', err)); 5await client.connect(); 6 7// Setting and getting string values 8await client.set('count', 5); 9await client.set('completion_rate', 95.5); 10await client.set('duration', 0); 11 12await client.decr('count'); // 4 13await client.decrBy('count', 2); // 2 14await client.incr('duration'); // 1 15await client.incrBy('duration', 2); // 3 16await client.incrByFloat('completion_rate', 1.5); // 97 17 18// Fetch the values and log them 19const count = await client.get('count'); 20const duration = await client.get('duration'); 21const completion_rate = await client.get('completion_rate'); 22 23console.log(`Course count: ${count}`); // 2 24console.log(`Duration: ${duration}`); // 3 25console.log(`Completion rate: ${completion_rate}`); // 97 26 27await client.disconnect();
- After setting initial values for
count
,completion_rate
, andduration
, we perform various operations:decr
operation decrements the value ofcount
by 1, anddecrBy
decrements it by the specified value, in this case, 2. So, the final value ofcount
is 2.incr
operation increments the value ofduration
by 1, andincrBy
increments it by the specified value, in this case, 2. So, the final value ofduration
is 3.incrByFloat
increments the value ofcompletion_rate
by the specified floating-point value, in this case, 1.5. So, the final value ofcompletion_rate
is 97.
- At the end, we fetch the updated values of
count
,duration
, andcompletion_rate
and log them to the console.
Note, that the incr
, decr
, incrBy
, and decrBy
operations cannot be applied to keys that contain floating-point values, that's why we use incrByFloat
to increment floating-point values. Note, that in order to decrement floating-point values, you can use incrByFloat
with a negative value.
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!