Numeric Operations in Redis

Moving On to Operations with Numbers

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.

What You'll Learn

In this lesson, you will learn how to:

  1. Increment and decrement numeric values.
  2. Modify numeric values using operations such as increments by a floating point.

Example Code: Performing Numeric Operations in Redis with C++ and Boost.Redis

Here is a C++ code snippet that demonstrates how to perform these operations using Boost.Redis:

C++
#include <boost/redis.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/detached.hpp>
#include <boost/asio/consign.hpp>
#include <optional>
#include <iostream>

#include <boost/redis/src.hpp>

namespace net = boost::asio;
using boost::redis::connection;
using boost::redis::config;
using boost::redis::logger;
using boost::redis::request;
using boost::redis::response;

int main() {
    try {
        net::io_context ioc;

        // Create a shared connection object
        auto conn = std::make_shared<connection>(ioc.get_executor());

        config cfg; // defaults: 127.0.0.1:6379
        conn->async_run(cfg, logger{logger::level::disabled},
                        net::consign(net::detached, conn));

        // Prepare Redis commands to set and modify numeric values
        request req;
        req.push("SET", "count", "5");
        req.push("SET", "completion_rate", "95.5");
        req.push("SET", "duration", "0");

        // Perform numeric operations
        req.push("DECR", "count");
        req.push("INCRBYFLOAT", "completion_rate", "1.5");
        req.push("INCR", "duration");

        // Retrieve the updated values
        req.push("GET", "count");
        req.push("GET", "completion_rate");
        req.push("GET", "duration");

        response<
            std::string, std::string, std::string,
            std::int64_t, double, std::int64_t,
            std::optional<std::string>, std::optional<std::string>, std::optional<std::string>
        > resp;

        conn->async_exec(req, resp,
            [conn, &resp](boost::system::error_code ec, std::size_t) {
                if (!ec) {
                    // Print SET response (first one shown as example)
                    std::cout << "SET count: " << std::get<0>(resp).value() << "\n";
                    // Other SET responses can be retrieved similarly from indices 1 and 2

                    // Print operation response (first one shown as example)
                    std::cout << "DECR count: " << std::get<3>(resp).value() << "\n";
                    // Other operation responses can be retrieved similarly from indices 4 and 5

                    // Print GET responses
                    if (auto& count = std::get<6>(resp); count && count.value()) {
                        std::cout << "Course count: " << *count.value() << "\n";
                    } else {
                        std::cout << "Course count: (nil)\n";
                    }

                    if (auto& rate = std::get<7>(resp); rate && rate.value()) {
                        std::cout << "Completion rate: " << *rate.value() << "\n";
                    } else {
                        std::cout << "Completion rate: (nil)\n";
                    }

                    // Other GET responses can be retrieved similarly from index 8
                } else {
                    std::cerr << "Error executing Redis commands: "
                              << ec.message() << "\n";
                }
                conn->cancel();
            });

        ioc.run();
    } catch (const std::exception& e) {
        std::cerr << "Exception: " << e.what() << "\n";
        return 1;
    }
    return 0;
}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal