HGETALL
Syntax
HGETALL key
- Available since:
- Redis Open Source 2.0.0
- Time complexity:
- O(N) where N is the size of the hash.
- ACL categories:
-
@read,@hash,@slow,
Returns all fields and values of the hash stored at key.
In the returned value, every field name is followed by its value, so the length
of the reply is twice the size of the hash.
Examples
redis> HSET myhash field1 "Hello"
(integer) 1
redis> HSET myhash field2 "World"
(integer) 1
redis> HGETALL myhash
1) "field1"
2) "Hello"
3) "field2"
4) "World"import redis
r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)
hdel1 = r.hset("myhash", "field1", "foo")
print(hdel1)
# >>> 1
hdel2 = r.hget("myhash", "field1")
print(hdel2)
# >>> 1
hdel3 = r.hget("myhash", "field2")
print(hdel3)
# >>> 0
res1 = r.hset("myhash", "field1", "Hello")
print(res1)
# >>> 1
res2 = r.hget("myhash", "field1")
print(res2)
# >>> Hello
res3 = r.hset("myhash", mapping={"field2": "Hi", "field3": "World"})
print(res3)
# >>> 2
res4 = r.hget("myhash", "field2")
print(res4)
# >>> Hi
res5 = r.hget("myhash", "field3")
print(res5)
# >>> World
res6 = r.hgetall("myhash")
print(res6)
# >>> { "field1": "Hello", "field2": "Hi", "field3": "World" }
res7 = r.hset("myhash", "field1", "foo")
print(res7)
# >>> 1
res8 = r.hget("myhash", "field1")
print(res8)
# >>> foo
res9 = r.hget("myhash", "field2")
print(res9)
# >>> None
res10 = r.hset("myhash", mapping={"field1": "Hello", "field2": "World"})
res11 = r.hgetall("myhash")
print(res11) # >>> { "field1": "Hello", "field2": "World" }
res10 = r.hset("myhash", mapping={"field1": "Hello", "field2": "World"})
res11 = r.hvals("myhash")
print(res11) # >>> [ "Hello", "World" ]
import assert from 'node:assert';
import { createClient } from 'redis';
const client = createClient();
await client.connect().catch(console.error);
const hDel1 = await client.hSet('myhash', 'field1', 'Hello')
console.log(hDel1) // 1
const hDel2 = await client.hDel('myhash', 'field1')
console.log(hDel2) // 1
const hDel3 = await client.hDel('myhash', 'field2')
console.log(hDel3) // 0
const res1 = await client.hSet('myhash', 'field1', 'Hello')
console.log(res1) // 1
const res2 = await client.hGet('myhash', 'field1')
console.log(res2) // Hello
const res3 = await client.hSet(
'myhash',
{
'field2': 'Hi',
'field3': 'World'
}
)
console.log(res3) // 2
const res4 = await client.hGet('myhash', 'field2')
console.log(res4) // Hi
const res5 = await client.hGet('myhash', 'field3')
console.log(res5) // World
const res6 = await client.hGetAll('myhash')
console.log(res6)
const res7 = await client.hSet('myhash', 'field1', 'foo')
console.log(res7) // 1
const res8 = await client.hGet('myhash', 'field1')
console.log(res8) // foo
const res9 = await client.hGet('myhash', 'field2')
console.log(res9) // null
const res10 = await client.hSet(
'myhash',
{
'field1': 'Hello',
'field2': 'World'
}
)
const res11 = await client.hGetAll('myhash')
console.log(res11) // [Object: null prototype] { field1: 'Hello', field2: 'World' }
const res12 = await client.hSet(
'myhash',
{
'field1': 'Hello',
'field2': 'World'
}
)
const res13 = await client.hVals('myhash')
console.log(res13) // [ 'Hello', 'World' ]
await client.close();
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.Collections;
import redis.clients.jedis.UnifiedJedis;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
public class CmdsHashExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
Map<String, String> hDelExampleParams = new HashMap<>();
hDelExampleParams.put("field1", "foo");
long hDelResult1 = jedis.hset("myhash", hDelExampleParams);
System.out.println(hDelResult1); // >>> 1
long hDelResult2 = jedis.hdel("myhash", "field1");
System.out.println(hDelResult2); // >>> 1
long hDelResult3 = jedis.hdel("myhash", "field2");
System.out.println(hDelResult3); // >>> 0
Map<String, String> hGetExampleParams = new HashMap<>();
hGetExampleParams.put("field1", "foo");
long hGetResult1 = jedis.hset("myhash", hGetExampleParams);
System.out.println(hGetResult1); // >>> 1
String hGetResult2 = jedis.hget("myhash", "field1");
System.out.println(hGetResult2); // >>> foo
String hGetResult3 = jedis.hget("myhash", "field2");
System.out.println(hGetResult3); // >>> null
Map<String, String> hGetAllExampleParams = new HashMap<>();
hGetAllExampleParams.put("field1", "Hello");
hGetAllExampleParams.put("field2", "World");
long hGetAllResult1 = jedis.hset("myhash", hGetAllExampleParams);
System.out.println(hGetAllResult1); // >>> 2
Map<String, String> hGetAllResult2 = jedis.hgetAll("myhash");
System.out.println(
hGetAllResult2.entrySet().stream()
.sorted((s1, s2)-> s1.getKey().compareTo(s2.getKey()))
.collect(toList())
.toString()
);
// >>> [field1=Hello, field2=World]
Map<String, String> hSetExampleParams = new HashMap<>();
hSetExampleParams.put("field1", "Hello");
long hSetResult1 = jedis.hset("myhash", hSetExampleParams);
System.out.println(hSetResult1); // >>> 1
String hSetResult2 = jedis.hget("myhash", "field1");
System.out.println(hSetResult2); // >>> Hello
hSetExampleParams.clear();
hSetExampleParams.put("field2", "Hi");
hSetExampleParams.put("field3", "World");
long hSetResult3 = jedis.hset("myhash",hSetExampleParams);
System.out.println(hSetResult3); // >>> 2
String hSetResult4 = jedis.hget("myhash", "field2");
System.out.println(hSetResult4); // >>> Hi
String hSetResult5 = jedis.hget("myhash", "field3");
System.out.println(hSetResult5); // >>> World
Map<String, String> hSetResult6 = jedis.hgetAll("myhash");
for (String key: hSetResult6.keySet()) {
System.out.println("Key: " + key + ", Value: " + hSetResult6.get(key));
}
// >>> Key: field3, Value: World
// >>> Key: field2, Value: Hi
// >>> Key: field1, Value: Hello
Map<String, String> hValsExampleParams = new HashMap<>();
hValsExampleParams.put("field1", "Hello");
hValsExampleParams.put("field2", "World");
long hValsResult1 = jedis.hset("myhash", hValsExampleParams);
System.out.println(hValsResult1); // >>> 2
List<String> hValsResult2 = jedis.hvals("myhash");
Collections.sort(hValsResult2);
System.out.println(hValsResult2);
// >>> [Hello, World]
jedis.close();
}
}
package io.redis.examples.async;
import io.lettuce.core.*;
import io.lettuce.core.api.async.RedisAsyncCommands;
import io.lettuce.core.api.StatefulRedisConnection;
import java.util.*;
import java.util.concurrent.CompletableFuture;
public class CmdsHashExample {
public void run() {
Map<String, String> hDelExampleParams = new HashMap<>();
hDelExampleParams.put("field1", "foo");
CompletableFuture<Void> hDelExample = asyncCommands.hset("myhash", hDelExampleParams).thenCompose(res1 -> {
System.out.println(res1); // >>> 1
return asyncCommands.hdel("myhash", "field1");
}).thenCompose(res2 -> {
System.out.println(res2); // >>> 1
return asyncCommands.hdel("myhash", "field2");
}).thenAccept(res3 -> {
System.out.println(res3); // >>> 0
}).toCompletableFuture();
hDelExample.join();
CompletableFuture<Void> hSetExample = asyncCommands.hset("myhash", "field1", "Hello").thenCompose(res1 -> {
System.out.println(res1); // >>> 1
return asyncCommands.hget("myhash", "field1");
}).thenCompose(res2 -> {
System.out.println(res2); // >>> Hello
Map<String, String> hSetExampleParams = new HashMap<>();
hSetExampleParams.put("field2", "Hi");
hSetExampleParams.put("field3", "World");
return asyncCommands.hset("myhash", hSetExampleParams);
}).thenCompose(res3 -> {
System.out.println(res3); // >>> 2
return asyncCommands.hget("myhash", "field2");
}).thenCompose(res4 -> {
System.out.println(res4); // >>> Hi
return asyncCommands.hget("myhash", "field3");
}).thenCompose(res5 -> {
System.out.println(res5); // >>> World
return asyncCommands.hgetall("myhash");
}).thenAccept(res6 -> {
System.out.println(res6);
// >>> {field1=Hello, field2=Hi, field3=World}
}).toCompletableFuture();
hSetExample.join();
Map<String, String> hGetExampleParams = new HashMap<>();
hGetExampleParams.put("field1", "foo");
CompletableFuture<Void> hGetExample = asyncCommands.hset("myhash", hGetExampleParams).thenCompose(res1 -> {
System.out.println(res1); // >>> 1
return asyncCommands.hget("myhash", "field1");
}).thenCompose(res2 -> {
System.out.println(res2); // >>> foo
return asyncCommands.hget("myhash", "field2");
}).thenAccept(res3 -> {
System.out.println(res3); // >>> null
}).toCompletableFuture();
hGetExample.join();
Map<String, String> hGetAllExampleParams = new HashMap<>();
hGetAllExampleParams.put("field1", "Hello");
hGetAllExampleParams.put("field2", "World");
CompletableFuture<Void> hGetAllExample = asyncCommands.hset("myhash", hGetAllExampleParams).thenCompose(res1 -> {
return asyncCommands.hgetall("myhash");
}).thenAccept(res2 -> {
System.out.println(res2);
// >>> {field1=Hello, field2=World}
}).toCompletableFuture();
hGetAllExample.join();
Map<String, String> hValsExampleParams = new HashMap<>();
hValsExampleParams.put("field1", "Hello");
hValsExampleParams.put("field2", "World");
CompletableFuture<Void> hValsExample = asyncCommands.hset("myhash", hValsExampleParams).thenCompose(res1 -> {
return asyncCommands.hvals("myhash");
}).thenAccept(res2 -> {
List<String> sortedValues = new ArrayList<>(res2);
Collections.sort(sortedValues);
System.out.println(sortedValues);
// >>> [Hello, World]
}).toCompletableFuture();
hValsExample.join();
} finally {
redisClient.shutdown();
}
}
}
package io.redis.examples.reactive;
import io.lettuce.core.*;
import io.lettuce.core.api.reactive.RedisReactiveCommands;
import io.lettuce.core.api.StatefulRedisConnection;
import reactor.core.publisher.Mono;
import java.util.*;
public class CmdsHashExample {
public void run() {
RedisClient redisClient = RedisClient.create("redis://localhost:6379");
try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
RedisReactiveCommands<String, String> reactiveCommands = connection.reactive();
Map<String, String> hDelExampleParams = new HashMap<>();
hDelExampleParams.put("field1", "foo");
Mono<Long> hDelExample1 = reactiveCommands.hset("myhash", hDelExampleParams).doOnNext(result -> {
System.out.println(result); // >>> 1
});
hDelExample1.block();
Mono<Long> hDelExample2 = reactiveCommands.hdel("myhash", "field1").doOnNext(result -> {
System.out.println(result); // >>> 1
});
hDelExample2.block();
Mono<Long> hDelExample3 = reactiveCommands.hdel("myhash", "field2").doOnNext(result -> {
System.out.println(result); // >>> 0
});
hDelExample3.block();
Mono<Boolean> hSetExample1 = reactiveCommands.hset("myhash", "field1", "Hello").doOnNext(result -> {
System.out.println(result); // >>> True
});
hSetExample1.block();
Mono<String> hSetExample2 = reactiveCommands.hget("myhash", "field1").doOnNext(result -> {
System.out.println(result); // >>> Hello
});
hSetExample2.block();
Map<String, String> hSetExampleParams = new HashMap<>();
hSetExampleParams.put("field2", "Hi");
hSetExampleParams.put("field3", "World");
Mono<Long> hSetExample3 = reactiveCommands.hset("myhash", hSetExampleParams).doOnNext(result -> {
System.out.println(result); // >>> 2
});
hSetExample3.block();
Mono<String> hSetExample4 = reactiveCommands.hget("myhash", "field2").doOnNext(result -> {
System.out.println(result); // >>> Hi
});
hSetExample4.block();
Mono<String> hSetExample5 = reactiveCommands.hget("myhash", "field3").doOnNext(result -> {
System.out.println(result); // >>> World
});
hSetExample5.block();
Mono<Map<String, String>> hSetExample6 = reactiveCommands.hgetall("myhash").collectMap(
KeyValue::getKey, KeyValue::getValue
).doOnNext(result -> {
System.out.println(result);
// >>> {field1=Hello, field2=Hi, field3=World}
});
hSetExample6.block();
Map<String, String> hGetExampleParams = new HashMap<>();
hGetExampleParams.put("field1", "foo");
Mono<Long> hGetExample1 = reactiveCommands.hset("myhash", hGetExampleParams).doOnNext(result -> {
System.out.println(result); // >>> 1
});
hGetExample1.block();
Mono<String> hGetExample2 = reactiveCommands.hget("myhash", "field1").doOnNext(result -> {
System.out.println(result); // >>> foo
});
hGetExample2.block();
Mono<String> hGetExample3 = reactiveCommands.hget("myhash", "field2").doOnNext(result -> {
System.out.println(result); // >>> null
});
hGetExample3.block();
Map<String, String> hGetAllExampleParams = new HashMap<>();
hGetAllExampleParams.put("field1", "Hello");
hGetAllExampleParams.put("field2", "World");
Mono<Long> hGetAllExample1 = reactiveCommands.hset("myhash", hGetAllExampleParams).doOnNext(result -> {
});
hGetAllExample1.block();
Mono<Map<String, String>> hGetAllExample2 = reactiveCommands.hgetall("myhash").collectMap(
KeyValue::getKey, KeyValue::getValue
).doOnNext(result -> {
System.out.println(result);
// >>> {field1=Hello, field2=World}
});
hGetAllExample2.block();
Map<String, String> hValsExampleParams = new HashMap<>();
hValsExampleParams.put("field1", "Hello");
hValsExampleParams.put("field2", "World");
Mono<Long> hValsExample1 = reactiveCommands.hset("myhash", hValsExampleParams).doOnNext(result -> {
});
hValsExample1.block();
Mono<List<String>> hValsExample2 = reactiveCommands.hvals("myhash").collectList().doOnNext(result -> {
List<String> sortedValues = new ArrayList<>(result);
Collections.sort(sortedValues);
System.out.println(sortedValues);
// >>> [Hello, World]
});
hValsExample2.block();
} finally {
redisClient.shutdown();
}
}
}
package example_commands_test
import (
"context"
"fmt"
"sort"
"github.com/redis/go-redis/v9"
)
func ExampleClient_hset() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.HSet(ctx, "myhash", "field1", "Hello").Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> 1
res2, err := rdb.HGet(ctx, "myhash", "field1").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> Hello
res3, err := rdb.HSet(ctx, "myhash",
"field2", "Hi",
"field3", "World",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> 2
res4, err := rdb.HGet(ctx, "myhash", "field2").Result()
if err != nil {
panic(err)
}
fmt.Println(res4) // >>> Hi
res5, err := rdb.HGet(ctx, "myhash", "field3").Result()
if err != nil {
panic(err)
}
fmt.Println(res5) // >>> World
res6, err := rdb.HGetAll(ctx, "myhash").Result()
if err != nil {
panic(err)
}
keys := make([]string, 0, len(res6))
for key, _ := range res6 {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
fmt.Printf("Key: %v, value: %v\n", key, res6[key])
}
// >>> Key: field1, value: Hello
// >>> Key: field2, value: Hi
// >>> Key: field3, value: World
}
func ExampleClient_hget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res7, err := rdb.HSet(ctx, "myhash", "field1", "foo").Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> 1
res8, err := rdb.HGet(ctx, "myhash", "field1").Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> foo
res9, err := rdb.HGet(ctx, "myhash", "field2").Result()
if err != nil {
fmt.Println(err)
}
fmt.Println(res9) // >>> <empty string>
}
func ExampleClient_hgetall() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password
DB: 0, // use default DB
})
hGetAllResult1, err := rdb.HSet(ctx, "myhash",
"field1", "Hello",
"field2", "World",
).Result()
if err != nil {
panic(err)
}
fmt.Println(hGetAllResult1) // >>> 2
hGetAllResult2, err := rdb.HGetAll(ctx, "myhash").Result()
if err != nil {
panic(err)
}
keys := make([]string, 0, len(hGetAllResult2))
for key, _ := range hGetAllResult2 {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
fmt.Printf("Key: %v, value: %v\n", key, hGetAllResult2[key])
}
// >>> Key: field1, value: Hello
// >>> Key: field2, value: World
}
func ExampleClient_hvals() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
hValsResult1, err := rdb.HSet(ctx, "myhash",
"field1", "Hello",
"field2", "World",
).Result()
if err != nil {
panic(err)
}
fmt.Println(hValsResult1) // >>> 2
hValsResult2, err := rdb.HVals(ctx, "myhash").Result()
if err != nil {
panic(err)
}
sort.Strings(hValsResult2)
fmt.Println(hValsResult2) // >>> [Hello World]
}
func ExampleClient_hdel() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
hdel1, err := rdb.HSet(ctx, "myhash", "field1", "foo").Result()
if err != nil {
panic(err)
}
fmt.Println(hdel1) // >>> 1
hdel2, err := rdb.HDel(ctx, "myhash", "field1").Result()
if err != nil {
panic(err)
}
fmt.Println(hdel2) // >>> 1
hdel3, err := rdb.HDel(ctx, "myhash", "field2").Result()
if err != nil {
fmt.Println(err)
}
fmt.Println(hdel3) // >>> 0
}using StackExchange.Redis;
using Xunit;
namespace Doc;
public class CmdsHashExample
{
public void Run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
// Clear any keys here before using them in tests.
db.KeyDelete("myhash");
bool hdelRes1 = db.HashSet("myhash", "field1", "foo");
RedisValue hdelRes2 = db.HashDelete("myhash", "field1");
Console.WriteLine(hdelRes2); // >>> 1
RedisValue hdelRes3 = db.HashDelete("myhash", "field1");
Console.WriteLine(hdelRes3); // >>> 0
Assert.True(hdelRes1);
Assert.Equal(1, hdelRes2);
Assert.Equal(0, hdelRes3);
db.KeyDelete("myhash");
bool hgetRes1 = db.HashSet("myhash", "field1", "foo");
RedisValue hgetRes2 = db.HashGet("myhash", "field1");
Console.WriteLine(hgetRes2); // >>> foo
RedisValue hgetRes3 = db.HashGet("myhash", "field2");
Console.WriteLine(hgetRes3); // >>> Null
Assert.True(hgetRes1);
Assert.Equal("foo", hgetRes2);
Assert.Equal(RedisValue.Null, hgetRes3);
db.KeyDelete("myhash");
bool hsetRes1 = db.HashSet("myhash", "field1", "Hello");
RedisValue hsetRes2 = db.HashGet("myhash", "field1");
Console.WriteLine(hsetRes2); // >>> Hello
db.HashSet(
"myhash",
[
new("field2", "Hi"),
new("field3", "World")
]
);
RedisValue hsetRes3 = db.HashGet("myhash", "field2");
Console.WriteLine(hsetRes3); // >>> Hi
RedisValue hsetRes4 = db.HashGet("myhash", "field3");
Console.WriteLine(hsetRes4); // >>> World
HashEntry[] hsetRes5 = db.HashGetAll("myhash");
Console.WriteLine($"{string.Join(", ", hsetRes5.Select(h => $"{h.Name}: {h.Value}"))}");
// >>> field1: Hello, field2: Hi, field3: World
Assert.True(hsetRes1);
Assert.Equal("Hello", hsetRes2);
Assert.Equal("Hi", hsetRes3);
Assert.Equal("World", hsetRes4);
Assert.Equal(
"field1: Hello, field2: Hi, field3: World",
string.Join(", ", hsetRes5.Select(h => $"{h.Name}: {h.Value}"))
);
db.KeyDelete("myhash");
db.HashSet("myhash",
[
new("field1", "Hello"),
new("field2", "World")
]
);
HashEntry[] hGetAllResult = db.HashGetAll("myhash");
Array.Sort(hGetAllResult, (a1, a2) => a1.Name.CompareTo(a2.Name));
Console.WriteLine(
string.Join(", ", hGetAllResult.Select(e => $"{e.Name}: {e.Value}"))
);
// >>> field1: Hello, field2: World
Assert.Equal("field1: Hello, field2: World", string.Join(", ", hGetAllResult.Select(e => $"{e.Name}: {e.Value}")));
db.KeyDelete("myhash");
db.HashSet("myhash",
[
new("field1", "Hello"),
new("field2", "World")
]
);
RedisValue[] hValsResult = db.HashValues("myhash");
Array.Sort(hValsResult);
Console.WriteLine(string.Join(", ", hValsResult));
// >>> Hello, World
Assert.Equal("Hello, World", string.Join(", ", hValsResult));
}
}
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use PHPUnit\Framework\TestCase;
use Predis\Client as PredisClient;
class CmdsHashTest extends TestCase
{
private PredisClient $redis;
protected function setUp(): void
{
$this->redis = new PredisClient([
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => 6379,
'password' => '',
'database' => 0,
]);
// Clean up before each test
$this->redis->flushall();
}
public function testCmdsHash(): void
{
echo "\n=== Testing Redis Hash Commands ===\n";
echo "\n--- HDEL Command ---\n";
$hDelResult1 = $this->redis->hset('myhash', 'field1', 'foo');
echo "HSET myhash field1 foo: " . $hDelResult1 . "\n"; // >>> 1
$hDelResult2 = $this->redis->hdel('myhash', 'field1');
echo "HDEL myhash field1: " . $hDelResult2 . "\n"; // >>> 1
$hDelResult3 = $this->redis->hdel('myhash', 'field2');
echo "HDEL myhash field2: " . $hDelResult3 . "\n"; // >>> 0
$this->assertEquals(1, $hDelResult1);
$this->assertEquals(1, $hDelResult2);
$this->assertEquals(0, $hDelResult3);
echo "\n--- HGET Command ---\n";
$hGetResult1 = $this->redis->hset('myhash', 'field1', 'foo');
echo "HSET myhash field1 foo: " . $hGetResult1 . "\n"; // >>> 1
$hGetResult2 = $this->redis->hget('myhash', 'field1');
echo "HGET myhash field1: " . ($hGetResult2 ?? 'null') . "\n"; // >>> foo
$hGetResult3 = $this->redis->hget('myhash', 'field2');
echo "HGET myhash field2: " . ($hGetResult3 ?? 'null') . "\n"; // >>> null
$this->assertEquals(1, $hGetResult1);
$this->assertEquals('foo', $hGetResult2);
$this->assertNull($hGetResult3);
echo "\n--- HGETALL Command ---\n";
$hGetAllResult1 = $this->redis->hmset('myhash', ['field1' => 'Hello', 'field2' => 'World']);
echo "HMSET myhash field1 Hello field2 World: " . ($hGetAllResult1 ? 'OK' : 'FAIL') . "\n"; // >>> OK
$hGetAllResult2 = $this->redis->hgetall('myhash');
echo "HGETALL myhash: " . json_encode($hGetAllResult2) . "\n"; // >>> {"field1":"Hello","field2":"World"}
$this->assertEquals('OK', $hGetAllResult1);
$this->assertEquals(['field1' => 'Hello', 'field2' => 'World'], $hGetAllResult2);
echo "\n--- HSET Command ---\n";
// Clean up first
$this->redis->del('myhash');
$hSetResult1 = $this->redis->hset('myhash', 'field1', 'Hello');
echo "HSET myhash field1 Hello: " . $hSetResult1 . "\n"; // >>> 1
$hSetResult2 = $this->redis->hget('myhash', 'field1');
echo "HGET myhash field1: " . $hSetResult2 . "\n"; // >>> Hello
$hSetResult3 = $this->redis->hmset('myhash', ['field2' => 'Hi', 'field3' => 'World']);
echo "HMSET myhash field2 Hi field3 World: " . ($hSetResult3 ? 'OK' : 'FAIL') . "\n"; // >>> OK
$hSetResult4 = $this->redis->hget('myhash', 'field2');
echo "HGET myhash field2: " . $hSetResult4 . "\n"; // >>> Hi
$hSetResult5 = $this->redis->hget('myhash', 'field3');
echo "HGET myhash field3: " . $hSetResult5 . "\n"; // >>> World
$hSetResult6 = $this->redis->hgetall('myhash');
echo "HGETALL myhash: ";
foreach ($hSetResult6 as $key => $value) {
echo "Key: $key, Value: $value; ";
}
echo "\n";
$this->assertEquals(1, $hSetResult1);
$this->assertEquals('Hello', $hSetResult2);
$this->assertEquals('OK', $hSetResult3);
$this->assertEquals('Hi', $hSetResult4);
$this->assertEquals('World', $hSetResult5);
$this->assertEquals(['field1' => 'Hello', 'field2' => 'Hi', 'field3' => 'World'], $hSetResult6);
echo "\n--- HVALS Command ---\n";
// Clean up first
$this->redis->del('myhash');
$hValsResult1 = $this->redis->hmset('myhash', ['field1' => 'Hello', 'field2' => 'World']);
echo "HMSET myhash field1 Hello field2 World: " . ($hValsResult1 ? 'OK' : 'FAIL') . "\n"; // >>> OK
$hValsResult2 = $this->redis->hvals('myhash');
echo "HVALS myhash: " . json_encode($hValsResult2) . "\n"; // >>> ["Hello","World"]
$this->assertEquals('OK', $hValsResult1);
$this->assertEquals(['Hello', 'World'], $hValsResult2);
echo "\n=== All Hash Commands Tests Passed! ===\n";
}
protected function tearDown(): void
{
// Clean up after each test
$this->redis->flushall();
$this->redis->disconnect();
}
}
mod cmds_hash_tests {
use redis::Commands;
use std::collections::HashMap;
fn run() {
let mut r = match redis::Client::open("redis://127.0.0.1") {
Ok(client) => {
match client.get_connection() {
Ok(conn) => conn,
Err(e) => {
println!("Failed to connect to Redis: {e}");
return;
}
}
},
Err(e) => {
println!("Failed to create Redis client: {e}");
return;
}
};
// Clean up any existing data
let _: Result<i32, _> = r.del("myhash");
match r.hset("myhash", "field1", "foo") {
Ok(hdel1) => {
let hdel1: i32 = hdel1;
println!("{hdel1}"); // >>> 1
},
Err(e) => {
println!("Error setting hash field: {e}");
return;
}
}
match r.hget("myhash", "field1") {
Ok(hdel2) => {
let hdel2: Option<String> = hdel2;
match hdel2 {
Some(value) => {
println!("{value}"); // >>> foo
},
None => {
println!("None");
}
}
},
Err(e) => {
println!("Error getting hash field: {e}");
return;
}
}
match r.hget("myhash", "field2") {
Ok(hdel3) => {
let hdel3: Option<String> = hdel3;
match hdel3 {
Some(_) => {
println!("Some value");
},
None => {
println!("None"); // >>> None
}
}
},
Err(e) => {
println!("Error getting hash field: {e}");
return;
}
}
match r.hset("myhash", "field1", "Hello") {
Ok(res1) => {
let res1: i32 = res1;
println!("{res1}"); // >>> 1
},
Err(e) => {
println!("Error setting hash field: {e}");
return;
}
}
match r.hget("myhash", "field1") {
Ok(res2) => {
let res2: Option<String> = res2;
match res2 {
Some(value) => {
println!("{value}"); // >>> Hello
},
None => {
println!("None");
}
}
},
Err(e) => {
println!("Error getting hash field: {e}");
return;
}
}
// Set multiple fields using hset_multiple
let hash_fields = [
("field2", "Hi"),
("field3", "World"),
];
if let Ok(res) = r.hset_multiple("myhash", &hash_fields) {
let res: String = res;
println!("{res}"); // >>> OK
}
match r.hget("myhash", "field2") {
Ok(res4) => {
let res4: Option<String> = res4;
match res4 {
Some(value) => {
println!("{value}"); // >>> Hi
},
None => {
println!("None");
}
}
},
Err(e) => {
println!("Error getting hash field: {e}");
return;
}
}
match r.hget("myhash", "field3") {
Ok(res5) => {
let res5: Option<String> = res5;
match res5 {
Some(value) => {
println!("{value}"); // >>> World
},
None => {
println!("None");
}
}
},
Err(e) => {
println!("Error getting hash field: {e}");
return;
}
}
match r.hgetall("myhash") {
Ok(res6) => {
let res6: HashMap<String, String> = res6;
println!("{res6:?}"); // >>> {"field1": "Hello", "field2": "Hi", "field3": "World"}
},
Err(e) => {
println!("Error getting all hash fields: {e}");
return;
}
}
match r.hset("myhash", "field1", "foo") {
Ok(res7) => {
let res7: i32 = res7;
println!("{res7}"); // >>> 1
},
Err(e) => {
println!("Error setting hash field: {e}");
return;
}
}
match r.hget("myhash", "field1") {
Ok(res8) => {
let res8: Option<String> = res8;
match res8 {
Some(value) => {
println!("{value}"); // >>> foo
},
None => {
println!("None");
}
}
},
Err(e) => {
println!("Error getting hash field: {e}");
return;
}
}
match r.hget("myhash", "field2") {
Ok(res9) => {
let res9: Option<String> = res9;
match res9 {
Some(_) => {
println!("Some value");
},
None => {
println!("None"); // >>> None
}
}
},
Err(e) => {
println!("Error getting hash field: {e}");
return;
}
}
let hash_fields = [
("field1", "Hello"),
("field2", "World"),
];
if let Ok(_) = r.hset_multiple::<&str, &str, &str, String>("myhash", &hash_fields) {
// Fields set successfully
}
match r.hgetall("myhash") {
Ok(res11) => {
let res11: HashMap<String, String> = res11;
println!("{res11:?}"); // >>> {"field1": "Hello", "field2": "World"}
},
Err(e) => {
println!("Error getting all hash fields: {e}");
return;
}
}
let hash_fields = [
("field1", "Hello"),
("field2", "World"),
];
if let Ok(_) = r.hset_multiple::<&str, &str, &str, String>("myhash", &hash_fields) {
// Fields set successfully
}
match r.hvals("myhash") {
Ok(res11) => {
let res11: Vec<String> = res11;
println!("{res11:?}"); // >>> ["Hello", "World"]
},
Err(e) => {
println!("Error getting hash values: {e}");
return;
}
}
}
}
mod cmds_hash_tests {
use redis::AsyncCommands;
use std::collections::HashMap;
async fn run() {
let mut r = match redis::Client::open("redis://127.0.0.1") {
Ok(client) => {
match client.get_multiplexed_async_connection().await {
Ok(conn) => conn,
Err(e) => {
println!("Failed to connect to Redis: {e}");
return;
}
}
},
Err(e) => {
println!("Failed to create Redis client: {e}");
return;
}
};
// Clean up any existing data
let _: Result<i32, _> = r.del("myhash").await;
match r.hset("myhash", "field1", "foo").await {
Ok(hdel1) => {
let hdel1: i32 = hdel1;
println!("{hdel1}"); // >>> 1
},
Err(e) => {
println!("Error setting hash field: {e}");
return;
}
}
match r.hget("myhash", "field1").await {
Ok(hdel2) => {
let hdel2: Option<String> = hdel2;
match hdel2 {
Some(value) => {
println!("{value}"); // >>> foo
},
None => {
println!("None");
}
}
},
Err(e) => {
println!("Error getting hash field: {e}");
return;
}
}
match r.hget("myhash", "field2").await {
Ok(hdel3) => {
let hdel3: Option<String> = hdel3;
match hdel3 {
Some(_) => {
println!("Some value");
},
None => {
println!("None"); // >>> None
}
}
},
Err(e) => {
println!("Error getting hash field: {e}");
return;
}
}
match r.hset("myhash", "field1", "Hello").await {
Ok(res1) => {
let res1: i32 = res1;
println!("{res1}"); // >>> 1
},
Err(e) => {
println!("Error setting hash field: {e}");
return;
}
}
match r.hget("myhash", "field1").await {
Ok(res2) => {
let res2: Option<String> = res2;
match res2 {
Some(value) => {
println!("{value}"); // >>> Hello
},
None => {
println!("None");
}
}
},
Err(e) => {
println!("Error getting hash field: {e}");
return;
}
}
// Set multiple fields using hset_multiple
let hash_fields = [
("field2", "Hi"),
("field3", "World"),
];
if let Ok(res) = r.hset_multiple("myhash", &hash_fields).await {
let res: String = res;
println!("{res}"); // >>> OK
}
match r.hget("myhash", "field2").await {
Ok(res4) => {
let res4: Option<String> = res4;
match res4 {
Some(value) => {
println!("{value}"); // >>> Hi
},
None => {
println!("None");
}
}
},
Err(e) => {
println!("Error getting hash field: {e}");
return;
}
}
match r.hget("myhash", "field3").await {
Ok(res5) => {
let res5: Option<String> = res5;
match res5 {
Some(value) => {
println!("{value}"); // >>> World
},
None => {
println!("None");
}
}
},
Err(e) => {
println!("Error getting hash field: {e}");
return;
}
}
match r.hgetall("myhash").await {
Ok(res6) => {
let res6: HashMap<String, String> = res6;
println!("{res6:?}"); // >>> {"field1": "Hello", "field2": "Hi", "field3": "World"}
},
Err(e) => {
println!("Error getting all hash fields: {e}");
return;
}
}
match r.hset("myhash", "field1", "foo").await {
Ok(res7) => {
let res7: i32 = res7;
println!("{res7}"); // >>> 1
},
Err(e) => {
println!("Error setting hash field: {e}");
return;
}
}
match r.hget("myhash", "field1").await {
Ok(res8) => {
let res8: Option<String> = res8;
match res8 {
Some(value) => {
println!("{value}"); // >>> foo
},
None => {
println!("None");
}
}
},
Err(e) => {
println!("Error getting hash field: {e}");
return;
}
}
match r.hget("myhash", "field2").await {
Ok(res9) => {
let res9: Option<String> = res9;
match res9 {
Some(_) => {
println!("Some value");
},
None => {
println!("None"); // >>> None
}
}
},
Err(e) => {
println!("Error getting hash field: {e}");
return;
}
}
let hash_fields = [
("field1", "Hello"),
("field2", "World"),
];
if let Ok(_) = r.hset_multiple::<&str, &str, &str, String>("myhash", &hash_fields).await {
// Fields set successfully
}
match r.hgetall("myhash").await {
Ok(res11) => {
let res11: HashMap<String, String> = res11;
println!("{res11:?}"); // >>> {"field1": "Hello", "field2": "World"}
},
Err(e) => {
println!("Error getting all hash fields: {e}");
return;
}
}
let hash_fields = [
("field1", "Hello"),
("field2", "World"),
];
if let Ok(_) = r.hset_multiple::<&str, &str, &str, String>("myhash", &hash_fields).await {
// Fields set successfully
}
match r.hvals("myhash").await {
Ok(res11) => {
let res11: Vec<String> = res11;
println!("{res11:?}"); // >>> ["Hello", "World"]
},
Err(e) => {
println!("Error getting hash values: {e}");
return;
}
}
}
}
Give these commands a try in the interactive console:
Return information
Array reply: a list of fields and their values, or an empty list when key does not exist.