[フレーム]
Docs Pricing
Login Book a meeting Try Redis

HSET

Syntax
HSET key field value [field value ...]
Available since:
Redis Open Source 2.0.0
Time complexity:
O(1) for each field/value pair added, so O(N) to add N field/value pairs when the command is called with multiple field/value pairs.
ACL categories:
@write, @hash, @fast,
Compatibility:
Redis Enterprise and Redis Cloud compatibility

Sets the specified fields to their respective values in the hash stored at key.

This command overwrites the values of specified fields that exist in the hash. If key doesn't exist, a new key holding a hash is created.

Examples

> HSET myhash field1 "Hello"
(integer) 1
> HGET myhash field1
"Hello"
> HSET myhash field2 "Hi" field3 "World"
(integer) 2
> HGET myhash field2
"Hi"
> HGET myhash field3
"World"
> HGETALL myhash
1) "field1"
2) "Hello"
3) "field2"
4) "Hi"
5) "field3"
6) "World"
Are you tired of using redis-cli? Try Redis Insight - the developer GUI for Redis.
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" ]
# Set up hash with fields
r.hset("myhash", mapping={"field1": "Hello", "field2": "World"})
# Set expiration on hash fields
res12 = r.hexpire("myhash", 10, "field1", "field2")
print(res12) # >>> [1, 1]
# Check TTL of the fields
res13 = r.httl("myhash", "field1", "field2")
print(res13) # >>> [10, 10] (or close to 10)
# Try to set expiration on non-existent field
res14 = r.hexpire("myhash", 10, "nonexistent")
print(res14) # >>> [-2]
Python Quick-Start
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' ]

// Set up hash with fields
await client.hSet('myhash', {
 'field1': 'Hello',
 'field2': 'World'
})
// Set expiration on hash fields
const res14 = await client.hExpire('myhash', ['field1', 'field2'], 10)
console.log(res14) // [1, 1]

// Check TTL of the fields
const res15 = await client.hTTL('myhash', ['field1', 'field2'])
console.log(res15) // [10, 10] (or close to 10)

// Try to set expiration on non-existent field
const res16 = await client.hExpire('myhash', ['nonexistent'], 10)
console.log(res16) // [-2]

await client.close();
Node.js Quick-Start
importjava.util.HashMap;importjava.util.Map;importjava.util.List;importjava.util.Collections;importjava.util.Arrays;importredis.clients.jedis.UnifiedJedis;import staticjava.util.stream.Collectors.toList;import staticorg.junit.jupiter.api.Assertions.assertEquals;import staticorg.junit.jupiter.api.Assertions.assertNull;import staticorg.junit.jupiter.api.Assertions.assertTrue;publicclass CmdsHashExample{publicvoidrun(){UnifiedJedisjedis=newUnifiedJedis("redis://localhost:6379");Map<String,String>hDelExampleParams=newHashMap<>();hDelExampleParams.put("field1","foo");longhDelResult1=jedis.hset("myhash",hDelExampleParams);System.out.println(hDelResult1);// >>> 1longhDelResult2=jedis.hdel("myhash","field1");System.out.println(hDelResult2);// >>> 1longhDelResult3=jedis.hdel("myhash","field2");System.out.println(hDelResult3);// >>> 0Map<String,String>hGetExampleParams=newHashMap<>();hGetExampleParams.put("field1","foo");longhGetResult1=jedis.hset("myhash",hGetExampleParams);System.out.println(hGetResult1);// >>> 1StringhGetResult2=jedis.hget("myhash","field1");System.out.println(hGetResult2);// >>> fooStringhGetResult3=jedis.hget("myhash","field2");System.out.println(hGetResult3);// >>> nullMap<String,String>hGetAllExampleParams=newHashMap<>();hGetAllExampleParams.put("field1","Hello");hGetAllExampleParams.put("field2","World");longhGetAllResult1=jedis.hset("myhash",hGetAllExampleParams);System.out.println(hGetAllResult1);// >>> 2Map<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=newHashMap<>();hSetExampleParams.put("field1","Hello");longhSetResult1=jedis.hset("myhash",hSetExampleParams);System.out.println(hSetResult1);// >>> 1StringhSetResult2=jedis.hget("myhash","field1");System.out.println(hSetResult2);// >>> HellohSetExampleParams.clear();hSetExampleParams.put("field2","Hi");hSetExampleParams.put("field3","World");longhSetResult3=jedis.hset("myhash",hSetExampleParams);System.out.println(hSetResult3);// >>> 2StringhSetResult4=jedis.hget("myhash","field2");System.out.println(hSetResult4);// >>> HiStringhSetResult5=jedis.hget("myhash","field3");System.out.println(hSetResult5);// >>> WorldMap<String,String>hSetResult6=jedis.hgetAll("myhash");for(Stringkey:hSetResult6.keySet()){System.out.println("Key: "+key+", Value: "+hSetResult6.get(key));}// >>> Key: field3, Value: World// >>> Key: field2, Value: Hi// >>> Key: field1, Value: HelloMap<String,String>hValsExampleParams=newHashMap<>();hValsExampleParams.put("field1","Hello");hValsExampleParams.put("field2","World");longhValsResult1=jedis.hset("myhash",hValsExampleParams);System.out.println(hValsResult1);// >>> 2List<String>hValsResult2=jedis.hvals("myhash");Collections.sort(hValsResult2);System.out.println(hValsResult2);// >>> [Hello, World]// Set up hash with fieldsMap<String,String>hExpireExampleParams=newHashMap<>();hExpireExampleParams.put("field1","Hello");hExpireExampleParams.put("field2","World");jedis.hset("myhash",hExpireExampleParams);// Set expiration on hash fieldsList<Long>hExpireResult1=jedis.hexpire("myhash",10,"field1","field2");System.out.println(hExpireResult1);// >>> [1, 1]// Check TTL of the fieldsList<Long>hExpireResult2=jedis.httl("myhash","field1","field2");System.out.println(hExpireResult2.size());// >>> 2// Try to set expiration on non-existent fieldList<Long>hExpireResult3=jedis.hexpire("myhash",10,"nonexistent");System.out.println(hExpireResult3);// >>> [-2]jedis.close();}}
Java-Sync Quick-Start
packageio.redis.examples.async;importio.lettuce.core.*;importio.lettuce.core.api.async.RedisAsyncCommands;importio.lettuce.core.api.StatefulRedisConnection;importjava.util.*;importjava.util.concurrent.CompletableFuture;publicclass CmdsHashExample{publicvoidrun(){Map<String,String>hDelExampleParams=newHashMap<>();hDelExampleParams.put("field1","foo");CompletableFuture<Void>hDelExample=asyncCommands.hset("myhash",hDelExampleParams).thenCompose(res1->{System.out.println(res1);// >>> 1returnasyncCommands.hdel("myhash","field1");}).thenCompose(res2->{System.out.println(res2);// >>> 1returnasyncCommands.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);// >>> 1returnasyncCommands.hget("myhash","field1");}).thenCompose(res2->{System.out.println(res2);// >>> HelloMap<String,String>hSetExampleParams=newHashMap<>();hSetExampleParams.put("field2","Hi");hSetExampleParams.put("field3","World");returnasyncCommands.hset("myhash",hSetExampleParams);}).thenCompose(res3->{System.out.println(res3);// >>> 2returnasyncCommands.hget("myhash","field2");}).thenCompose(res4->{System.out.println(res4);// >>> HireturnasyncCommands.hget("myhash","field3");}).thenCompose(res5->{System.out.println(res5);// >>> WorldreturnasyncCommands.hgetall("myhash");}).thenAccept(res6->{System.out.println(res6);// >>> {field1=Hello, field2=Hi, field3=World}}).toCompletableFuture();hSetExample.join();Map<String,String>hGetExampleParams=newHashMap<>();hGetExampleParams.put("field1","foo");CompletableFuture<Void>hGetExample=asyncCommands.hset("myhash",hGetExampleParams).thenCompose(res1->{System.out.println(res1);// >>> 1returnasyncCommands.hget("myhash","field1");}).thenCompose(res2->{System.out.println(res2);// >>> fooreturnasyncCommands.hget("myhash","field2");}).thenAccept(res3->{System.out.println(res3);// >>> null}).toCompletableFuture();hGetExample.join();Map<String,String>hGetAllExampleParams=newHashMap<>();hGetAllExampleParams.put("field1","Hello");hGetAllExampleParams.put("field2","World");CompletableFuture<Void>hGetAllExample=asyncCommands.hset("myhash",hGetAllExampleParams).thenCompose(res1->{returnasyncCommands.hgetall("myhash");}).thenAccept(res2->{System.out.println(res2);// >>> {field1=Hello, field2=World}}).toCompletableFuture();hGetAllExample.join();Map<String,String>hValsExampleParams=newHashMap<>();hValsExampleParams.put("field1","Hello");hValsExampleParams.put("field2","World");CompletableFuture<Void>hValsExample=asyncCommands.hset("myhash",hValsExampleParams).thenCompose(res1->{returnasyncCommands.hvals("myhash");}).thenAccept(res2->{List<String>sortedValues=newArrayList<>(res2);Collections.sort(sortedValues);System.out.println(sortedValues);// >>> [Hello, World]}).toCompletableFuture();hValsExample.join();// Set up hash with fieldsMap<String,String>hExpireExampleParams=newHashMap<>();hExpireExampleParams.put("field1","Hello");hExpireExampleParams.put("field2","World");CompletableFuture<Void>hExpireExample=asyncCommands.hset("myhash",hExpireExampleParams).thenCompose(res1->{// Set expiration on hash fieldsreturnasyncCommands.hexpire("myhash",10,"field1","field2");}).thenCompose(res2->{System.out.println(res2);// >>> [1, 1]// Check TTL of the fieldsreturnasyncCommands.httl("myhash","field1","field2");}).thenCompose(res3->{System.out.println(res3.size());// >>> 2// Try to set expiration on non-existent fieldreturnasyncCommands.hexpire("myhash",10,"nonexistent");}).thenAccept(System.out::println)// >>> -2.toCompletableFuture();hExpireExample.join();}finally{redisClient.shutdown();}}}
Java-Async Quick-Start
packageio.redis.examples.reactive;importio.lettuce.core.*;importio.lettuce.core.api.reactive.RedisReactiveCommands;importio.lettuce.core.api.StatefulRedisConnection;importreactor.core.publisher.Mono;importjava.util.*;publicclass CmdsHashExample{publicvoidrun(){RedisClientredisClient=RedisClient.create("redis://localhost:6379");try(StatefulRedisConnection<String,String>connection=redisClient.connect()){RedisReactiveCommands<String,String>reactiveCommands=connection.reactive();Map<String,String>hDelExampleParams=newHashMap<>();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=newHashMap<>();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=newHashMap<>();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=newHashMap<>();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=newHashMap<>();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=newArrayList<>(result);Collections.sort(sortedValues);System.out.println(sortedValues);// >>> [Hello, World]});hValsExample2.block();// Set up hash with fieldsMap<String,String>hExpireExampleParams=newHashMap<>();hExpireExampleParams.put("field1","Hello");hExpireExampleParams.put("field2","World");Mono<Long>hExpireExample1=reactiveCommands.hset("myhash",hExpireExampleParams).doOnNext(result->{});hExpireExample1.block();// Set expiration on hash fieldsMono<List<Long>>hExpireExample2=reactiveCommands.hexpire("myhash",10,"field1","field2").collectList().doOnNext(result->{System.out.println(result);// >>> [1, 1]});hExpireExample2.block();// Check TTL of the fieldsMono<List<Long>>hExpireExample3=reactiveCommands.httl("myhash","field1","field2").collectList().doOnNext(result->{System.out.println(result.size());// >>> 2});hExpireExample3.block();// Try to set expiration on non-existent fieldMono<List<Long>>hExpireExample4=reactiveCommands.hexpire("myhash",10,"nonexistent").collectList().doOnNext(result->{System.out.println(result);// >>> [-2]});hExpireExample4.block();}finally{redisClient.shutdown();}}}
Java-Reactive Quick-Start
package example_commands_test
import (
	"context"
	"fmt"
	"sort"
	"time"
	"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
}
func ExampleClient_hexpire() {
	ctx := context.Background()
	rdb := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
		Password: "", // no password
		DB: 0, // use default DB
	})
	// Set up hash with fields
	rdb.HSet(ctx, "myhash", "field1", "Hello", "field2", "World")
	// Set expiration on hash fields
	res1, err := rdb.HExpire(ctx, "myhash", 10*time.Second, "field1", "field2").Result()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(res1) // >>> [1 1]
	// Check TTL of the fields
	res2, err := rdb.HTTL(ctx, "myhash", "field1", "field2").Result()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(len(res2)) // >>> 2
	// Try to set expiration on non-existent field
	res3, err := rdb.HExpire(ctx, "myhash", 10*time.Second, "nonexistent").Result()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(res3) // >>> [-2]
	// Clean up
	rdb.Del(ctx, "myhash")
}
Go Quick-Start
using StackExchange.Redis;
using Xunit;
using System.Linq;
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
 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
 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
 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
 db.HashSet("myhash",
 [
 new("field1", "Hello"),
 new("field2", "World")
 ]
 );
 RedisValue[] hValsResult = db.HashValues("myhash");
 Array.Sort(hValsResult);
 Console.WriteLine(string.Join(", ", hValsResult));
 // >>> Hello, World
 // Set up hash with fields
 db.HashSet("myhash",
 [
 new("field1", "Hello"),
 new("field2", "World")
 ]
 );
 ExpireResult[] hexpireRes1 = db.HashFieldExpire(
 "myhash",
 new RedisValue[] { "field1", "field2" },
 TimeSpan.FromSeconds(10)
 );
 Console.WriteLine(string.Join(", ", hexpireRes1));
 // >>> Success, Success
 long[] hexpireRes2 = db.HashFieldGetTimeToLive(
 "myhash",
 new RedisValue[] { "field1", "field2" }
 );
 Console.WriteLine(string.Join(", ", hexpireRes2));
 // >>> 10, 10 (approximately)
 // Try to set expiration on non-existent field
 ExpireResult[] hexpireRes3 = db.HashFieldExpire(
 "myhash",
 new RedisValue[] { "nonexistent" },
 TimeSpan.FromSeconds(10)
 );
 Console.WriteLine(string.Join(", ", hexpireRes3));
 // >>> NoSuchField
 }
}
C#-Sync Quick-Start
<?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
 {
 $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

 $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

 $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"}

 $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";
 $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"]

 // Set up hash with fields
 $hExpireResult1 = $this->redis->hmset('myhash', ['field1' => 'Hello', 'field2' => 'World']);
 echo "HMSET myhash field1 Hello field2 World: " . ($hExpireResult1 ? 'OK' : 'FAIL') . "\n"; // >>> OK

 // Set expiration on hash fields
 $hExpireResult2 = $this->redis->hexpire('myhash', 10, ['field1', 'field2']);
 echo "HEXPIRE myhash 10 FIELDS field1 field2: " . json_encode($hExpireResult2) . "\n"; // >>> [1,1]

 // Check TTL of the fields
 $hExpireResult3 = $this->redis->httl('myhash', ['field1', 'field2']);
 echo "HTTL myhash FIELDS field1 field2 count: " . count($hExpireResult3) . "\n"; // >>> 2

 // Try to set expiration on non-existent field
 $hExpireResult4 = $this->redis->hexpire('myhash', 10, ['nonexistent']);
 echo "HEXPIRE myhash 10 FIELDS nonexistent: " . json_encode($hExpireResult4) . "\n"; // >>> [-2]

 }
 protected function tearDown(): void
 {
 // Clean up after each test
 $this->redis->flushall();
 $this->redis->disconnect();
 }
}
PHP Quick-Start
mod cmds_hash_tests{useredis::Commands;usestd::collections::HashMap;fn run(){letmutr=matchredis::Client::open("redis://127.0.0.1"){Ok(client)=>{matchclient.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");matchr.hset("myhash","field1","foo"){Ok(hdel1)=>{lethdel1: i32 =hdel1;println!("{hdel1}");// >>> 1
},Err(e)=>{println!("Error setting hash field: {e}");return;}}matchr.hget("myhash","field1"){Ok(hdel2)=>{lethdel2: Option<String>=hdel2;matchhdel2{Some(value)=>{println!("{value}");// >>> foo
},None=>{println!("None");}}},Err(e)=>{println!("Error getting hash field: {e}");return;}}matchr.hget("myhash","field2"){Ok(hdel3)=>{lethdel3: Option<String>=hdel3;matchhdel3{Some(_)=>{println!("Some value");},None=>{println!("None");// >>> None
}}},Err(e)=>{println!("Error getting hash field: {e}");return;}}matchr.hset("myhash","field1","Hello"){Ok(res1)=>{letres1: i32 =res1;println!("{res1}");// >>> 1
},Err(e)=>{println!("Error setting hash field: {e}");return;}}matchr.hget("myhash","field1"){Ok(res2)=>{letres2: Option<String>=res2;matchres2{Some(value)=>{println!("{value}");// >>> Hello
},None=>{println!("None");}}},Err(e)=>{println!("Error getting hash field: {e}");return;}}// Set multiple fields using hset_multiple
lethash_fields=[("field2","Hi"),("field3","World"),];ifletOk(res)=r.hset_multiple("myhash",&hash_fields){letres: String =res;println!("{res}");// >>> OK
}matchr.hget("myhash","field2"){Ok(res4)=>{letres4: Option<String>=res4;matchres4{Some(value)=>{println!("{value}");// >>> Hi
},None=>{println!("None");}}},Err(e)=>{println!("Error getting hash field: {e}");return;}}matchr.hget("myhash","field3"){Ok(res5)=>{letres5: Option<String>=res5;matchres5{Some(value)=>{println!("{value}");// >>> World
},None=>{println!("None");}}},Err(e)=>{println!("Error getting hash field: {e}");return;}}matchr.hgetall("myhash"){Ok(res6)=>{letres6: HashMap<String,String>=res6;println!("{res6:?}");// >>> {"field1": "Hello", "field2": "Hi", "field3": "World"}
},Err(e)=>{println!("Error getting all hash fields: {e}");return;}}matchr.hset("myhash","field1","foo"){Ok(res7)=>{letres7: i32 =res7;println!("{res7}");// >>> 1
},Err(e)=>{println!("Error setting hash field: {e}");return;}}matchr.hget("myhash","field1"){Ok(res8)=>{letres8: Option<String>=res8;matchres8{Some(value)=>{println!("{value}");// >>> foo
},None=>{println!("None");}}},Err(e)=>{println!("Error getting hash field: {e}");return;}}matchr.hget("myhash","field2"){Ok(res9)=>{letres9: Option<String>=res9;matchres9{Some(_)=>{println!("Some value");},None=>{println!("None");// >>> None
}}},Err(e)=>{println!("Error getting hash field: {e}");return;}}lethash_fields=[("field1","Hello"),("field2","World"),];ifletOk(_)=r.hset_multiple::<&str,&str,&str,String>("myhash",&hash_fields){// Fields set successfully
}matchr.hgetall("myhash"){Ok(res11)=>{letres11: HashMap<String,String>=res11;println!("{res11:?}");// >>> {"field1": "Hello", "field2": "World"}
},Err(e)=>{println!("Error getting all hash fields: {e}");return;}}lethash_fields=[("field1","Hello"),("field2","World"),];ifletOk(_)=r.hset_multiple::<&str,&str,&str,String>("myhash",&hash_fields){// Fields set successfully
}matchr.hvals("myhash"){Ok(res11)=>{letres11: Vec<String>=res11;println!("{res11:?}");// >>> ["Hello", "World"]
},Err(e)=>{println!("Error getting hash values: {e}");return;}}// Set up hash with fields
lethash_fields=vec![("field1","Hello"),("field2","World")];ifletOk(res)=r.hset_multiple("myhash",&hash_fields){letres: String =res;println!("{res}");// >>> OK
}// Set expiration on hash fields
matchr.hexpire("myhash",10,redis::ExpireOption::NONE,&["field1","field2"]){Ok(res1)=>{letres1: Vec<i32>=res1;println!("{:?}",res1);// >>> [1, 1]
},Err(e)=>{println!("Error setting expiration: {e}");return;}}// Check TTL of the fields
matchr.httl("myhash",&["field1","field2"]){Ok(res2)=>{letres2: Vec<i32>=res2;println!("{}",res2.len());// >>> 2
},Err(e)=>{println!("Error getting TTL: {e}");return;}}// Try to set expiration on non-existent field
matchr.hexpire("myhash",10,redis::ExpireOption::NONE,&["nonexistent"]){Ok(res3)=>{letres3: Vec<i32>=res3;println!("{:?}",res3);// >>> [-2]
},Err(e)=>{println!("Error setting expiration on non-existent field: {e}");return;}}}}
Rust-Sync Quick-Start
mod cmds_hash_tests{useredis::AsyncCommands;usestd::collections::HashMap;asyncfn run(){letmutr=matchredis::Client::open("redis://127.0.0.1"){Ok(client)=>{matchclient.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;matchr.hset("myhash","field1","foo").await{Ok(hdel1)=>{lethdel1: i32 =hdel1;println!("{hdel1}");// >>> 1
},Err(e)=>{println!("Error setting hash field: {e}");return;}}matchr.hget("myhash","field1").await{Ok(hdel2)=>{lethdel2: Option<String>=hdel2;matchhdel2{Some(value)=>{println!("{value}");// >>> foo
},None=>{println!("None");}}},Err(e)=>{println!("Error getting hash field: {e}");return;}}matchr.hget("myhash","field2").await{Ok(hdel3)=>{lethdel3: Option<String>=hdel3;matchhdel3{Some(_)=>{println!("Some value");},None=>{println!("None");// >>> None
}}},Err(e)=>{println!("Error getting hash field: {e}");return;}}matchr.hset("myhash","field1","Hello").await{Ok(res1)=>{letres1: i32 =res1;println!("{res1}");// >>> 1
},Err(e)=>{println!("Error setting hash field: {e}");return;}}matchr.hget("myhash","field1").await{Ok(res2)=>{letres2: Option<String>=res2;matchres2{Some(value)=>{println!("{value}");// >>> Hello
},None=>{println!("None");}}},Err(e)=>{println!("Error getting hash field: {e}");return;}}// Set multiple fields using hset_multiple
lethash_fields=[("field2","Hi"),("field3","World"),];ifletOk(res)=r.hset_multiple("myhash",&hash_fields).await{letres: String =res;println!("{res}");// >>> OK
}matchr.hget("myhash","field2").await{Ok(res4)=>{letres4: Option<String>=res4;matchres4{Some(value)=>{println!("{value}");// >>> Hi
},None=>{println!("None");}}},Err(e)=>{println!("Error getting hash field: {e}");return;}}matchr.hget("myhash","field3").await{Ok(res5)=>{letres5: Option<String>=res5;matchres5{Some(value)=>{println!("{value}");// >>> World
},None=>{println!("None");}}},Err(e)=>{println!("Error getting hash field: {e}");return;}}matchr.hgetall("myhash").await{Ok(res6)=>{letres6: HashMap<String,String>=res6;println!("{res6:?}");// >>> {"field1": "Hello", "field2": "Hi", "field3": "World"}
},Err(e)=>{println!("Error getting all hash fields: {e}");return;}}matchr.hset("myhash","field1","foo").await{Ok(res7)=>{letres7: i32 =res7;println!("{res7}");// >>> 1
},Err(e)=>{println!("Error setting hash field: {e}");return;}}matchr.hget("myhash","field1").await{Ok(res8)=>{letres8: Option<String>=res8;matchres8{Some(value)=>{println!("{value}");// >>> foo
},None=>{println!("None");}}},Err(e)=>{println!("Error getting hash field: {e}");return;}}matchr.hget("myhash","field2").await{Ok(res9)=>{letres9: Option<String>=res9;matchres9{Some(_)=>{println!("Some value");},None=>{println!("None");// >>> None
}}},Err(e)=>{println!("Error getting hash field: {e}");return;}}lethash_fields=[("field1","Hello"),("field2","World"),];ifletOk(_)=r.hset_multiple::<&str,&str,&str,String>("myhash",&hash_fields).await{// Fields set successfully
}matchr.hgetall("myhash").await{Ok(res11)=>{letres11: HashMap<String,String>=res11;println!("{res11:?}");// >>> {"field1": "Hello", "field2": "World"}
},Err(e)=>{println!("Error getting all hash fields: {e}");return;}}lethash_fields=[("field1","Hello"),("field2","World"),];ifletOk(_)=r.hset_multiple::<&str,&str,&str,String>("myhash",&hash_fields).await{// Fields set successfully
}matchr.hvals("myhash").await{Ok(res11)=>{letres11: Vec<String>=res11;println!("{res11:?}");// >>> ["Hello", "World"]
},Err(e)=>{println!("Error getting hash values: {e}");return;}}// Set up hash with fields
lethash_fields=vec![("field1","Hello"),("field2","World")];ifletOk(res)=r.hset_multiple("myhash",&hash_fields).await{letres: String =res;println!("{res}");// >>> OK
}// Set expiration on hash fields
matchr.hexpire("myhash",10,redis::ExpireOption::NONE,&["field1","field2"]).await{Ok(res1)=>{letres1: Vec<i32>=res1;println!("{:?}",res1);// >>> [1, 1]
},Err(e)=>{println!("Error setting expiration: {e}");return;}}// Check TTL of the fields
matchr.httl("myhash",&["field1","field2"]).await{Ok(res2)=>{letres2: Vec<i32>=res2;println!("{}",res2.len());// >>> 2
},Err(e)=>{println!("Error getting TTL: {e}");return;}}// Try to set expiration on non-existent field
matchr.hexpire("myhash",10,redis::ExpireOption::NONE,&["nonexistent"]).await{Ok(res3)=>{letres3: Vec<i32>=res3;println!("{:?}",res3);// >>> [-2]
},Err(e)=>{println!("Error setting expiration on non-existent field: {e}");return;}}}}
Rust-Async Quick-Start

Give these commands a try in the interactive console:

HSET myhash field1 "Hello" HGET myhash field1 HSET myhash field2 "Hi" field3 "World" HGET myhash field2 HGET myhash field3 HGETALL myhash

Redis Enterprise and Redis Cloud compatibility

Redis
Enterprise
Redis
Cloud
Notes
✅ Standard
✅ Active-Active
✅ Standard
✅ Active-Active

Return information

Integer reply: the number of fields that were added.

History

RATE THIS PAGE
Back to top ↑

AltStyle によって変換されたページ (->オリジナル) /