HSET

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 Software 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.

Required arguments

key

The name of the key that holds the hash.

field value [field value ...]

One or more field-value pairs to set in the hash.

Examples

Foundational: Set one or more field-value pairs in a hash using HSET (creates hash if needed, overwrites existing fields, returns count of new fields)
> 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"
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" }

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)  


import assert from 'node:assert';
import { Redis } from 'ioredis';

const redis = new Redis();


await redis.hset('myhash', { field1: 'Hello', field2: 'World' });

const hmgetResult = await redis.hmget('myhash', 'field1', 'field2', 'nofield');
console.log(hmgetResult); // >>> ['Hello', 'World', null]


redis.disconnect();

        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
            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();
            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}
            });
	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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis/hiredis.h>

int main(int argc, char **argv) {
    redisContext *c = redisConnect("127.0.0.1", 6379);

    if (c == NULL || c->err) {
        if (c) {
            printf("Connection error: %s\n", c->errstr);
            redisFree(c);
        } else {
            printf("Connection error: can't allocate redis context\n");
        }
        return 1;
    }


    redisReply *reply;

    // Set up hash with fields
    reply = redisCommand(c, "HSET %s %s %s %s %s",
        "myhash", "field1", "Hello", "field2", "World");
    freeReplyObject(reply);

    // Get multiple fields at once
    reply = redisCommand(c, "HMGET %s %s %s %s",
        "myhash", "field1", "field2", "nofield");

    printf("HMGET myhash field1 field2 nofield:\n");
    for (size_t i = 0; i < reply->elements; i++) {
        if (reply->element[i]->type == REDIS_REPLY_NIL) {
            printf("  [%zu]: null\n", i);
        } else {
            printf("  [%zu]: %s\n", i, reply->element[i]->str);
        }
    }
    // >>> [0]: Hello
    // >>> [1]: World
    // >>> [2]: null


    freeReplyObject(reply);


    redisFree(c);

    return 0;
}

        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

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

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 Software and Redis Cloud compatibility

Redis
Software
Redis
Cloud
Notes
✅ Standard
✅ Active-Active
✅ Standard
✅ Active-Active

Return information

Integer reply: the number of fields that were added.

History

  • Starting with Redis version 4.0.0: Accepts multiple field and value arguments.
RATE THIS PAGE
Back to top ↑