Working with Redis Hashes

Understanding Redis Hashes

Welcome back! We've covered how to connect to Redis, work with numbers, and handle lists. Now, it's time to explore another crucial data structure in Redis: hashes. Hashes are used to store related pieces of information in a single key, making them perfect for representing objects such as user profiles or configurations.

What You'll Learn

In this lesson, you will learn how to:

  1. Use the HSET command to store fields and values in a Redis hash using C++ and Boost.Redis.
  2. Retrieve data from a hash using the HGETALL command in C++.
  3. Retrieve a specific field from a hash using the HGET command.

Example: Using Hashes with Boost.Redis in C++

Let's look at an example of how to work with Redis hashes in C++ using the Boost.Redis library:

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

#include <boost/redis/src.hpp> // Include Boost.Redis implementation

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;
        connection conn{ioc};

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

        // Prepare Redis commands to set and get hash fields
        request req;
        req.push("HSET", "user:1000", "username", "alice", "email", "alice@example.com");
        req.push("HGETALL", "user:1000");
        req.push("HGET", "user:1000", "username");

        // NOTE: response<T...> stores result<T, adapter::error> for each T
        response<std::int64_t, std::vector<std::string>, std::optional<std::string>> resp;

        conn.async_exec(req, resp,
            [&resp, &conn](boost::system::error_code ec, std::size_t) {
                if (ec) {
                    std::cerr << "Error executing Redis commands: " << ec.message() << std::endl;
                    conn.cancel();
                    return;
                }

                // HSET result
                const auto& hset_res = std::get<0>(resp); // result<int64_t, error>
                if (hset_res) {
                    std::cout << "HSET Response (fields added): " << hset_res.value() << std::endl;
                } else {
                    std::cout << "HSET failed" << std::endl;
                }

                // HGETALL result
                const auto& hgetall_res = std::get<1>(resp); // result<vector<string>, error>
                if (hgetall_res) {
                    const auto& fields = hgetall_res.value();
                    std::cout << "User details: { ";
                    for (std::size_t i = 0; i + 1 < fields.size(); i += 2) {
                        std::cout << fields[i] << ": " << fields[i + 1];
                        if (i + 2 < fields.size()) std::cout << ", ";
                    }
                    std::cout << " }" << std::endl;
                } else {
                    std::cout << "HGETALL failed" << std::endl;
                }

                // HGET result
                const auto& hget_res = std::get<2>(resp); // result<optional<string>, error>
                if (hget_res) {
                    if (const auto& username = hget_res.value(); username) {
                        std::cout << "Username field: " << *username << std::endl;
                    } else {
                        std::cout << "Username field: (nil)" << std::endl;
                    }
                } else {
                    std::cout << "HGET failed" << std::endl;
                }

                conn.cancel(); // Stop the connection
            });

        ioc.run(); // Run the event loop until all operations complete

    } catch (const std::exception& e) {
        std::cerr << "Exception: " << e.what() << std::endl;
        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