Redis hashes
Introduction to Redis hashes
Redis hashes are record types structured as collections of field-value pairs. You can use hashes to represent basic objects and to store groupings of counters, among other things.
> HSET bike:1 model Deimos brand Ergonom type 'Enduro bikes' price 4972
(integer) 4
> HGET bike:1 model
"Deimos"
> HGET bike:1 price
"4972"
> HGETALL bike:1
1) "model"
2) "Deimos"
3) "brand"
4) "Ergonom"
5) "type"
6) "Enduro bikes"
7) "price"
8) "4972"
"""
Code samples for Hash doc pages:
https://redis.io/docs/latest/develop/data-types/hashes/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.hset(
"bike:1",
mapping={
"model": "Deimos",
"brand": "Ergonom",
"type": "Enduro bikes",
"price": 4972,
},
)
print(res1)
# >>> 4
res2 = r.hget("bike:1", "model")
print(res2)
# >>> 'Deimos'
res3 = r.hget("bike:1", "price")
print(res3)
# >>> '4972'
res4 = r.hgetall("bike:1")
print(res4)
# >>> {'model': 'Deimos', 'brand': 'Ergonom', 'type': 'Enduro bikes', 'price': '4972'}
res5 = r.hmget("bike:1", ["model", "price"])
print(res5)
# >>> ['Deimos', '4972']
res6 = r.hincrby("bike:1", "price", 100)
print(res6)
# >>> 5072
res7 = r.hincrby("bike:1", "price", -100)
print(res7)
# >>> 4972
res11 = r.hincrby("bike:1:stats", "rides", 1)
print(res11)
# >>> 1
res12 = r.hincrby("bike:1:stats", "rides", 1)
print(res12)
# >>> 2
res13 = r.hincrby("bike:1:stats", "rides", 1)
print(res13)
# >>> 3
res14 = r.hincrby("bike:1:stats", "crashes", 1)
print(res14)
# >>> 1
res15 = r.hincrby("bike:1:stats", "owners", 1)
print(res15)
# >>> 1
res16 = r.hget("bike:1:stats", "rides")
print(res16)
# >>> 3
res17 = r.hmget("bike:1:stats", ["crashes", "owners"])
print(res17)
# >>> ['1', '1']
import assert from 'assert';
import { createClient } from 'redis';
const client = createClient();
await client.connect();
const res1 = await client.hSet(
'bike:1',
{
'model': 'Deimos',
'brand': 'Ergonom',
'type': 'Enduro bikes',
'price': 4972,
}
)
console.log(res1) // 4
const res2 = await client.hGet('bike:1', 'model')
console.log(res2) // 'Deimos'
const res3 = await client.hGet('bike:1', 'price')
console.log(res3) // '4972'
const res4 = await client.hGetAll('bike:1')
console.log(res4)
/*
{
brand: 'Ergonom',
model: 'Deimos',
price: '4972',
type: 'Enduro bikes'
}
*/
const res5 = await client.hmGet('bike:1', ['model', 'price'])
console.log(res5) // ['Deimos', '4972']
const res6 = await client.hIncrBy('bike:1', 'price', 100)
console.log(res6) // 5072
const res7 = await client.hIncrBy('bike:1', 'price', -100)
console.log(res7) // 4972
const res11 = await client.hIncrBy('bike:1:stats', 'rides', 1)
console.log(res11) // 1
const res12 = await client.hIncrBy('bike:1:stats', 'rides', 1)
console.log(res12) // 2
const res13 = await client.hIncrBy('bike:1:stats', 'rides', 1)
console.log(res13) // 3
const res14 = await client.hIncrBy('bike:1:stats', 'crashes', 1)
console.log(res14) // 1
const res15 = await client.hIncrBy('bike:1:stats', 'owners', 1)
console.log(res15) // 1
const res16 = await client.hGet('bike:1:stats', 'rides')
console.log(res16) // 3
const res17 = await client.hmGet('bike:1:stats', ['crashes', 'owners'])
console.log(res17) // ['1', '1']
package io.redis.examples;
import redis.clients.jedis.UnifiedJedis;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HashExample {
public void run() {
try (UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379")) {
Map<String, String> bike1 = new HashMap<>();
bike1.put("model", "Deimos");
bike1.put("brand", "Ergonom");
bike1.put("type", "Enduro bikes");
bike1.put("price", "4972");
Long res1 = jedis.hset("bike:1", bike1);
System.out.println(res1); // 4
String res2 = jedis.hget("bike:1", "model");
System.out.println(res2); // Deimos
String res3 = jedis.hget("bike:1", "price");
System.out.println(res3); // 4972
Map<String, String> res4 = jedis.hgetAll("bike:1");
System.out.println(res4); // {type=Enduro bikes, brand=Ergonom, price=4972, model=Deimos}
List<String> res5 = jedis.hmget("bike:1", "model", "price");
System.out.println(res5); // [Deimos, 4972]
Long res6 = jedis.hincrBy("bike:1", "price", 100);
System.out.println(res6); // 5072
Long res7 = jedis.hincrBy("bike:1", "price", -100);
System.out.println(res7); // 4972
Long res8 = jedis.hincrBy("bike:1:stats", "rides", 1);
System.out.println(res8); // 1
Long res9 = jedis.hincrBy("bike:1:stats", "rides", 1);
System.out.println(res9); // 2
Long res10 = jedis.hincrBy("bike:1:stats", "rides", 1);
System.out.println(res10); // 3
Long res11 = jedis.hincrBy("bike:1:stats", "crashes", 1);
System.out.println(res11); // 1
Long res12 = jedis.hincrBy("bike:1:stats", "owners", 1);
System.out.println(res12); // 1
String res13 = jedis.hget("bike:1:stats", "rides");
System.out.println(res13); // 3
List<String> res14 = jedis.hmget("bike:1:stats", "crashes", "owners");
System.out.println(res14); // [1, 1]
}
}
}
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 HashExample {
public void run() {
RedisClient redisClient = RedisClient.create("redis://localhost:6379");
try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
RedisAsyncCommands<String, String> asyncCommands = connection.async();
Map<String, String> bike1 = new HashMap<>();
bike1.put("model", "Deimos");
bike1.put("brand", "Ergonom");
bike1.put("type", "Enduro bikes");
bike1.put("price", "4972");
CompletableFuture<Void> setGetAll = asyncCommands.hset("bike:1", bike1).thenCompose(res1 -> {
System.out.println(res1); // >>> 4
return asyncCommands.hget("bike:1", "model");
}).thenCompose(res2 -> {
System.out.println(res2); // >>> Deimos
return asyncCommands.hget("bike:1", "price");
}).thenCompose(res3 -> {
System.out.println(res3); // >>> 4972
return asyncCommands.hgetall("bike:1");
})
.thenAccept(System.out::println)
// >>> {type=Enduro bikes, brand=Ergonom, price=4972, model=Deimos}
.toCompletableFuture();
CompletableFuture<Void> hmGet = setGetAll.thenCompose(res4 -> {
return asyncCommands.hmget("bike:1", "model", "price");
})
.thenAccept(System.out::println)
// [KeyValue[model, Deimos], KeyValue[price, 4972]]
.toCompletableFuture();
CompletableFuture<Void> hIncrBy = hmGet.thenCompose(r -> {
return asyncCommands.hincrby("bike:1", "price", 100);
}).thenCompose(res6 -> {
System.out.println(res6); // >>> 5072
return asyncCommands.hincrby("bike:1", "price", -100);
})
.thenAccept(System.out::println)
// >>> 4972
.toCompletableFuture();
CompletableFuture<Void> incrByGetMget = asyncCommands.hincrby("bike:1:stats", "rides", 1).thenCompose(res7 -> {
System.out.println(res7); // >>> 1
return asyncCommands.hincrby("bike:1:stats", "rides", 1);
}).thenCompose(res8 -> {
System.out.println(res8); // >>> 2
return asyncCommands.hincrby("bike:1:stats", "rides", 1);
}).thenCompose(res9 -> {
System.out.println(res9); // >>> 3
return asyncCommands.hincrby("bike:1:stats", "crashes", 1);
}).thenCompose(res10 -> {
System.out.println(res10); // >>> 1
return asyncCommands.hincrby("bike:1:stats", "owners", 1);
}).thenCompose(res11 -> {
System.out.println(res11); // >>> 1
return asyncCommands.hget("bike:1:stats", "rides");
}).thenCompose(res12 -> {
System.out.println(res12); // >>> 3
return asyncCommands.hmget("bike:1:stats", "crashes", "owners");
})
.thenAccept(System.out::println)
// >>> [KeyValue[crashes, 1], KeyValue[owners, 1]]
.toCompletableFuture();
CompletableFuture.allOf(
hIncrBy, incrByGetMget).join();
} finally {
redisClient.shutdown();
}
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_set_get_all() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
hashFields := []string{
"model", "Deimos",
"brand", "Ergonom",
"type", "Enduro bikes",
"price", "4972",
}
res1, err := rdb.HSet(ctx, "bike:1", hashFields).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> 4
res2, err := rdb.HGet(ctx, "bike:1", "model").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> Deimos
res3, err := rdb.HGet(ctx, "bike:1", "price").Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> 4972
cmdReturn := rdb.HGetAll(ctx, "bike:1")
res4, err := cmdReturn.Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> map[brand:Ergonom model:Deimos price:4972 type:Enduro bikes]
type BikeInfo struct {
Model string `redis:"model"`
Brand string `redis:"brand"`
Type string `redis:"type"`
Price int `redis:"price"`
}
var res4a BikeInfo
if err := cmdReturn.Scan(&res4a); err != nil {
panic(err)
}
fmt.Printf("Model: %v, Brand: %v, Type: %v, Price: $%v\n",
res4a.Model, res4a.Brand, res4a.Type, res4a.Price)
// >>> Model: Deimos, Brand: Ergonom, Type: Enduro bikes, Price: $4972
}
func ExampleClient_hmget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
hashFields := []string{
"model", "Deimos",
"brand", "Ergonom",
"type", "Enduro bikes",
"price", "4972",
}
_, err := rdb.HSet(ctx, "bike:1", hashFields).Result()
if err != nil {
panic(err)
}
cmdReturn := rdb.HMGet(ctx, "bike:1", "model", "price")
res5, err := cmdReturn.Result()
if err != nil {
panic(err)
}
fmt.Println(res5) // >>> [Deimos 4972]
type BikeInfo struct {
Model string `redis:"model"`
Brand string `redis:"-"`
Type string `redis:"-"`
Price int `redis:"price"`
}
var res5a BikeInfo
if err := cmdReturn.Scan(&res5a); err != nil {
panic(err)
}
fmt.Printf("Model: %v, Price: $%v\n", res5a.Model, res5a.Price)
// >>> Model: Deimos, Price: $4972
}
func ExampleClient_hincrby() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
hashFields := []string{
"model", "Deimos",
"brand", "Ergonom",
"type", "Enduro bikes",
"price", "4972",
}
_, err := rdb.HSet(ctx, "bike:1", hashFields).Result()
if err != nil {
panic(err)
}
res6, err := rdb.HIncrBy(ctx, "bike:1", "price", 100).Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> 5072
res7, err := rdb.HIncrBy(ctx, "bike:1", "price", -100).Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> 4972
}
func ExampleClient_incrby_get_mget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res8, err := rdb.HIncrBy(ctx, "bike:1:stats", "rides", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> 1
res9, err := rdb.HIncrBy(ctx, "bike:1:stats", "rides", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> 2
res10, err := rdb.HIncrBy(ctx, "bike:1:stats", "rides", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> 3
res11, err := rdb.HIncrBy(ctx, "bike:1:stats", "crashes", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> 1
res12, err := rdb.HIncrBy(ctx, "bike:1:stats", "owners", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> 1
res13, err := rdb.HGet(ctx, "bike:1:stats", "rides").Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> 3
res14, err := rdb.HMGet(ctx, "bike:1:stats", "crashes", "owners").Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> [1 1]
}
using NRedisStack.Tests;
using StackExchange.Redis;
public class HashExample
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
db.KeyDelete("bike:1");
db.HashSet("bike:1", new HashEntry[]
{
new HashEntry("model", "Deimos"),
new HashEntry("brand", "Ergonom"),
new HashEntry("type", "Enduro bikes"),
new HashEntry("price", 4972)
});
Console.WriteLine("Hash Created");
// Hash Created
var model = db.HashGet("bike:1", "model");
Console.WriteLine($"Model: {model}");
// Model: Deimos
var price = db.HashGet("bike:1", "price");
Console.WriteLine($"Price: {price}");
// Price: 4972
var bike = db.HashGetAll("bike:1");
Console.WriteLine("bike:1");
Console.WriteLine(string.Join("\n", bike.Select(b => $"{b.Name}: {b.Value}")));
// Bike:1:
// model: Deimos
// brand: Ergonom
// type: Enduro bikes
// price: 4972
var values = db.HashGet("bike:1", new RedisValue[] { "model", "price" });
Console.WriteLine(string.Join(" ", values));
// Deimos 4972
var newPrice = db.HashIncrement("bike:1", "price", 100);
Console.WriteLine($"New price: {newPrice}");
// New price: 5072
newPrice = db.HashIncrement("bike:1", "price", -100);
Console.WriteLine($"New price: {newPrice}");
// New price: 4972
var rides = db.HashIncrement("bike:1", "rides");
Console.WriteLine($"Rides: {rides}");
// Rides: 1
rides = db.HashIncrement("bike:1", "rides");
Console.WriteLine($"Rides: {rides}");
// Rides: 2
rides = db.HashIncrement("bike:1", "rides");
Console.WriteLine($"Rides: {rides}");
// Rides: 3
var crashes = db.HashIncrement("bike:1", "crashes");
Console.WriteLine($"Crashes: {crashes}");
// Crashes: 1
var owners = db.HashIncrement("bike:1", "owners");
Console.WriteLine($"Owners: {owners}");
// Owners: 1
var stats = db.HashGet("bike:1", new RedisValue[] { "crashes", "owners" });
Console.WriteLine($"Bike stats: crashes={stats[0]}, owners={stats[1]}");
// Bike stats: crashes=1, owners=1
}
}
While hashes are handy to represent objects, actually the number of fields you can put inside a hash has no practical limits (other than available memory), so you can use hashes in many different ways inside your application.
The command HSET
sets multiple fields of the hash, while HGET
retrieves
a single field. HMGET
is similar to HGET
but returns an array of values:
> HMGET bike:1 model price no-such-field
1) "Deimos"
2) "4972"
3) (nil)
"""
Code samples for Hash doc pages:
https://redis.io/docs/latest/develop/data-types/hashes/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.hset(
"bike:1",
mapping={
"model": "Deimos",
"brand": "Ergonom",
"type": "Enduro bikes",
"price": 4972,
},
)
print(res1)
# >>> 4
res2 = r.hget("bike:1", "model")
print(res2)
# >>> 'Deimos'
res3 = r.hget("bike:1", "price")
print(res3)
# >>> '4972'
res4 = r.hgetall("bike:1")
print(res4)
# >>> {'model': 'Deimos', 'brand': 'Ergonom', 'type': 'Enduro bikes', 'price': '4972'}
res5 = r.hmget("bike:1", ["model", "price"])
print(res5)
# >>> ['Deimos', '4972']
res6 = r.hincrby("bike:1", "price", 100)
print(res6)
# >>> 5072
res7 = r.hincrby("bike:1", "price", -100)
print(res7)
# >>> 4972
res11 = r.hincrby("bike:1:stats", "rides", 1)
print(res11)
# >>> 1
res12 = r.hincrby("bike:1:stats", "rides", 1)
print(res12)
# >>> 2
res13 = r.hincrby("bike:1:stats", "rides", 1)
print(res13)
# >>> 3
res14 = r.hincrby("bike:1:stats", "crashes", 1)
print(res14)
# >>> 1
res15 = r.hincrby("bike:1:stats", "owners", 1)
print(res15)
# >>> 1
res16 = r.hget("bike:1:stats", "rides")
print(res16)
# >>> 3
res17 = r.hmget("bike:1:stats", ["crashes", "owners"])
print(res17)
# >>> ['1', '1']
import assert from 'assert';
import { createClient } from 'redis';
const client = createClient();
await client.connect();
const res1 = await client.hSet(
'bike:1',
{
'model': 'Deimos',
'brand': 'Ergonom',
'type': 'Enduro bikes',
'price': 4972,
}
)
console.log(res1) // 4
const res2 = await client.hGet('bike:1', 'model')
console.log(res2) // 'Deimos'
const res3 = await client.hGet('bike:1', 'price')
console.log(res3) // '4972'
const res4 = await client.hGetAll('bike:1')
console.log(res4)
/*
{
brand: 'Ergonom',
model: 'Deimos',
price: '4972',
type: 'Enduro bikes'
}
*/
const res5 = await client.hmGet('bike:1', ['model', 'price'])
console.log(res5) // ['Deimos', '4972']
const res6 = await client.hIncrBy('bike:1', 'price', 100)
console.log(res6) // 5072
const res7 = await client.hIncrBy('bike:1', 'price', -100)
console.log(res7) // 4972
const res11 = await client.hIncrBy('bike:1:stats', 'rides', 1)
console.log(res11) // 1
const res12 = await client.hIncrBy('bike:1:stats', 'rides', 1)
console.log(res12) // 2
const res13 = await client.hIncrBy('bike:1:stats', 'rides', 1)
console.log(res13) // 3
const res14 = await client.hIncrBy('bike:1:stats', 'crashes', 1)
console.log(res14) // 1
const res15 = await client.hIncrBy('bike:1:stats', 'owners', 1)
console.log(res15) // 1
const res16 = await client.hGet('bike:1:stats', 'rides')
console.log(res16) // 3
const res17 = await client.hmGet('bike:1:stats', ['crashes', 'owners'])
console.log(res17) // ['1', '1']
package io.redis.examples;
import redis.clients.jedis.UnifiedJedis;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HashExample {
public void run() {
try (UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379")) {
Map<String, String> bike1 = new HashMap<>();
bike1.put("model", "Deimos");
bike1.put("brand", "Ergonom");
bike1.put("type", "Enduro bikes");
bike1.put("price", "4972");
Long res1 = jedis.hset("bike:1", bike1);
System.out.println(res1); // 4
String res2 = jedis.hget("bike:1", "model");
System.out.println(res2); // Deimos
String res3 = jedis.hget("bike:1", "price");
System.out.println(res3); // 4972
Map<String, String> res4 = jedis.hgetAll("bike:1");
System.out.println(res4); // {type=Enduro bikes, brand=Ergonom, price=4972, model=Deimos}
List<String> res5 = jedis.hmget("bike:1", "model", "price");
System.out.println(res5); // [Deimos, 4972]
Long res6 = jedis.hincrBy("bike:1", "price", 100);
System.out.println(res6); // 5072
Long res7 = jedis.hincrBy("bike:1", "price", -100);
System.out.println(res7); // 4972
Long res8 = jedis.hincrBy("bike:1:stats", "rides", 1);
System.out.println(res8); // 1
Long res9 = jedis.hincrBy("bike:1:stats", "rides", 1);
System.out.println(res9); // 2
Long res10 = jedis.hincrBy("bike:1:stats", "rides", 1);
System.out.println(res10); // 3
Long res11 = jedis.hincrBy("bike:1:stats", "crashes", 1);
System.out.println(res11); // 1
Long res12 = jedis.hincrBy("bike:1:stats", "owners", 1);
System.out.println(res12); // 1
String res13 = jedis.hget("bike:1:stats", "rides");
System.out.println(res13); // 3
List<String> res14 = jedis.hmget("bike:1:stats", "crashes", "owners");
System.out.println(res14); // [1, 1]
}
}
}
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 HashExample {
public void run() {
RedisClient redisClient = RedisClient.create("redis://localhost:6379");
try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
RedisAsyncCommands<String, String> asyncCommands = connection.async();
Map<String, String> bike1 = new HashMap<>();
bike1.put("model", "Deimos");
bike1.put("brand", "Ergonom");
bike1.put("type", "Enduro bikes");
bike1.put("price", "4972");
CompletableFuture<Void> setGetAll = asyncCommands.hset("bike:1", bike1).thenCompose(res1 -> {
System.out.println(res1); // >>> 4
return asyncCommands.hget("bike:1", "model");
}).thenCompose(res2 -> {
System.out.println(res2); // >>> Deimos
return asyncCommands.hget("bike:1", "price");
}).thenCompose(res3 -> {
System.out.println(res3); // >>> 4972
return asyncCommands.hgetall("bike:1");
})
.thenAccept(System.out::println)
// >>> {type=Enduro bikes, brand=Ergonom, price=4972, model=Deimos}
.toCompletableFuture();
CompletableFuture<Void> hmGet = setGetAll.thenCompose(res4 -> {
return asyncCommands.hmget("bike:1", "model", "price");
})
.thenAccept(System.out::println)
// [KeyValue[model, Deimos], KeyValue[price, 4972]]
.toCompletableFuture();
CompletableFuture<Void> hIncrBy = hmGet.thenCompose(r -> {
return asyncCommands.hincrby("bike:1", "price", 100);
}).thenCompose(res6 -> {
System.out.println(res6); // >>> 5072
return asyncCommands.hincrby("bike:1", "price", -100);
})
.thenAccept(System.out::println)
// >>> 4972
.toCompletableFuture();
CompletableFuture<Void> incrByGetMget = asyncCommands.hincrby("bike:1:stats", "rides", 1).thenCompose(res7 -> {
System.out.println(res7); // >>> 1
return asyncCommands.hincrby("bike:1:stats", "rides", 1);
}).thenCompose(res8 -> {
System.out.println(res8); // >>> 2
return asyncCommands.hincrby("bike:1:stats", "rides", 1);
}).thenCompose(res9 -> {
System.out.println(res9); // >>> 3
return asyncCommands.hincrby("bike:1:stats", "crashes", 1);
}).thenCompose(res10 -> {
System.out.println(res10); // >>> 1
return asyncCommands.hincrby("bike:1:stats", "owners", 1);
}).thenCompose(res11 -> {
System.out.println(res11); // >>> 1
return asyncCommands.hget("bike:1:stats", "rides");
}).thenCompose(res12 -> {
System.out.println(res12); // >>> 3
return asyncCommands.hmget("bike:1:stats", "crashes", "owners");
})
.thenAccept(System.out::println)
// >>> [KeyValue[crashes, 1], KeyValue[owners, 1]]
.toCompletableFuture();
CompletableFuture.allOf(
hIncrBy, incrByGetMget).join();
} finally {
redisClient.shutdown();
}
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_set_get_all() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
hashFields := []string{
"model", "Deimos",
"brand", "Ergonom",
"type", "Enduro bikes",
"price", "4972",
}
res1, err := rdb.HSet(ctx, "bike:1", hashFields).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> 4
res2, err := rdb.HGet(ctx, "bike:1", "model").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> Deimos
res3, err := rdb.HGet(ctx, "bike:1", "price").Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> 4972
cmdReturn := rdb.HGetAll(ctx, "bike:1")
res4, err := cmdReturn.Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> map[brand:Ergonom model:Deimos price:4972 type:Enduro bikes]
type BikeInfo struct {
Model string `redis:"model"`
Brand string `redis:"brand"`
Type string `redis:"type"`
Price int `redis:"price"`
}
var res4a BikeInfo
if err := cmdReturn.Scan(&res4a); err != nil {
panic(err)
}
fmt.Printf("Model: %v, Brand: %v, Type: %v, Price: $%v\n",
res4a.Model, res4a.Brand, res4a.Type, res4a.Price)
// >>> Model: Deimos, Brand: Ergonom, Type: Enduro bikes, Price: $4972
}
func ExampleClient_hmget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
hashFields := []string{
"model", "Deimos",
"brand", "Ergonom",
"type", "Enduro bikes",
"price", "4972",
}
_, err := rdb.HSet(ctx, "bike:1", hashFields).Result()
if err != nil {
panic(err)
}
cmdReturn := rdb.HMGet(ctx, "bike:1", "model", "price")
res5, err := cmdReturn.Result()
if err != nil {
panic(err)
}
fmt.Println(res5) // >>> [Deimos 4972]
type BikeInfo struct {
Model string `redis:"model"`
Brand string `redis:"-"`
Type string `redis:"-"`
Price int `redis:"price"`
}
var res5a BikeInfo
if err := cmdReturn.Scan(&res5a); err != nil {
panic(err)
}
fmt.Printf("Model: %v, Price: $%v\n", res5a.Model, res5a.Price)
// >>> Model: Deimos, Price: $4972
}
func ExampleClient_hincrby() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
hashFields := []string{
"model", "Deimos",
"brand", "Ergonom",
"type", "Enduro bikes",
"price", "4972",
}
_, err := rdb.HSet(ctx, "bike:1", hashFields).Result()
if err != nil {
panic(err)
}
res6, err := rdb.HIncrBy(ctx, "bike:1", "price", 100).Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> 5072
res7, err := rdb.HIncrBy(ctx, "bike:1", "price", -100).Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> 4972
}
func ExampleClient_incrby_get_mget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res8, err := rdb.HIncrBy(ctx, "bike:1:stats", "rides", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> 1
res9, err := rdb.HIncrBy(ctx, "bike:1:stats", "rides", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> 2
res10, err := rdb.HIncrBy(ctx, "bike:1:stats", "rides", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> 3
res11, err := rdb.HIncrBy(ctx, "bike:1:stats", "crashes", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> 1
res12, err := rdb.HIncrBy(ctx, "bike:1:stats", "owners", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> 1
res13, err := rdb.HGet(ctx, "bike:1:stats", "rides").Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> 3
res14, err := rdb.HMGet(ctx, "bike:1:stats", "crashes", "owners").Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> [1 1]
}
using NRedisStack.Tests;
using StackExchange.Redis;
public class HashExample
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
db.KeyDelete("bike:1");
db.HashSet("bike:1", new HashEntry[]
{
new HashEntry("model", "Deimos"),
new HashEntry("brand", "Ergonom"),
new HashEntry("type", "Enduro bikes"),
new HashEntry("price", 4972)
});
Console.WriteLine("Hash Created");
// Hash Created
var model = db.HashGet("bike:1", "model");
Console.WriteLine($"Model: {model}");
// Model: Deimos
var price = db.HashGet("bike:1", "price");
Console.WriteLine($"Price: {price}");
// Price: 4972
var bike = db.HashGetAll("bike:1");
Console.WriteLine("bike:1");
Console.WriteLine(string.Join("\n", bike.Select(b => $"{b.Name}: {b.Value}")));
// Bike:1:
// model: Deimos
// brand: Ergonom
// type: Enduro bikes
// price: 4972
var values = db.HashGet("bike:1", new RedisValue[] { "model", "price" });
Console.WriteLine(string.Join(" ", values));
// Deimos 4972
var newPrice = db.HashIncrement("bike:1", "price", 100);
Console.WriteLine($"New price: {newPrice}");
// New price: 5072
newPrice = db.HashIncrement("bike:1", "price", -100);
Console.WriteLine($"New price: {newPrice}");
// New price: 4972
var rides = db.HashIncrement("bike:1", "rides");
Console.WriteLine($"Rides: {rides}");
// Rides: 1
rides = db.HashIncrement("bike:1", "rides");
Console.WriteLine($"Rides: {rides}");
// Rides: 2
rides = db.HashIncrement("bike:1", "rides");
Console.WriteLine($"Rides: {rides}");
// Rides: 3
var crashes = db.HashIncrement("bike:1", "crashes");
Console.WriteLine($"Crashes: {crashes}");
// Crashes: 1
var owners = db.HashIncrement("bike:1", "owners");
Console.WriteLine($"Owners: {owners}");
// Owners: 1
var stats = db.HashGet("bike:1", new RedisValue[] { "crashes", "owners" });
Console.WriteLine($"Bike stats: crashes={stats[0]}, owners={stats[1]}");
// Bike stats: crashes=1, owners=1
}
}
There are commands that are able to perform operations on individual fields
as well, like HINCRBY
:
> HINCRBY bike:1 price 100
(integer) 5072
> HINCRBY bike:1 price -100
(integer) 4972
"""
Code samples for Hash doc pages:
https://redis.io/docs/latest/develop/data-types/hashes/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.hset(
"bike:1",
mapping={
"model": "Deimos",
"brand": "Ergonom",
"type": "Enduro bikes",
"price": 4972,
},
)
print(res1)
# >>> 4
res2 = r.hget("bike:1", "model")
print(res2)
# >>> 'Deimos'
res3 = r.hget("bike:1", "price")
print(res3)
# >>> '4972'
res4 = r.hgetall("bike:1")
print(res4)
# >>> {'model': 'Deimos', 'brand': 'Ergonom', 'type': 'Enduro bikes', 'price': '4972'}
res5 = r.hmget("bike:1", ["model", "price"])
print(res5)
# >>> ['Deimos', '4972']
res6 = r.hincrby("bike:1", "price", 100)
print(res6)
# >>> 5072
res7 = r.hincrby("bike:1", "price", -100)
print(res7)
# >>> 4972
res11 = r.hincrby("bike:1:stats", "rides", 1)
print(res11)
# >>> 1
res12 = r.hincrby("bike:1:stats", "rides", 1)
print(res12)
# >>> 2
res13 = r.hincrby("bike:1:stats", "rides", 1)
print(res13)
# >>> 3
res14 = r.hincrby("bike:1:stats", "crashes", 1)
print(res14)
# >>> 1
res15 = r.hincrby("bike:1:stats", "owners", 1)
print(res15)
# >>> 1
res16 = r.hget("bike:1:stats", "rides")
print(res16)
# >>> 3
res17 = r.hmget("bike:1:stats", ["crashes", "owners"])
print(res17)
# >>> ['1', '1']
import assert from 'assert';
import { createClient } from 'redis';
const client = createClient();
await client.connect();
const res1 = await client.hSet(
'bike:1',
{
'model': 'Deimos',
'brand': 'Ergonom',
'type': 'Enduro bikes',
'price': 4972,
}
)
console.log(res1) // 4
const res2 = await client.hGet('bike:1', 'model')
console.log(res2) // 'Deimos'
const res3 = await client.hGet('bike:1', 'price')
console.log(res3) // '4972'
const res4 = await client.hGetAll('bike:1')
console.log(res4)
/*
{
brand: 'Ergonom',
model: 'Deimos',
price: '4972',
type: 'Enduro bikes'
}
*/
const res5 = await client.hmGet('bike:1', ['model', 'price'])
console.log(res5) // ['Deimos', '4972']
const res6 = await client.hIncrBy('bike:1', 'price', 100)
console.log(res6) // 5072
const res7 = await client.hIncrBy('bike:1', 'price', -100)
console.log(res7) // 4972
const res11 = await client.hIncrBy('bike:1:stats', 'rides', 1)
console.log(res11) // 1
const res12 = await client.hIncrBy('bike:1:stats', 'rides', 1)
console.log(res12) // 2
const res13 = await client.hIncrBy('bike:1:stats', 'rides', 1)
console.log(res13) // 3
const res14 = await client.hIncrBy('bike:1:stats', 'crashes', 1)
console.log(res14) // 1
const res15 = await client.hIncrBy('bike:1:stats', 'owners', 1)
console.log(res15) // 1
const res16 = await client.hGet('bike:1:stats', 'rides')
console.log(res16) // 3
const res17 = await client.hmGet('bike:1:stats', ['crashes', 'owners'])
console.log(res17) // ['1', '1']
package io.redis.examples;
import redis.clients.jedis.UnifiedJedis;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HashExample {
public void run() {
try (UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379")) {
Map<String, String> bike1 = new HashMap<>();
bike1.put("model", "Deimos");
bike1.put("brand", "Ergonom");
bike1.put("type", "Enduro bikes");
bike1.put("price", "4972");
Long res1 = jedis.hset("bike:1", bike1);
System.out.println(res1); // 4
String res2 = jedis.hget("bike:1", "model");
System.out.println(res2); // Deimos
String res3 = jedis.hget("bike:1", "price");
System.out.println(res3); // 4972
Map<String, String> res4 = jedis.hgetAll("bike:1");
System.out.println(res4); // {type=Enduro bikes, brand=Ergonom, price=4972, model=Deimos}
List<String> res5 = jedis.hmget("bike:1", "model", "price");
System.out.println(res5); // [Deimos, 4972]
Long res6 = jedis.hincrBy("bike:1", "price", 100);
System.out.println(res6); // 5072
Long res7 = jedis.hincrBy("bike:1", "price", -100);
System.out.println(res7); // 4972
Long res8 = jedis.hincrBy("bike:1:stats", "rides", 1);
System.out.println(res8); // 1
Long res9 = jedis.hincrBy("bike:1:stats", "rides", 1);
System.out.println(res9); // 2
Long res10 = jedis.hincrBy("bike:1:stats", "rides", 1);
System.out.println(res10); // 3
Long res11 = jedis.hincrBy("bike:1:stats", "crashes", 1);
System.out.println(res11); // 1
Long res12 = jedis.hincrBy("bike:1:stats", "owners", 1);
System.out.println(res12); // 1
String res13 = jedis.hget("bike:1:stats", "rides");
System.out.println(res13); // 3
List<String> res14 = jedis.hmget("bike:1:stats", "crashes", "owners");
System.out.println(res14); // [1, 1]
}
}
}
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 HashExample {
public void run() {
RedisClient redisClient = RedisClient.create("redis://localhost:6379");
try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
RedisAsyncCommands<String, String> asyncCommands = connection.async();
Map<String, String> bike1 = new HashMap<>();
bike1.put("model", "Deimos");
bike1.put("brand", "Ergonom");
bike1.put("type", "Enduro bikes");
bike1.put("price", "4972");
CompletableFuture<Void> setGetAll = asyncCommands.hset("bike:1", bike1).thenCompose(res1 -> {
System.out.println(res1); // >>> 4
return asyncCommands.hget("bike:1", "model");
}).thenCompose(res2 -> {
System.out.println(res2); // >>> Deimos
return asyncCommands.hget("bike:1", "price");
}).thenCompose(res3 -> {
System.out.println(res3); // >>> 4972
return asyncCommands.hgetall("bike:1");
})
.thenAccept(System.out::println)
// >>> {type=Enduro bikes, brand=Ergonom, price=4972, model=Deimos}
.toCompletableFuture();
CompletableFuture<Void> hmGet = setGetAll.thenCompose(res4 -> {
return asyncCommands.hmget("bike:1", "model", "price");
})
.thenAccept(System.out::println)
// [KeyValue[model, Deimos], KeyValue[price, 4972]]
.toCompletableFuture();
CompletableFuture<Void> hIncrBy = hmGet.thenCompose(r -> {
return asyncCommands.hincrby("bike:1", "price", 100);
}).thenCompose(res6 -> {
System.out.println(res6); // >>> 5072
return asyncCommands.hincrby("bike:1", "price", -100);
})
.thenAccept(System.out::println)
// >>> 4972
.toCompletableFuture();
CompletableFuture<Void> incrByGetMget = asyncCommands.hincrby("bike:1:stats", "rides", 1).thenCompose(res7 -> {
System.out.println(res7); // >>> 1
return asyncCommands.hincrby("bike:1:stats", "rides", 1);
}).thenCompose(res8 -> {
System.out.println(res8); // >>> 2
return asyncCommands.hincrby("bike:1:stats", "rides", 1);
}).thenCompose(res9 -> {
System.out.println(res9); // >>> 3
return asyncCommands.hincrby("bike:1:stats", "crashes", 1);
}).thenCompose(res10 -> {
System.out.println(res10); // >>> 1
return asyncCommands.hincrby("bike:1:stats", "owners", 1);
}).thenCompose(res11 -> {
System.out.println(res11); // >>> 1
return asyncCommands.hget("bike:1:stats", "rides");
}).thenCompose(res12 -> {
System.out.println(res12); // >>> 3
return asyncCommands.hmget("bike:1:stats", "crashes", "owners");
})
.thenAccept(System.out::println)
// >>> [KeyValue[crashes, 1], KeyValue[owners, 1]]
.toCompletableFuture();
CompletableFuture.allOf(
hIncrBy, incrByGetMget).join();
} finally {
redisClient.shutdown();
}
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_set_get_all() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
hashFields := []string{
"model", "Deimos",
"brand", "Ergonom",
"type", "Enduro bikes",
"price", "4972",
}
res1, err := rdb.HSet(ctx, "bike:1", hashFields).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> 4
res2, err := rdb.HGet(ctx, "bike:1", "model").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> Deimos
res3, err := rdb.HGet(ctx, "bike:1", "price").Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> 4972
cmdReturn := rdb.HGetAll(ctx, "bike:1")
res4, err := cmdReturn.Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> map[brand:Ergonom model:Deimos price:4972 type:Enduro bikes]
type BikeInfo struct {
Model string `redis:"model"`
Brand string `redis:"brand"`
Type string `redis:"type"`
Price int `redis:"price"`
}
var res4a BikeInfo
if err := cmdReturn.Scan(&res4a); err != nil {
panic(err)
}
fmt.Printf("Model: %v, Brand: %v, Type: %v, Price: $%v\n",
res4a.Model, res4a.Brand, res4a.Type, res4a.Price)
// >>> Model: Deimos, Brand: Ergonom, Type: Enduro bikes, Price: $4972
}
func ExampleClient_hmget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
hashFields := []string{
"model", "Deimos",
"brand", "Ergonom",
"type", "Enduro bikes",
"price", "4972",
}
_, err := rdb.HSet(ctx, "bike:1", hashFields).Result()
if err != nil {
panic(err)
}
cmdReturn := rdb.HMGet(ctx, "bike:1", "model", "price")
res5, err := cmdReturn.Result()
if err != nil {
panic(err)
}
fmt.Println(res5) // >>> [Deimos 4972]
type BikeInfo struct {
Model string `redis:"model"`
Brand string `redis:"-"`
Type string `redis:"-"`
Price int `redis:"price"`
}
var res5a BikeInfo
if err := cmdReturn.Scan(&res5a); err != nil {
panic(err)
}
fmt.Printf("Model: %v, Price: $%v\n", res5a.Model, res5a.Price)
// >>> Model: Deimos, Price: $4972
}
func ExampleClient_hincrby() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
hashFields := []string{
"model", "Deimos",
"brand", "Ergonom",
"type", "Enduro bikes",
"price", "4972",
}
_, err := rdb.HSet(ctx, "bike:1", hashFields).Result()
if err != nil {
panic(err)
}
res6, err := rdb.HIncrBy(ctx, "bike:1", "price", 100).Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> 5072
res7, err := rdb.HIncrBy(ctx, "bike:1", "price", -100).Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> 4972
}
func ExampleClient_incrby_get_mget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res8, err := rdb.HIncrBy(ctx, "bike:1:stats", "rides", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> 1
res9, err := rdb.HIncrBy(ctx, "bike:1:stats", "rides", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> 2
res10, err := rdb.HIncrBy(ctx, "bike:1:stats", "rides", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> 3
res11, err := rdb.HIncrBy(ctx, "bike:1:stats", "crashes", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> 1
res12, err := rdb.HIncrBy(ctx, "bike:1:stats", "owners", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> 1
res13, err := rdb.HGet(ctx, "bike:1:stats", "rides").Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> 3
res14, err := rdb.HMGet(ctx, "bike:1:stats", "crashes", "owners").Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> [1 1]
}
using NRedisStack.Tests;
using StackExchange.Redis;
public class HashExample
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
db.KeyDelete("bike:1");
db.HashSet("bike:1", new HashEntry[]
{
new HashEntry("model", "Deimos"),
new HashEntry("brand", "Ergonom"),
new HashEntry("type", "Enduro bikes"),
new HashEntry("price", 4972)
});
Console.WriteLine("Hash Created");
// Hash Created
var model = db.HashGet("bike:1", "model");
Console.WriteLine($"Model: {model}");
// Model: Deimos
var price = db.HashGet("bike:1", "price");
Console.WriteLine($"Price: {price}");
// Price: 4972
var bike = db.HashGetAll("bike:1");
Console.WriteLine("bike:1");
Console.WriteLine(string.Join("\n", bike.Select(b => $"{b.Name}: {b.Value}")));
// Bike:1:
// model: Deimos
// brand: Ergonom
// type: Enduro bikes
// price: 4972
var values = db.HashGet("bike:1", new RedisValue[] { "model", "price" });
Console.WriteLine(string.Join(" ", values));
// Deimos 4972
var newPrice = db.HashIncrement("bike:1", "price", 100);
Console.WriteLine($"New price: {newPrice}");
// New price: 5072
newPrice = db.HashIncrement("bike:1", "price", -100);
Console.WriteLine($"New price: {newPrice}");
// New price: 4972
var rides = db.HashIncrement("bike:1", "rides");
Console.WriteLine($"Rides: {rides}");
// Rides: 1
rides = db.HashIncrement("bike:1", "rides");
Console.WriteLine($"Rides: {rides}");
// Rides: 2
rides = db.HashIncrement("bike:1", "rides");
Console.WriteLine($"Rides: {rides}");
// Rides: 3
var crashes = db.HashIncrement("bike:1", "crashes");
Console.WriteLine($"Crashes: {crashes}");
// Crashes: 1
var owners = db.HashIncrement("bike:1", "owners");
Console.WriteLine($"Owners: {owners}");
// Owners: 1
var stats = db.HashGet("bike:1", new RedisValue[] { "crashes", "owners" });
Console.WriteLine($"Bike stats: crashes={stats[0]}, owners={stats[1]}");
// Bike stats: crashes=1, owners=1
}
}
You can find the full list of hash commands in the documentation.
It is worth noting that small hashes (i.e., a few elements with small values) are encoded in special way in memory that make them very memory efficient.
Basic commands
HSET
: sets the value of one or more fields on a hash.HGET
: returns the value at a given field.HMGET
: returns the values at one or more given fields.HINCRBY
: increments the value at a given field by the integer provided.
See the complete list of hash commands.
Examples
- Store counters for the number of times bike:1 has been ridden, has crashed, or has changed owners:
> HINCRBY bike:1:stats rides 1 (integer) 1 > HINCRBY bike:1:stats rides 1 (integer) 2 > HINCRBY bike:1:stats rides 1 (integer) 3 > HINCRBY bike:1:stats crashes 1 (integer) 1 > HINCRBY bike:1:stats owners 1 (integer) 1 > HGET bike:1:stats rides "3" > HMGET bike:1:stats owners crashes 1) "1" 2) "1"
Are you tired of using redis-cli? Try Redis Insight - the developer GUI for Redis.""" Code samples for Hash doc pages: https://redis.io/docs/latest/develop/data-types/hashes/ """ import redis r = redis.Redis(decode_responses=True) res1 = r.hset( "bike:1", mapping={ "model": "Deimos", "brand": "Ergonom", "type": "Enduro bikes", "price": 4972, }, ) print(res1) # >>> 4 res2 = r.hget("bike:1", "model") print(res2) # >>> 'Deimos' res3 = r.hget("bike:1", "price") print(res3) # >>> '4972' res4 = r.hgetall("bike:1") print(res4) # >>> {'model': 'Deimos', 'brand': 'Ergonom', 'type': 'Enduro bikes', 'price': '4972'} res5 = r.hmget("bike:1", ["model", "price"]) print(res5) # >>> ['Deimos', '4972'] res6 = r.hincrby("bike:1", "price", 100) print(res6) # >>> 5072 res7 = r.hincrby("bike:1", "price", -100) print(res7) # >>> 4972 res11 = r.hincrby("bike:1:stats", "rides", 1) print(res11) # >>> 1 res12 = r.hincrby("bike:1:stats", "rides", 1) print(res12) # >>> 2 res13 = r.hincrby("bike:1:stats", "rides", 1) print(res13) # >>> 3 res14 = r.hincrby("bike:1:stats", "crashes", 1) print(res14) # >>> 1 res15 = r.hincrby("bike:1:stats", "owners", 1) print(res15) # >>> 1 res16 = r.hget("bike:1:stats", "rides") print(res16) # >>> 3 res17 = r.hmget("bike:1:stats", ["crashes", "owners"]) print(res17) # >>> ['1', '1']
import assert from 'assert'; import { createClient } from 'redis'; const client = createClient(); await client.connect(); const res1 = await client.hSet( 'bike:1', { 'model': 'Deimos', 'brand': 'Ergonom', 'type': 'Enduro bikes', 'price': 4972, } ) console.log(res1) // 4 const res2 = await client.hGet('bike:1', 'model') console.log(res2) // 'Deimos' const res3 = await client.hGet('bike:1', 'price') console.log(res3) // '4972' const res4 = await client.hGetAll('bike:1') console.log(res4) /* { brand: 'Ergonom', model: 'Deimos', price: '4972', type: 'Enduro bikes' } */ const res5 = await client.hmGet('bike:1', ['model', 'price']) console.log(res5) // ['Deimos', '4972'] const res6 = await client.hIncrBy('bike:1', 'price', 100) console.log(res6) // 5072 const res7 = await client.hIncrBy('bike:1', 'price', -100) console.log(res7) // 4972 const res11 = await client.hIncrBy('bike:1:stats', 'rides', 1) console.log(res11) // 1 const res12 = await client.hIncrBy('bike:1:stats', 'rides', 1) console.log(res12) // 2 const res13 = await client.hIncrBy('bike:1:stats', 'rides', 1) console.log(res13) // 3 const res14 = await client.hIncrBy('bike:1:stats', 'crashes', 1) console.log(res14) // 1 const res15 = await client.hIncrBy('bike:1:stats', 'owners', 1) console.log(res15) // 1 const res16 = await client.hGet('bike:1:stats', 'rides') console.log(res16) // 3 const res17 = await client.hmGet('bike:1:stats', ['crashes', 'owners']) console.log(res17) // ['1', '1']
package io.redis.examples; import redis.clients.jedis.UnifiedJedis; import java.util.HashMap; import java.util.List; import java.util.Map; public class HashExample { public void run() { try (UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379")) { Map<String, String> bike1 = new HashMap<>(); bike1.put("model", "Deimos"); bike1.put("brand", "Ergonom"); bike1.put("type", "Enduro bikes"); bike1.put("price", "4972"); Long res1 = jedis.hset("bike:1", bike1); System.out.println(res1); // 4 String res2 = jedis.hget("bike:1", "model"); System.out.println(res2); // Deimos String res3 = jedis.hget("bike:1", "price"); System.out.println(res3); // 4972 Map<String, String> res4 = jedis.hgetAll("bike:1"); System.out.println(res4); // {type=Enduro bikes, brand=Ergonom, price=4972, model=Deimos} List<String> res5 = jedis.hmget("bike:1", "model", "price"); System.out.println(res5); // [Deimos, 4972] Long res6 = jedis.hincrBy("bike:1", "price", 100); System.out.println(res6); // 5072 Long res7 = jedis.hincrBy("bike:1", "price", -100); System.out.println(res7); // 4972 Long res8 = jedis.hincrBy("bike:1:stats", "rides", 1); System.out.println(res8); // 1 Long res9 = jedis.hincrBy("bike:1:stats", "rides", 1); System.out.println(res9); // 2 Long res10 = jedis.hincrBy("bike:1:stats", "rides", 1); System.out.println(res10); // 3 Long res11 = jedis.hincrBy("bike:1:stats", "crashes", 1); System.out.println(res11); // 1 Long res12 = jedis.hincrBy("bike:1:stats", "owners", 1); System.out.println(res12); // 1 String res13 = jedis.hget("bike:1:stats", "rides"); System.out.println(res13); // 3 List<String> res14 = jedis.hmget("bike:1:stats", "crashes", "owners"); System.out.println(res14); // [1, 1] } } }
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 HashExample { public void run() { RedisClient redisClient = RedisClient.create("redis://localhost:6379"); try (StatefulRedisConnection<String, String> connection = redisClient.connect()) { RedisAsyncCommands<String, String> asyncCommands = connection.async(); Map<String, String> bike1 = new HashMap<>(); bike1.put("model", "Deimos"); bike1.put("brand", "Ergonom"); bike1.put("type", "Enduro bikes"); bike1.put("price", "4972"); CompletableFuture<Void> setGetAll = asyncCommands.hset("bike:1", bike1).thenCompose(res1 -> { System.out.println(res1); // >>> 4 return asyncCommands.hget("bike:1", "model"); }).thenCompose(res2 -> { System.out.println(res2); // >>> Deimos return asyncCommands.hget("bike:1", "price"); }).thenCompose(res3 -> { System.out.println(res3); // >>> 4972 return asyncCommands.hgetall("bike:1"); }) .thenAccept(System.out::println) // >>> {type=Enduro bikes, brand=Ergonom, price=4972, model=Deimos} .toCompletableFuture(); CompletableFuture<Void> hmGet = setGetAll.thenCompose(res4 -> { return asyncCommands.hmget("bike:1", "model", "price"); }) .thenAccept(System.out::println) // [KeyValue[model, Deimos], KeyValue[price, 4972]] .toCompletableFuture(); CompletableFuture<Void> hIncrBy = hmGet.thenCompose(r -> { return asyncCommands.hincrby("bike:1", "price", 100); }).thenCompose(res6 -> { System.out.println(res6); // >>> 5072 return asyncCommands.hincrby("bike:1", "price", -100); }) .thenAccept(System.out::println) // >>> 4972 .toCompletableFuture(); CompletableFuture<Void> incrByGetMget = asyncCommands.hincrby("bike:1:stats", "rides", 1).thenCompose(res7 -> { System.out.println(res7); // >>> 1 return asyncCommands.hincrby("bike:1:stats", "rides", 1); }).thenCompose(res8 -> { System.out.println(res8); // >>> 2 return asyncCommands.hincrby("bike:1:stats", "rides", 1); }).thenCompose(res9 -> { System.out.println(res9); // >>> 3 return asyncCommands.hincrby("bike:1:stats", "crashes", 1); }).thenCompose(res10 -> { System.out.println(res10); // >>> 1 return asyncCommands.hincrby("bike:1:stats", "owners", 1); }).thenCompose(res11 -> { System.out.println(res11); // >>> 1 return asyncCommands.hget("bike:1:stats", "rides"); }).thenCompose(res12 -> { System.out.println(res12); // >>> 3 return asyncCommands.hmget("bike:1:stats", "crashes", "owners"); }) .thenAccept(System.out::println) // >>> [KeyValue[crashes, 1], KeyValue[owners, 1]] .toCompletableFuture(); CompletableFuture.allOf( hIncrBy, incrByGetMget).join(); } finally { redisClient.shutdown(); } } }
package example_commands_test import ( "context" "fmt" "github.com/redis/go-redis/v9" ) func ExampleClient_set_get_all() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password docs DB: 0, // use default DB }) hashFields := []string{ "model", "Deimos", "brand", "Ergonom", "type", "Enduro bikes", "price", "4972", } res1, err := rdb.HSet(ctx, "bike:1", hashFields).Result() if err != nil { panic(err) } fmt.Println(res1) // >>> 4 res2, err := rdb.HGet(ctx, "bike:1", "model").Result() if err != nil { panic(err) } fmt.Println(res2) // >>> Deimos res3, err := rdb.HGet(ctx, "bike:1", "price").Result() if err != nil { panic(err) } fmt.Println(res3) // >>> 4972 cmdReturn := rdb.HGetAll(ctx, "bike:1") res4, err := cmdReturn.Result() if err != nil { panic(err) } fmt.Println(res4) // >>> map[brand:Ergonom model:Deimos price:4972 type:Enduro bikes] type BikeInfo struct { Model string `redis:"model"` Brand string `redis:"brand"` Type string `redis:"type"` Price int `redis:"price"` } var res4a BikeInfo if err := cmdReturn.Scan(&res4a); err != nil { panic(err) } fmt.Printf("Model: %v, Brand: %v, Type: %v, Price: $%v\n", res4a.Model, res4a.Brand, res4a.Type, res4a.Price) // >>> Model: Deimos, Brand: Ergonom, Type: Enduro bikes, Price: $4972 } func ExampleClient_hmget() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password docs DB: 0, // use default DB }) hashFields := []string{ "model", "Deimos", "brand", "Ergonom", "type", "Enduro bikes", "price", "4972", } _, err := rdb.HSet(ctx, "bike:1", hashFields).Result() if err != nil { panic(err) } cmdReturn := rdb.HMGet(ctx, "bike:1", "model", "price") res5, err := cmdReturn.Result() if err != nil { panic(err) } fmt.Println(res5) // >>> [Deimos 4972] type BikeInfo struct { Model string `redis:"model"` Brand string `redis:"-"` Type string `redis:"-"` Price int `redis:"price"` } var res5a BikeInfo if err := cmdReturn.Scan(&res5a); err != nil { panic(err) } fmt.Printf("Model: %v, Price: $%v\n", res5a.Model, res5a.Price) // >>> Model: Deimos, Price: $4972 } func ExampleClient_hincrby() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password docs DB: 0, // use default DB }) hashFields := []string{ "model", "Deimos", "brand", "Ergonom", "type", "Enduro bikes", "price", "4972", } _, err := rdb.HSet(ctx, "bike:1", hashFields).Result() if err != nil { panic(err) } res6, err := rdb.HIncrBy(ctx, "bike:1", "price", 100).Result() if err != nil { panic(err) } fmt.Println(res6) // >>> 5072 res7, err := rdb.HIncrBy(ctx, "bike:1", "price", -100).Result() if err != nil { panic(err) } fmt.Println(res7) // >>> 4972 } func ExampleClient_incrby_get_mget() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password docs DB: 0, // use default DB }) res8, err := rdb.HIncrBy(ctx, "bike:1:stats", "rides", 1).Result() if err != nil { panic(err) } fmt.Println(res8) // >>> 1 res9, err := rdb.HIncrBy(ctx, "bike:1:stats", "rides", 1).Result() if err != nil { panic(err) } fmt.Println(res9) // >>> 2 res10, err := rdb.HIncrBy(ctx, "bike:1:stats", "rides", 1).Result() if err != nil { panic(err) } fmt.Println(res10) // >>> 3 res11, err := rdb.HIncrBy(ctx, "bike:1:stats", "crashes", 1).Result() if err != nil { panic(err) } fmt.Println(res11) // >>> 1 res12, err := rdb.HIncrBy(ctx, "bike:1:stats", "owners", 1).Result() if err != nil { panic(err) } fmt.Println(res12) // >>> 1 res13, err := rdb.HGet(ctx, "bike:1:stats", "rides").Result() if err != nil { panic(err) } fmt.Println(res13) // >>> 3 res14, err := rdb.HMGet(ctx, "bike:1:stats", "crashes", "owners").Result() if err != nil { panic(err) } fmt.Println(res14) // >>> [1 1] }
using NRedisStack.Tests; using StackExchange.Redis; public class HashExample { public void run() { var muxer = ConnectionMultiplexer.Connect("localhost:6379"); var db = muxer.GetDatabase(); db.KeyDelete("bike:1"); db.HashSet("bike:1", new HashEntry[] { new HashEntry("model", "Deimos"), new HashEntry("brand", "Ergonom"), new HashEntry("type", "Enduro bikes"), new HashEntry("price", 4972) }); Console.WriteLine("Hash Created"); // Hash Created var model = db.HashGet("bike:1", "model"); Console.WriteLine($"Model: {model}"); // Model: Deimos var price = db.HashGet("bike:1", "price"); Console.WriteLine($"Price: {price}"); // Price: 4972 var bike = db.HashGetAll("bike:1"); Console.WriteLine("bike:1"); Console.WriteLine(string.Join("\n", bike.Select(b => $"{b.Name}: {b.Value}"))); // Bike:1: // model: Deimos // brand: Ergonom // type: Enduro bikes // price: 4972 var values = db.HashGet("bike:1", new RedisValue[] { "model", "price" }); Console.WriteLine(string.Join(" ", values)); // Deimos 4972 var newPrice = db.HashIncrement("bike:1", "price", 100); Console.WriteLine($"New price: {newPrice}"); // New price: 5072 newPrice = db.HashIncrement("bike:1", "price", -100); Console.WriteLine($"New price: {newPrice}"); // New price: 4972 var rides = db.HashIncrement("bike:1", "rides"); Console.WriteLine($"Rides: {rides}"); // Rides: 1 rides = db.HashIncrement("bike:1", "rides"); Console.WriteLine($"Rides: {rides}"); // Rides: 2 rides = db.HashIncrement("bike:1", "rides"); Console.WriteLine($"Rides: {rides}"); // Rides: 3 var crashes = db.HashIncrement("bike:1", "crashes"); Console.WriteLine($"Crashes: {crashes}"); // Crashes: 1 var owners = db.HashIncrement("bike:1", "owners"); Console.WriteLine($"Owners: {owners}"); // Owners: 1 var stats = db.HashGet("bike:1", new RedisValue[] { "crashes", "owners" }); Console.WriteLine($"Bike stats: crashes={stats[0]}, owners={stats[1]}"); // Bike stats: crashes=1, owners=1 } }
Field expiration
New in Redis Community Edition 7.4 is the ability to specify an expiration time or a time-to-live (TTL) value for individual hash fields. This capability is comparable to key expiration and includes a number of similar commands.
Use the following commands to set either an exact expiration time or a TTL value for specific fields:
HEXPIRE
: set the remaining TTL in seconds.HPEXPIRE
: set the remaining TTL in milliseconds.HEXPIREAT
: set the expiration time to a timestamp1 specified in seconds.HPEXPIREAT
: set the expiration time to a timestamp specified in milliseconds.
Use the following commands to retrieve either the exact time when or the remaining TTL until specific fields will expire:
HEXPIRETIME
: get the expiration time as a timestamp in seconds.HPEXPIRETIME
: get the expiration time as a timestamp in milliseconds.HTTL
: get the remaining TTL in seconds.HPTTL
: get the remaining TTL in milliseconds.
Use the following command to remove the expiration of specific fields:
HPERSIST
: remove the expiration.
Common field expiration use cases
-
Event Tracking: Use a hash key to store events from the last hour. Set each event's TTL to one hour. Use
HLEN
to count events from the past hour. -
Fraud Detection: Create a hash with hourly counters for events. Set each field's TTL to 48 hours. Query the hash to get the number of events per hour for the last 48 hours.
-
Customer Session Management: Store customer data in hash keys. Create a new hash key for each session and add a session field to the customer’s hash key. Expire both the session key and the session field in the customer’s hash key automatically when the session expires.
-
Active Session Tracking: Store all active sessions in a hash key. Set each session's TTL to expire automatically after inactivity. Use
HLEN
to count active sessions.
Field expiration examples
Support for hash field expiration in the official client libraries is not yet available, but you can test hash field expiration now with beta versions of the Python (redis-py) and Java (Jedis) client libraries.
Following are some Python examples that demonstrate how to use field expiration.
Consider a hash data set for storing sensor data that has the following structure:
event = {
'air_quality': 256,
'battery_level':89
}
r.hset('sensor:sensor1', mapping=event)
In the examples below, you will likely need to refresh the sensor:sensor1
key after its fields expire.
Set and retrieve the TTL for multiple fields in a hash:
# set the TTL for two hash fields to 60 seconds
r.hexpire('sensor:sensor1', 60, 'air_quality', 'battery_level')
ttl = r.httl('sensor:sensor1', 'air_quality', 'battery_level')
print(ttl)
# prints [60, 60]
Set and retrieve a hash field's TTL in milliseconds:
# set the TTL of the 'air_quality' field in milliseconds
r.hpexpire('sensor:sensor1', 60000, 'air_quality')
# and retrieve it
pttl = r.hpttl('sensor:sensor1', 'air_quality')
print(pttl)
# prints [59994] # your actual value may vary
Set and retrieve a hash field’s expiration timestamp:
# set the expiration of 'air_quality' to now + 24 hours
# (similar to setting the TTL to 24 hours)
r.hexpireat('sensor:sensor1',
datetime.now() + timedelta(hours=24),
'air_quality')
# and retrieve it
expire_time = r.hexpiretime('sensor:sensor1', 'air_quality')
print(expire_time)
# prints [1717668041] # your actual value may vary
Performance
Most Redis hash commands are O(1).
A few commands, such as HKEYS
, HVALS
, HGETALL
, and most of the expiration-related commands, are O(n), where n is the number of field-value pairs.
Limits
Every hash can store up to 4,294,967,295 (2^32 - 1) field-value pairs. In practice, your hashes are limited only by the overall memory on the VMs hosting your Redis deployment.
Learn more
- Redis Hashes Explained is a short, comprehensive video explainer covering Redis hashes.
- Redis University's RU101 covers Redis hashes in detail.
-
all timestamps are specified in seconds or milliseconds since the Unix epoch. ↩︎