diff --git a/content/commands/hdel.md b/content/commands/hdel.md index 9b0703f98..4acc356fd 100644 --- a/content/commands/hdel.md +++ b/content/commands/hdel.md @@ -63,6 +63,17 @@ If `key` does not exist, it is treated as an empty hash and this command returns ## Examples +{{< clients-example set="cmds_hash" step="hdel" >}} +HSET myhash field1 "foo" +(integer) 1 +HDEL myhash field1 +(integer) 1 +HDEL myhash field2 +(integer) 0 +{{< /clients-example >}} + +Give these commands a try in the interactive console: + {{% redis-cli %}} HSET myhash field1 "foo" HDEL myhash field1 diff --git a/local_examples/cmds_hash/NRedisStack/CmdsHashExample.cs b/local_examples/cmds_hash/NRedisStack/CmdsHashExample.cs new file mode 100644 index 000000000..038c5b5b0 --- /dev/null +++ b/local_examples/cmds_hash/NRedisStack/CmdsHashExample.cs @@ -0,0 +1,114 @@ +// EXAMPLE: cmds_hash +using StackExchange.Redis; +using Xunit; + +namespace Doc; + +public class CmdsHashExample +{ + [Fact] + 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"); + + // STEP_START hdel + 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 + + // STEP_END + Assert.True(hdelRes1); + Assert.Equal(1, hdelRes2); + Assert.Equal(0, hdelRes3); + db.KeyDelete("myhash"); + + // STEP_START hget + 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 + + // STEP_END + Assert.True(hgetRes1); + Assert.Equal("foo", hgetRes2); + Assert.Equal(RedisValue.Null, hgetRes3); + db.KeyDelete("myhash"); + + // STEP_START hset + 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 + + // STEP_END + 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"); + + // STEP_START hgetall + 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 + // STEP_END + Assert.Equal("field1: Hello, field2: World", string.Join(", ", hGetAllResult.Select(e => $"{e.Name}: {e.Value}"))); + db.KeyDelete("myhash"); + + // STEP_START hvals + db.HashSet("myhash", + [ + new("field1", "Hello"), + new("field2", "World") + ] + ); + + RedisValue[] hValsResult = db.HashValues("myhash"); + Array.Sort(hValsResult); + Console.WriteLine(string.Join(", ", hValsResult)); + // >>> Hello, World + // STEP_END + Assert.Equal("Hello, World", string.Join(", ", hValsResult)); + } +} diff --git a/local_examples/cmds_hash/go-redis/cmds_hash_test.go b/local_examples/cmds_hash/go-redis/cmds_hash_test.go new file mode 100644 index 000000000..8dcd85d81 --- /dev/null +++ b/local_examples/cmds_hash/go-redis/cmds_hash_test.go @@ -0,0 +1,296 @@ +// EXAMPLE: cmds_hash +// HIDE_START +package example_commands_test + +import ( + "context" + "fmt" + "sort" + + "github.com/redis/go-redis/v9" +) + +// HIDE_END + +func ExampleClient_hset() { + ctx := context.Background() + + rdb := redis.NewClient(&redis.Options{ + Addr: "localhost:6379", + Password: "", // no password docs + DB: 0, // use default DB + }) + + // REMOVE_START + // make sure we are working with fresh database + rdb.FlushDB(ctx) + rdb.Del(ctx, "myhash") + // REMOVE_END + + // STEP_START hset + 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 + // STEP_END + + // Output: + // 1 + // Hello + // 2 + // Hi + // World + // 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 + }) + + // REMOVE_START + // start with fresh database + rdb.FlushDB(ctx) + rdb.Del(ctx, "myhash") + // REMOVE_END + + // STEP_START hget + 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) // >>> + // STEP_END + + // Output: + // 1 + // foo + // redis: nil +} + +func ExampleClient_hgetall() { + ctx := context.Background() + + rdb := redis.NewClient(&redis.Options{ + Addr: "localhost:6379", + Password: "", // no password + DB: 0, // use default DB + }) + + // REMOVE_START + // start with fresh database + rdb.FlushDB(ctx) + rdb.Del(ctx, "myhash") + // REMOVE_END + + // STEP_START hgetall + 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 + // STEP_END + + // Output: + // 2 + // 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 + }) + + // REMOVE_START + // start with fresh database + rdb.FlushDB(ctx) + rdb.Del(ctx, "myhash") + // REMOVE_END + + // STEP_START hvals + 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] + // STEP_END + + // Output: + // 2 + // [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 + }) + + // REMOVE_START + // start with fresh database + rdb.FlushDB(ctx) + rdb.Del(ctx, "myhash") + // REMOVE_END + + // STEP_START hdel + 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 + // STEP_END + + // Output: + // 1 + // 1 + // 0 +} \ No newline at end of file diff --git a/local_examples/cmds_hash/jedis/CmdsHashExample.java b/local_examples/cmds_hash/jedis/CmdsHashExample.java new file mode 100644 index 000000000..3124a26d7 --- /dev/null +++ b/local_examples/cmds_hash/jedis/CmdsHashExample.java @@ -0,0 +1,174 @@ +// EXAMPLE: cmds_hash +// REMOVE_START +package io.redis.examples; + +import org.junit.jupiter.api.Test; +// REMOVE_END + +import java.util.HashMap; +import java.util.Map; +import java.util.List; +import java.util.Collections; + +// HIDE_START +import redis.clients.jedis.UnifiedJedis; +// HIDE_END + +import static java.util.stream.Collectors.toList; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +// HIDE_START +public class CmdsHashExample { + + @Test + public void run() { + UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379"); + + //REMOVE_START + // Clear any keys here before using them in tests. + jedis.del("myhash"); + //REMOVE_END +// HIDE_END + + // STEP_START hdel + Map 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 + // STEP_END + // REMOVE_START + // Tests for 'hdel' step. + assertEquals(1, hDelResult1); + assertEquals(1L, hDelResult2); + assertEquals(0L, hDelResult3); + jedis.del("myhash"); + // REMOVE_END + + // STEP_START hget + Map 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 + // STEP_END + // REMOVE_START + // Tests for 'hget' step. + assertEquals(1, hGetResult1); + assertEquals("foo", hGetResult2); + assertNull(hGetResult3); + jedis.del("myhash"); + // REMOVE_END + + // STEP_START hgetall + Map hGetAllExampleParams = new HashMap<>(); + hGetAllExampleParams.put("field1", "Hello"); + hGetAllExampleParams.put("field2", "World"); + + long hGetAllResult1 = jedis.hset("myhash", hGetAllExampleParams); + System.out.println(hGetAllResult1); // >>> 2 + + Map 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] + // STEP_END + // REMOVE_START + // Tests for 'hgetall' step. + assertEquals(2, hGetAllResult1); + assertEquals("[field1=Hello, field2=World]", + hGetAllResult2.entrySet().stream() + .sorted((s1, s2)-> s1.getKey().compareTo(s2.getKey())) + .collect(toList()) + .toString() + ); + jedis.del("myhash"); + // REMOVE_END + + // STEP_START hset + Map 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 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 + // STEP_END + // REMOVE_START + // Tests for 'hset' step. + assertEquals(1, hSetResult1); + assertEquals("Hello", hSetResult2); + assertEquals(2, hSetResult3); + assertEquals("Hi", hSetResult4); + assertEquals("World", hSetResult5); + assertEquals(3, hSetResult6.size()); + assertEquals("Hello", hSetResult6.get("field1")); + assertEquals("Hi", hSetResult6.get("field2")); + assertEquals("World", hSetResult6.get("field3")); + jedis.del("myhash"); + // REMOVE_END + + // STEP_START hvals + Map hValsExampleParams = new HashMap<>(); + hValsExampleParams.put("field1", "Hello"); + hValsExampleParams.put("field2", "World"); + + long hValsResult1 = jedis.hset("myhash", hValsExampleParams); + System.out.println(hValsResult1); // >>> 2 + + List hValsResult2 = jedis.hvals("myhash"); + Collections.sort(hValsResult2); + System.out.println(hValsResult2); + // >>> [Hello, World] + // STEP_END + // REMOVE_START + // Tests for 'hvals' step. + assertEquals(2, hValsResult1); + assertEquals("[Hello, World]", hValsResult2.toString()); + jedis.del("myhash"); + // REMOVE_END + +// HIDE_START + jedis.close(); + } +} +// HIDE_END + diff --git a/local_examples/cmds_hash/lettuce-async/CmdsHashExample.java b/local_examples/cmds_hash/lettuce-async/CmdsHashExample.java new file mode 100644 index 000000000..ea580b190 --- /dev/null +++ b/local_examples/cmds_hash/lettuce-async/CmdsHashExample.java @@ -0,0 +1,193 @@ +// EXAMPLE: cmds_hash +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; +// REMOVE_START +import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; +// REMOVE_END + +public class CmdsHashExample { + + // REMOVE_START + @Test + // REMOVE_END + public void run() { + // REMOVE_START + RedisClient redisClient = RedisClient.create("redis://localhost:6379"); + + try (StatefulRedisConnection connection = redisClient.connect()) { + RedisAsyncCommands asyncCommands = connection.async(); + asyncCommands.del("myhash").toCompletableFuture().join(); + // REMOVE_END + + // STEP_START hdel + Map hDelExampleParams = new HashMap<>(); + hDelExampleParams.put("field1", "foo"); + + CompletableFuture hDelExample = asyncCommands.hset("myhash", hDelExampleParams).thenCompose(res1 -> { + System.out.println(res1); // >>> 1 + // REMOVE_START + assertThat(res1).isEqualTo(1L); + // REMOVE_END + return asyncCommands.hdel("myhash", "field1"); + }).thenCompose(res2 -> { + System.out.println(res2); // >>> 1 + // REMOVE_START + assertThat(res2).isEqualTo(1L); + // REMOVE_END + return asyncCommands.hdel("myhash", "field2"); + }).thenAccept(res3 -> { + System.out.println(res3); // >>> 0 + // REMOVE_START + assertThat(res3).isEqualTo(0L); + // REMOVE_END + }).toCompletableFuture(); + // STEP_END + + hDelExample.join(); + // REMOVE_START + asyncCommands.del("myhash").toCompletableFuture().join(); + // REMOVE_END + + // STEP_START hset + CompletableFuture hSetExample = asyncCommands.hset("myhash", "field1", "Hello").thenCompose(res1 -> { + System.out.println(res1); // >>> 1 + // REMOVE_START + assertThat(res1).isEqualTo(true); + // REMOVE_END + return asyncCommands.hget("myhash", "field1"); + }).thenCompose(res2 -> { + System.out.println(res2); // >>> Hello + // REMOVE_START + assertThat(res2).isEqualTo("Hello"); + // REMOVE_END + Map hSetExampleParams = new HashMap<>(); + hSetExampleParams.put("field2", "Hi"); + hSetExampleParams.put("field3", "World"); + return asyncCommands.hset("myhash", hSetExampleParams); + }).thenCompose(res3 -> { + System.out.println(res3); // >>> 2 + // REMOVE_START + assertThat(res3).isEqualTo(2L); + // REMOVE_END + return asyncCommands.hget("myhash", "field2"); + }).thenCompose(res4 -> { + System.out.println(res4); // >>> Hi + // REMOVE_START + assertThat(res4).isEqualTo("Hi"); + // REMOVE_END + return asyncCommands.hget("myhash", "field3"); + }).thenCompose(res5 -> { + System.out.println(res5); // >>> World + // REMOVE_START + assertThat(res5).isEqualTo("World"); + // REMOVE_END + return asyncCommands.hgetall("myhash"); + }).thenAccept(res6 -> { + System.out.println(res6); + // >>> {field1=Hello, field2=Hi, field3=World} + // REMOVE_START + assertThat(res6.get("field1")).isEqualTo("Hello"); + assertThat(res6.get("field2")).isEqualTo("Hi"); + assertThat(res6.get("field3")).isEqualTo("World"); + // REMOVE_END + }).toCompletableFuture(); + // STEP_END + + hSetExample.join(); + // REMOVE_START + asyncCommands.del("myhash").toCompletableFuture().join(); + // REMOVE_END + + // STEP_START hget + Map hGetExampleParams = new HashMap<>(); + hGetExampleParams.put("field1", "foo"); + + CompletableFuture hGetExample = asyncCommands.hset("myhash", hGetExampleParams).thenCompose(res1 -> { + System.out.println(res1); // >>> 1 + // REMOVE_START + assertThat(res1).isEqualTo(1L); + // REMOVE_END + return asyncCommands.hget("myhash", "field1"); + }).thenCompose(res2 -> { + System.out.println(res2); // >>> foo + // REMOVE_START + assertThat(res2).isEqualTo("foo"); + // REMOVE_END + return asyncCommands.hget("myhash", "field2"); + }).thenAccept(res3 -> { + System.out.println(res3); // >>> null + // REMOVE_START + assertThat(res3).isNull(); + // REMOVE_END + }).toCompletableFuture(); + // STEP_END + + hGetExample.join(); + // REMOVE_START + asyncCommands.del("myhash").toCompletableFuture().join(); + // REMOVE_END + + // STEP_START hgetall + Map hGetAllExampleParams = new HashMap<>(); + hGetAllExampleParams.put("field1", "Hello"); + hGetAllExampleParams.put("field2", "World"); + + CompletableFuture hGetAllExample = asyncCommands.hset("myhash", hGetAllExampleParams).thenCompose(res1 -> { + // REMOVE_START + assertThat(res1).isEqualTo(2L); + // REMOVE_END + return asyncCommands.hgetall("myhash"); + }).thenAccept(res2 -> { + System.out.println(res2); + // >>> {field1=Hello, field2=World} + // REMOVE_START + assertThat(res2.get("field1")).isEqualTo("Hello"); + assertThat(res2.get("field2")).isEqualTo("World"); + // REMOVE_END + }).toCompletableFuture(); + // STEP_END + + hGetAllExample.join(); + // REMOVE_START + asyncCommands.del("myhash").toCompletableFuture().join(); + // REMOVE_END + + // STEP_START hvals + Map hValsExampleParams = new HashMap<>(); + hValsExampleParams.put("field1", "Hello"); + hValsExampleParams.put("field2", "World"); + + CompletableFuture hValsExample = asyncCommands.hset("myhash", hValsExampleParams).thenCompose(res1 -> { + // REMOVE_START + assertThat(res1).isEqualTo(2L); + // REMOVE_END + return asyncCommands.hvals("myhash"); + }).thenAccept(res2 -> { + List sortedValues = new ArrayList<>(res2); + Collections.sort(sortedValues); + System.out.println(sortedValues); + // >>> [Hello, World] + // REMOVE_START + assertThat(sortedValues).containsExactly("Hello", "World"); + // REMOVE_END + }).toCompletableFuture(); + // STEP_END + + hValsExample.join(); + // REMOVE_START + asyncCommands.del("myhash").toCompletableFuture().join(); + // REMOVE_END + } finally { + redisClient.shutdown(); + } + } + +} + diff --git a/local_examples/cmds_hash/lettuce-reactive/CmdsHashExample.java b/local_examples/cmds_hash/lettuce-reactive/CmdsHashExample.java new file mode 100644 index 000000000..c42580283 --- /dev/null +++ b/local_examples/cmds_hash/lettuce-reactive/CmdsHashExample.java @@ -0,0 +1,232 @@ +// EXAMPLE: cmds_hash +package io.redis.examples.reactive; + +import io.lettuce.core.*; +import io.lettuce.core.api.reactive.RedisReactiveCommands; +import io.lettuce.core.api.StatefulRedisConnection; +// REMOVE_START +import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; +// REMOVE_END + +import reactor.core.publisher.Mono; + +import java.util.*; + +public class CmdsHashExample { + + // REMOVE_START + @Test + // REMOVE_END + public void run() { + RedisClient redisClient = RedisClient.create("redis://localhost:6379"); + + try (StatefulRedisConnection connection = redisClient.connect()) { + RedisReactiveCommands reactiveCommands = connection.reactive(); + // REMOVE_START + // Clean up any existing data + reactiveCommands.del("myhash").block(); + // REMOVE_END + + // STEP_START hdel + Map hDelExampleParams = new HashMap<>(); + hDelExampleParams.put("field1", "foo"); + + Mono hDelExample1 = reactiveCommands.hset("myhash", hDelExampleParams).doOnNext(result -> { + System.out.println(result); // >>> 1 + // REMOVE_START + assertThat(result).isEqualTo(1L); + // REMOVE_END + }); + + hDelExample1.block(); + + Mono hDelExample2 = reactiveCommands.hdel("myhash", "field1").doOnNext(result -> { + System.out.println(result); // >>> 1 + // REMOVE_START + assertThat(result).isEqualTo(1L); + // REMOVE_END + }); + + hDelExample2.block(); + + Mono hDelExample3 = reactiveCommands.hdel("myhash", "field2").doOnNext(result -> { + System.out.println(result); // >>> 0 + // REMOVE_START + assertThat(result).isEqualTo(0L); + // REMOVE_END + }); + // STEP_END + + hDelExample3.block(); + // REMOVE_START + reactiveCommands.del("myhash").block(); + // REMOVE_END + + // STEP_START hset + Mono hSetExample1 = reactiveCommands.hset("myhash", "field1", "Hello").doOnNext(result -> { + System.out.println(result); // >>> True + // REMOVE_START + assertThat(result).isEqualTo(true); + // REMOVE_END + }); + + hSetExample1.block(); + + Mono hSetExample2 = reactiveCommands.hget("myhash", "field1").doOnNext(result -> { + System.out.println(result); // >>> Hello + // REMOVE_START + assertThat(result).isEqualTo("Hello"); + // REMOVE_END + }); + + hSetExample2.block(); + + Map hSetExampleParams = new HashMap<>(); + hSetExampleParams.put("field2", "Hi"); + hSetExampleParams.put("field3", "World"); + + Mono hSetExample3 = reactiveCommands.hset("myhash", hSetExampleParams).doOnNext(result -> { + System.out.println(result); // >>> 2 + // REMOVE_START + assertThat(result).isEqualTo(2L); + // REMOVE_END + }); + + hSetExample3.block(); + + Mono hSetExample4 = reactiveCommands.hget("myhash", "field2").doOnNext(result -> { + System.out.println(result); // >>> Hi + // REMOVE_START + assertThat(result).isEqualTo("Hi"); + // REMOVE_END + }); + + hSetExample4.block(); + + Mono hSetExample5 = reactiveCommands.hget("myhash", "field3").doOnNext(result -> { + System.out.println(result); // >>> World + // REMOVE_START + assertThat(result).isEqualTo("World"); + // REMOVE_END + }); + + hSetExample5.block(); + + Mono> hSetExample6 = reactiveCommands.hgetall("myhash").collectMap( + KeyValue::getKey, KeyValue::getValue + ).doOnNext(result -> { + System.out.println(result); + // >>> {field1=Hello, field2=Hi, field3=World} + // REMOVE_START + assertThat(result.get("field1")).isEqualTo("Hello"); + assertThat(result.get("field2")).isEqualTo("Hi"); + assertThat(result.get("field3")).isEqualTo("World"); + // REMOVE_END + }); + // STEP_END + + hSetExample6.block(); + // REMOVE_START + reactiveCommands.del("myhash").block(); + // REMOVE_END + + // STEP_START hget + Map hGetExampleParams = new HashMap<>(); + hGetExampleParams.put("field1", "foo"); + + Mono hGetExample1 = reactiveCommands.hset("myhash", hGetExampleParams).doOnNext(result -> { + System.out.println(result); // >>> 1 + // REMOVE_START + assertThat(result).isEqualTo(1L); + // REMOVE_END + }); + + hGetExample1.block(); + + Mono hGetExample2 = reactiveCommands.hget("myhash", "field1").doOnNext(result -> { + System.out.println(result); // >>> foo + // REMOVE_START + assertThat(result).isEqualTo("foo"); + // REMOVE_END + }); + + hGetExample2.block(); + + Mono hGetExample3 = reactiveCommands.hget("myhash", "field2").doOnNext(result -> { + System.out.println(result); // >>> null + // REMOVE_START + assertThat(result).isNull(); + // REMOVE_END + }); + // STEP_END + + hGetExample3.block(); + // REMOVE_START + reactiveCommands.del("myhash").block(); + // REMOVE_END + + // STEP_START hgetall + Map hGetAllExampleParams = new HashMap<>(); + hGetAllExampleParams.put("field1", "Hello"); + hGetAllExampleParams.put("field2", "World"); + + Mono hGetAllExample1 = reactiveCommands.hset("myhash", hGetAllExampleParams).doOnNext(result -> { + // REMOVE_START + assertThat(result).isEqualTo(2L); + // REMOVE_END + }); + + hGetAllExample1.block(); + + Mono> hGetAllExample2 = reactiveCommands.hgetall("myhash").collectMap( + KeyValue::getKey, KeyValue::getValue + ).doOnNext(result -> { + System.out.println(result); + // >>> {field1=Hello, field2=World} + // REMOVE_START + assertThat(result.get("field1")).isEqualTo("Hello"); + assertThat(result.get("field2")).isEqualTo("World"); + // REMOVE_END + }); + // STEP_END + + hGetAllExample2.block(); + // REMOVE_START + reactiveCommands.del("myhash").block(); + // REMOVE_END + + // STEP_START hvals + Map hValsExampleParams = new HashMap<>(); + hValsExampleParams.put("field1", "Hello"); + hValsExampleParams.put("field2", "World"); + + Mono hValsExample1 = reactiveCommands.hset("myhash", hValsExampleParams).doOnNext(result -> { + // REMOVE_START + assertThat(result).isEqualTo(2L); + // REMOVE_END + }); + + hValsExample1.block(); + + Mono> hValsExample2 = reactiveCommands.hvals("myhash").collectList().doOnNext(result -> { + List sortedValues = new ArrayList<>(result); + Collections.sort(sortedValues); + System.out.println(sortedValues); + // >>> [Hello, World] + // REMOVE_START + assertThat(sortedValues).containsExactly("Hello", "World"); + // REMOVE_END + }); + // STEP_END + + hValsExample2.block(); + // REMOVE_START + reactiveCommands.del("myhash").block(); + // REMOVE_END + } finally { + redisClient.shutdown(); + } + } + +} diff --git a/local_examples/cmds_hash/node-redis/cmds-hash.js b/local_examples/cmds_hash/node-redis/cmds-hash.js new file mode 100644 index 000000000..e48eaad6b --- /dev/null +++ b/local_examples/cmds_hash/node-redis/cmds-hash.js @@ -0,0 +1,127 @@ +// EXAMPLE: cmds_hash +// HIDE_START +import assert from 'node:assert'; +import { createClient } from 'redis'; + +const client = createClient(); +await client.connect().catch(console.error); +// HIDE_END + +// STEP_START hdel +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 + +// REMOVE_START +assert.equal(hDel1, 1); +assert.equal(hDel2, 1); +assert.equal(hDel3, 0); +await client.del('myhash') +// REMOVE_END +// STEP_END + +// STEP_START hset +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) + +// REMOVE_START +assert.equal(res1, 1); +assert.equal(res2, 'Hello'); +assert.equal(res3, 2); +assert.equal(res4, 'Hi'); +assert.equal(res5, 'World'); +assert.deepEqual(res6, { + field1: 'Hello', + field2: 'Hi', + field3: 'World' +}); +await client.del('myhash') +// REMOVE_END +// STEP_END + +// STEP_START hget +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 + +// REMOVE_START +assert.equal(res7, 1); +assert.equal(res8, 'foo'); +assert.equal(res9, null); +await client.del('myhash') +// REMOVE_END +// STEP_END + +// STEP_START hgetall +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' } + +// REMOVE_START +assert.deepEqual(res11, { + field1: 'Hello', + field2: 'World' +}); +await client.del('myhash') +// REMOVE_END +// STEP_END + +// STEP_START hvals +const res12 = await client.hSet( + 'myhash', + { + 'field1': 'Hello', + 'field2': 'World' + } +) + +const res13 = await client.hVals('myhash') +console.log(res13) // [ 'Hello', 'World' ] + +// REMOVE_START +assert.deepEqual(res13, [ 'Hello', 'World' ]); +await client.del('myhash') +// REMOVE_END +// STEP_END + +// HIDE_START +await client.close(); +// HIDE_END diff --git a/local_examples/cmds_hash/predis/CmdsHashTest.php b/local_examples/cmds_hash/predis/CmdsHashTest.php new file mode 100644 index 000000000..1772579f6 --- /dev/null +++ b/local_examples/cmds_hash/predis/CmdsHashTest.php @@ -0,0 +1,134 @@ +// EXAMPLE: cmds_hash +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"; + + // STEP_START hdel + 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 + // STEP_END + + $this->assertEquals(1, $hDelResult1); + $this->assertEquals(1, $hDelResult2); + $this->assertEquals(0, $hDelResult3); + + // STEP_START hget + 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 + // STEP_END + + $this->assertEquals(1, $hGetResult1); + $this->assertEquals('foo', $hGetResult2); + $this->assertNull($hGetResult3); + + // STEP_START hgetall + 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"} + // STEP_END + + $this->assertEquals('OK', $hGetAllResult1); + $this->assertEquals(['field1' => 'Hello', 'field2' => 'World'], $hGetAllResult2); + + // STEP_START hset + 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"; + // STEP_END + + $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); + + // STEP_START hvals + 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"] + // STEP_END + + $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(); + } +} diff --git a/local_examples/cmds_hash/redis-py/cmds_hash.py b/local_examples/cmds_hash/redis-py/cmds_hash.py new file mode 100644 index 000000000..fd876b719 --- /dev/null +++ b/local_examples/cmds_hash/redis-py/cmds_hash.py @@ -0,0 +1,108 @@ +# EXAMPLE: cmds_hash +# HIDE_START +import redis + +r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True) +# HIDE_END + +# STEP_START hdel +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 + +# REMOVE_START +assert hdel1 == 1 +assert hdel2 == "foo" +assert hdel3 == None +r.delete("myhash") +# REMOVE_END +# STEP_END + +# STEP_START hset +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" } + +# REMOVE_START +assert res1 == 1 +assert res2 == "Hello" +assert res3 == 2 +assert res4 == "Hi" +assert res5 == "World" +assert res6 == { "field1": "Hello", "field2": "Hi", "field3": "World" } +r.delete("myhash") +# REMOVE_END +# STEP_END + +# STEP_START hget +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 + +# REMOVE_START +assert res7 == 1 +assert res8 == "foo" +assert res9 == None +r.delete("myhash") +# REMOVE_END +# STEP_END + +# STEP_START hgetall +res10 = r.hset("myhash", mapping={"field1": "Hello", "field2": "World"}) + +res11 = r.hgetall("myhash") +print(res11) # >>> { "field1": "Hello", "field2": "World" } + +# REMOVE_START +assert res11 == { "field1": "Hello", "field2": "World" } +r.delete("myhash") +# REMOVE_END +# STEP_END + +# STEP_START hvals +res10 = r.hset("myhash", mapping={"field1": "Hello", "field2": "World"}) + +res11 = r.hvals("myhash") +print(res11) # >>> [ "Hello", "World" ] + +# REMOVE_START +assert res11 == [ "Hello", "World" ] +r.delete("myhash") +# REMOVE_END +# STEP_END \ No newline at end of file