Understanding Redis Hashes

Understanding Redis Hashes

Welcome back! We've covered how to connect to Redis, work with strings, numbers, and 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:

<?php

require 'vendor/autoload.php';

Predis\Autoloader::register();

// Create a new Redis client
$client = new Predis\Client([
    'scheme' => 'tcp',
    'host'   => '127.0.0.1',
    'port'   => 6379,
]);

// Using hashes to store and retrieve fields and values
$client->hset('user:1000', 'username', 'alice');
$client->hset('user:1000', 'email', 'alice@example.com');

$user = $client->hgetall('user:1000');
echo "User details:\n";
print_r($user); // Output: User details: Array ( [username] => alice [email] => alice@example.com )

$username = $client->hget('user:1000', 'username');
echo "Username: $username\n"; // Output: Username: alice

?>

In this example:

  • The hset command adds the fields username and email to the hash user:1000. The hash key is user:1000, and the fields are username and email, with corresponding values alice and alice@example.com.
  • The hgetall command retrieves all fields and values from the user:1000 hash. The result is stored in the $user variable, which is then printed to the console. Similarly, you can use hget to retrieve a single field from a hash by specifying the field name (username in this case).

Using HSet to Supply Multiple Fields and Values

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