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"
using NRedisStack.Tests;
using StackExchange.Redis;
public class HashExample
{
[SkipIfRedis(Is.OSSCluster)]
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
}
}
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]
}
}
}
import { createClient } from 'redis';
const client = createClient();
client.on('error', err => console.log('Redis Client Error', err));
await client.connect();
const fieldsAdded = await client.hSet(
'bike:1',
{
model: 'Deimos',
brand: 'Ergonom',
type: 'Enduro bikes',
price: 4972,
},
)
console.log(`Number of fields were added: ${fieldsAdded}`);
// Number of fields were added: 4
const model = await client.hGet('bike:1', 'model');
console.log(`Model: ${model}`);
// Model: Deimos
const price = await client.hGet('bike:1', 'price');
console.log(`Price: ${price}`);
// Price: 4972
const bike = await client.hGetAll('bike:1');
console.log(bike);
// {
// model: 'Deimos',
// brand: 'Ergonom',
// type: 'Enduro bikes',
// price: '4972'
// }
const fields = await client.hmGet('bike:1', ['model', 'price']);
console.log(fields);
// [ 'Deimos', '4972' ]
let newPrice = await client.hIncrBy('bike:1', 'price', 100);
console.log(newPrice);
// 5072
newPrice = await client.hIncrBy('bike:1', 'price', -100);
console.log(newPrice);
// 4972
let rides = await client.hIncrBy('bike:1:stats', 'rides', 1);
console.log(rides);
// 1
rides = await client.hIncrBy('bike:1:stats', 'rides', 1);
console.log(rides);
// 2
rides = await client.hIncrBy('bike:1:stats', 'rides', 1);
console.log(rides);
// 3
let crashes = await client.hIncrBy('bike:1:stats', 'crashes', 1);
console.log(crashes);
// 1
let owners = await client.hIncrBy('bike:1:stats', 'owners', 1);
console.log(owners);
// 1
rides = await client.hGet('bike:1:stats', 'rides');
console.log(`Total rides: ${rides}`);
// Total rides: 3
const stats = await client.hmGet('bike:1:stats', ['crashes', 'owners']);
console.log(`Bike stats: crashes=${stats[0]}, owners=${stats[1]}`);
// Bike stats: crashes=1, owners=1
await client.quit();
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']
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)
using NRedisStack.Tests;
using StackExchange.Redis;
public class HashExample
{
[SkipIfRedis(Is.OSSCluster)]
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
}
}
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]
}
}
}
import { createClient } from 'redis';
const client = createClient();
client.on('error', err => console.log('Redis Client Error', err));
await client.connect();
const fieldsAdded = await client.hSet(
'bike:1',
{
model: 'Deimos',
brand: 'Ergonom',
type: 'Enduro bikes',
price: 4972,
},
)
console.log(`Number of fields were added: ${fieldsAdded}`);
// Number of fields were added: 4
const model = await client.hGet('bike:1', 'model');
console.log(`Model: ${model}`);
// Model: Deimos
const price = await client.hGet('bike:1', 'price');
console.log(`Price: ${price}`);
// Price: 4972
const bike = await client.hGetAll('bike:1');
console.log(bike);
// {
// model: 'Deimos',
// brand: 'Ergonom',
// type: 'Enduro bikes',
// price: '4972'
// }
const fields = await client.hmGet('bike:1', ['model', 'price']);
console.log(fields);
// [ 'Deimos', '4972' ]
let newPrice = await client.hIncrBy('bike:1', 'price', 100);
console.log(newPrice);
// 5072
newPrice = await client.hIncrBy('bike:1', 'price', -100);
console.log(newPrice);
// 4972
let rides = await client.hIncrBy('bike:1:stats', 'rides', 1);
console.log(rides);
// 1
rides = await client.hIncrBy('bike:1:stats', 'rides', 1);
console.log(rides);
// 2
rides = await client.hIncrBy('bike:1:stats', 'rides', 1);
console.log(rides);
// 3
let crashes = await client.hIncrBy('bike:1:stats', 'crashes', 1);
console.log(crashes);
// 1
let owners = await client.hIncrBy('bike:1:stats', 'owners', 1);
console.log(owners);
// 1
rides = await client.hGet('bike:1:stats', 'rides');
console.log(`Total rides: ${rides}`);
// Total rides: 3
const stats = await client.hmGet('bike:1:stats', ['crashes', 'owners']);
console.log(`Bike stats: crashes=${stats[0]}, owners=${stats[1]}`);
// Bike stats: crashes=1, owners=1
await client.quit();
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']
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
using NRedisStack.Tests;
using StackExchange.Redis;
public class HashExample
{
[SkipIfRedis(Is.OSSCluster)]
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
}
}
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]
}
}
}
import { createClient } from 'redis';
const client = createClient();
client.on('error', err => console.log('Redis Client Error', err));
await client.connect();
const fieldsAdded = await client.hSet(
'bike:1',
{
model: 'Deimos',
brand: 'Ergonom',
type: 'Enduro bikes',
price: 4972,
},
)
console.log(`Number of fields were added: ${fieldsAdded}`);
// Number of fields were added: 4
const model = await client.hGet('bike:1', 'model');
console.log(`Model: ${model}`);
// Model: Deimos
const price = await client.hGet('bike:1', 'price');
console.log(`Price: ${price}`);
// Price: 4972
const bike = await client.hGetAll('bike:1');
console.log(bike);
// {
// model: 'Deimos',
// brand: 'Ergonom',
// type: 'Enduro bikes',
// price: '4972'
// }
const fields = await client.hmGet('bike:1', ['model', 'price']);
console.log(fields);
// [ 'Deimos', '4972' ]
let newPrice = await client.hIncrBy('bike:1', 'price', 100);
console.log(newPrice);
// 5072
newPrice = await client.hIncrBy('bike:1', 'price', -100);
console.log(newPrice);
// 4972
let rides = await client.hIncrBy('bike:1:stats', 'rides', 1);
console.log(rides);
// 1
rides = await client.hIncrBy('bike:1:stats', 'rides', 1);
console.log(rides);
// 2
rides = await client.hIncrBy('bike:1:stats', 'rides', 1);
console.log(rides);
// 3
let crashes = await client.hIncrBy('bike:1:stats', 'crashes', 1);
console.log(crashes);
// 1
let owners = await client.hIncrBy('bike:1:stats', 'owners', 1);
console.log(owners);
// 1
rides = await client.hGet('bike:1:stats', 'rides');
console.log(`Total rides: ${rides}`);
// Total rides: 3
const stats = await client.hmGet('bike:1:stats', ['crashes', 'owners']);
console.log(`Bike stats: crashes=${stats[0]}, owners=${stats[1]}`);
// Bike stats: crashes=1, owners=1
await client.quit();
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']
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 RedisInsight - the developer GUI for Redis.using NRedisStack.Tests; using StackExchange.Redis; public class HashExample { [SkipIfRedis(Is.OSSCluster)] 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 } }
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] } } }
import { createClient } from 'redis'; const client = createClient(); client.on('error', err => console.log('Redis Client Error', err)); await client.connect(); const fieldsAdded = await client.hSet( 'bike:1', { model: 'Deimos', brand: 'Ergonom', type: 'Enduro bikes', price: 4972, }, ) console.log(`Number of fields were added: ${fieldsAdded}`); // Number of fields were added: 4 const model = await client.hGet('bike:1', 'model'); console.log(`Model: ${model}`); // Model: Deimos const price = await client.hGet('bike:1', 'price'); console.log(`Price: ${price}`); // Price: 4972 const bike = await client.hGetAll('bike:1'); console.log(bike); // { // model: 'Deimos', // brand: 'Ergonom', // type: 'Enduro bikes', // price: '4972' // } const fields = await client.hmGet('bike:1', ['model', 'price']); console.log(fields); // [ 'Deimos', '4972' ] let newPrice = await client.hIncrBy('bike:1', 'price', 100); console.log(newPrice); // 5072 newPrice = await client.hIncrBy('bike:1', 'price', -100); console.log(newPrice); // 4972 let rides = await client.hIncrBy('bike:1:stats', 'rides', 1); console.log(rides); // 1 rides = await client.hIncrBy('bike:1:stats', 'rides', 1); console.log(rides); // 2 rides = await client.hIncrBy('bike:1:stats', 'rides', 1); console.log(rides); // 3 let crashes = await client.hIncrBy('bike:1:stats', 'crashes', 1); console.log(crashes); // 1 let owners = await client.hIncrBy('bike:1:stats', 'owners', 1); console.log(owners); // 1 rides = await client.hGet('bike:1:stats', 'rides'); console.log(`Total rides: ${rides}`); // Total rides: 3 const stats = await client.hmGet('bike:1:stats', ['crashes', 'owners']); console.log(`Bike stats: crashes=${stats[0]}, owners=${stats[1]}`); // Bike stats: crashes=1, owners=1 await client.quit();
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']
Performance
Most Redis hash commands are O(1).
A few commands - such as HKEYS
, HVALS
, and HGETALL
- 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.