Understanding Redis Hashes Using C++

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 like 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.
  2. Retrieve data from a hash using the HGETALL command.

Let's look at an example:

#include <iostream>
#include <hiredis/hiredis.h>

int main() {
    // Connect to Redis
    redisContext* context = redisConnect("127.0.0.1", 6379);
    if (context == NULL || context->err) {
        if (context) {
            std::cerr << "Error: " << context->errstr << std::endl;
            redisFree(context);
        } else {
            std::cerr << "Can't allocate redis context" << std::endl;
        }
        return 1;
    }

    // Using hashes to store and retrieve fields and values
    redisReply* reply;
    const char* userKey = "user:1000";

    // Setting hash fields
    reply = (redisReply*)redisCommand(context, "HSET %s username %s email %s", userKey, "alice", "alice@example.com");
    if (reply == NULL) {
        redisFree(context);
        return 1;
    }
    freeReplyObject(reply);

    // Retrieving all fields and values from the hash
    reply = (redisReply*)redisCommand(context, "HGETALL %s", userKey);
    if (reply != NULL && reply->type == REDIS_REPLY_ARRAY) {
        std::cout << "User details: {";
        for (size_t i = 0; i < reply->elements; i += 2) {
            std::cout << reply->element[i]->str << ": " << reply->element[i + 1]->str;
            if (i < reply->elements - 2) {
                std::cout << ", ";
            }
        }
        std::cout << "}" << std::endl;
    }
    freeReplyObject(reply);

    // Cleanup
    redisFree(context);
    return 0;
}
// Expected Output:
// User details: {username: alice, email: alice@example.com}

In this example:

  • The HSET command adds the fields username and email to the hash user:1000.
  • The HGETALL command retrieves all fields and values from the user:1000 hash.
    • Additionally, we could use HGET to retrieve a specific field from the hash. For example, to retrieve the username field, we would use the command redisCommand(context, "HGET %s %s", userKey, "username").
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