Redis as an in-memory data structure store quick start guide
Understand how to use basic Redis data types
This quick start guide shows you how to:
- Get started with Redis
- Store data under a key in Redis
- Retrieve data with a key from Redis
- Scan the keyspace for keys that match a specific pattern
The examples in this article refer to a simple bicycle inventory.
Setup
The easiest way to get started with Redis is to use Redis Cloud:
-
Create a free account.
👁 Image
-
Follow the instructions to create a free database.
You can alternatively follow the installation guides to install Redis on your local machine.
Connect
The first step is to connect to Redis. You can find further details about the connection options in this documentation site's Tools section. The following example shows how to connect to a Redis server that runs on localhost (-h 127.0.0.1) and listens on the default port (-p 6379):
> redis-cli -h 127.0.0.1 -p 6379- REDIS-CLI
r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)
- REDIS-CLI
const client = createClient();
client.on('error', err => console.log('Redis Client Error', err));
await client.connect();
- REDIS-CLI
RedisClientjedis=RedisClient.create("localhost",6379);- REDIS-CLI
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
Protocol: 2,
})
- REDIS-CLI
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
var ft = db.FT();
var json = db.JSON();
- REDIS-CLI
us-east-1 and listens on port 16379: redis-16379.c283.us-east-1-4.ec2.cloud.redislabs.com:16379. The connection string has the format host:port. You must also copy and paste the username and password of your Cloud database and then either pass the credentials to your client or use the AUTH command after the connection is established.Store and retrieve data
Redis stands for Remote Dictionary Server. You can use the same data types as in your local programming environment but on the server side within Redis.
Similar to byte arrays, Redis strings store sequences of bytes, including text, serialized objects, counter values, and binary arrays. The following example shows you how to set and get a string value:
SET bike:1 "Process 134"
GET bike:1"""
Code samples for data structure store quickstart pages:
https://redis.io/docs/latest/develop/get-started/data-store/
"""
import redis
r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)
res = r.set("bike:1", "Process 134")
print(res)
# >>> True
res = r.get("bike:1")
print(res)
# >>> "Process 134"
import { createClient } from 'redis';
const client = createClient();
client.on('error', err => console.log('Redis Client Error', err));
await client.connect().catch(console.error);
await client.set('bike:1', 'Process 134');
const value = await client.get('bike:1');
console.log(value);
// returns 'Process 134'
await client.close();
packageio.redis.examples;importredis.clients.jedis.RedisClient;publicclass SetGetExample{publicvoidrun(){RedisClientjedis=RedisClient.create("redis://localhost:6379");Stringstatus=jedis.set("bike:1","Process 134");if("OK".equals(status))System.out.println("Successfully added a bike.");Stringvalue=jedis.get("bike:1");if(value!=null)System.out.println("The name of the bike is: "+value+".");jedis.close();}}package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_Set_and_get() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
err := rdb.Set(ctx, "bike:1", "Process 134", 0).Err()
if err != nil {
panic(err)
}
fmt.Println("OK")
value, err := rdb.Get(ctx, "bike:1").Result()
if err != nil {
panic(err)
}
fmt.Printf("The name of the bike is %s", value)
}
using NRedisStack.Tests;
using StackExchange.Redis;
public class SetGetExample
{
public void Run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool status = db.StringSet("bike:1", "Process 134");
if (status)
Console.WriteLine("Successfully added a bike.");
var value = db.StringGet("bike:1");
if (value.HasValue)
Console.WriteLine("The name of the bike is: " + value + ".");
}
}
Hashes are the equivalent of dictionaries (dicts or hash maps). Among other things, you can use hashes to represent plain objects and to store groupings of counters. The following example explains how to set and access field values of an object:
> 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"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'}
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'
}
*/
Map<String,String>bike1=newHashMap<>();bike1.put("model","Deimos");bike1.put("brand","Ergonom");bike1.put("type","Enduro bikes");bike1.put("price","4972");Longres1=jedis.hset("bike:1",bike1);System.out.println(res1);// 4Stringres2=jedis.hget("bike:1","model");System.out.println(res2);// DeimosStringres3=jedis.hget("bike:1","price");System.out.println(res3);// 4972Map<String,String>res4=jedis.hgetAll("bike:1");System.out.println(res4);// {type=Enduro bikes, brand=Ergonom, price=4972, model=Deimos}-
Creates or modifies the value of a field in a hash.
-
hset(
- key: byte[],
- field: byte[],
- value: byte[]
-
hset(
- key: byte[],
- hash: Map<byte[], byte[]>
-
hset(
- key: String,
- field: String,
- value: String
-
hset(
- key: String,
- hash: Map<String, String>
-
hset(
Map<String,String>bike1=newHashMap<>();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);// >>> 4returnasyncCommands.hget("bike:1","model");}).thenCompose(res2->{System.out.println(res2);// >>> DeimosreturnasyncCommands.hget("bike:1","price");}).thenCompose(res3->{System.out.println(res3);// >>> 4972returnasyncCommands.hgetall("bike:1");}).thenAccept(System.out::println)// >>> {type=Enduro bikes, brand=Ergonom, price=4972, model=Deimos}.toCompletableFuture();-
Creates or modifies the value of a field in a hash.
-
hset(
- key: K, // the key of the hash.
- field: K,
- value: V
-
hset(
- key: K, // the key of the hash.
- map: Map<K, V> // the field/value pairs to update.
-
hset(
Map<String,String>bike1=newHashMap<>();bike1.put("model","Deimos");bike1.put("brand","Ergonom");bike1.put("type","Enduro bikes");bike1.put("price","4972");Mono<Long>setGetAll=reactiveCommands.hset("bike:1",bike1).doOnNext(result->{System.out.println(result);// >>> 4});setGetAll.block();Mono<String>getModel=reactiveCommands.hget("bike:1","model").doOnNext(result->{System.out.println(result);// >>> Deimos});Mono<String>getPrice=reactiveCommands.hget("bike:1","price").doOnNext(result->{System.out.println(result);// >>> 4972});Mono<List<KeyValue<String,String>>>getAll=reactiveCommands.hgetall("bike:1").collectList().doOnNext(result->{System.out.println(result);// >>> [KeyValue[type, Enduro bikes], KeyValue[brand, Ergonom],// KeyValue[price, 4972], KeyValue[model, Deimos]]});-
Creates or modifies the value of a field in a hash.
-
hset(
- key: K, // the key of the hash.
- field: K,
- value: V
-
hset(
- key: K, // the key of the hash.
- map: Map<K, V> // the field/value pairs to update.
-
hset(
-
Returns all fields and values in a hash.
-
hgetall(
- key: K // the key.
-
hgetall(
- channel: KeyValueStreamingChannel<K, V>, // the channel.
- key: K // the key.
-
hgetall(
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
db.HashSet("bike:1", [
new("model", "Deimos"),
new("brand", "Ergonom"),
new("type", "Enduro bikes"),
new("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
-
Creates or modifies the value of a field in a hash.
-
HashSet(
- key: RedisKey, // The key of the hash.
- hashFields: HashEntry[],
- flags: CommandFlags // The flags to use for this operation.
-
HashSet(
- key: RedisKey, // The key of the hash.
- hashField: RedisValue, // The field to set in the hash.
- value: RedisValue, // The value to set.
- when: When, // Which conditions under which to set the field value (defaults to always).
- flags: CommandFlags // The flags to use for this operation.
-
HashSet(
- key: RedisKey, // The key of the hash.
- hashField: RedisValue, // The field to set in the hash.
- value: RedisValue, // The value to set.
- when: When, // Which conditions under which to set the field value (defaults to always).
- flags: CommandFlags // The flags to use for this operation.
-
HashSet(
- key: RedisKey, // The key of the hash.
- hashFields: HashEntry[],
- flags: CommandFlags // The flags to use for this operation.
-
HashSet(
-
Returns the value of a field in a hash.
-
HashGet(
- key: RedisKey, // The key of the hash.
- hashField: RedisValue,
- flags: CommandFlags // The flags to use for this operation.
-
HashGet(
- key: RedisKey, // The key of the hash.
- hashFields: RedisValue[], // The fields in the hash to get.
- flags: CommandFlags // The flags to use for this operation.
-
HashGet(
- key: RedisKey, // The key of the hash.
- hashField: RedisValue,
- flags: CommandFlags // The flags to use for this operation.
-
HashGet(
- key: RedisKey, // The key of the hash.
- hashFields: RedisValue[], // The fields in the hash to get.
- flags: CommandFlags // The flags to use for this operation.
-
HashGet(
-
Returns all fields and values in a hash.
-
HashGetAll(
- key: RedisKey, // The key of the hash to get all entries from.
- flags: CommandFlags // The flags to use for this operation.
-
HashGetAll(
- key: RedisKey, // The key of the hash to get all entries from.
- flags: CommandFlags // The flags to use for this operation.
-
HashGetAll(
$res1 = $r->hmset('bike:1', [
'model' => 'Deimos',
'brand' => 'Ergonom',
'type' => 'Enduro bikes',
'price' => 4972,
]);
echo $res1 . PHP_EOL;
// >>> 4
$res2 = $r->hget('bike:1', 'model');
echo $res2 . PHP_EOL;
// >>> Deimos
$res3 = $r->hget('bike:1', 'price');
echo $res3 . PHP_EOL;
// >>> 4972
$res4 = $r->hgetall('bike:1');
echo json_encode($res3) . PHP_EOL;
// >>> {"name":"Deimos","brand":"Ergonom","type":"Enduro bikes","price":"4972"}
res1 = r.hset('bike:1', {
'model' => 'Deimos',
'brand' => 'Ergonom',
'type' => 'Enduro bikes',
'price' => 4972
})
puts res1 # 4
res2 = r.hget('bike:1', 'model')
puts res2 # Deimos
res3 = r.hget('bike:1', 'price')
puts res3 # 4972
res4 = r.hgetall('bike:1')
puts res4.inspect
# {"model"=>"Deimos", "brand"=>"Ergonom", "type"=>"Enduro bikes", "price"=>"4972"}
lethash_fields=[("model","Deimos"),("brand","Ergonom"),("type","Enduro bikes"),("price","4972"),];ifletOk(res)=r.hset_multiple("bike:1",&hash_fields){letres: String =res;println!("{res}");// >>> OK
}matchr.hget("bike:1","model"){Ok(res)=>{letres: String =res;println!("{res}");// >>> Deimos
},Err(e)=>{println!("Error getting bike:1 model: {e}");return;}};matchr.hget("bike:1","price"){Ok(res)=>{letres: String =res;println!("{res}");// >>> 4972
},Err(e)=>{println!("Error getting bike:1 price: {e}");return;}};matchr.hgetall("bike:1"){Ok(res)=>{letres: Vec<(String,String)>=res;println!("{res:?}");// >>> [("model", "Deimos"), ("brand", "Ergonom"), ("type", "Enduro bikes"), ("price", "4972")]
},Err(e)=>{println!("Error getting bike:1: {e}");return;}};lethash_fields=[("model","Deimos"),("brand","Ergonom"),("type","Enduro bikes"),("price","4972"),];ifletOk(res)=r.hset_multiple("bike:1",&hash_fields).await{letres: String =res;println!("{res}");// >>> OK
}matchr.hget("bike:1","model").await{Ok(res)=>{letres: String =res;println!("{res}");// >>> Deimos
},Err(e)=>{println!("Error getting bike:1 model: {e}");return;}};matchr.hget("bike:1","price").await{Ok(res)=>{letres: String =res;println!("{res}");// >>> 4972
},Err(e)=>{println!("Error getting bike:1 price: {e}");return;}};matchr.hgetall("bike:1").await{Ok(res)=>{letres: Vec<(String,String)>=res;println!("{res:?}");// >>> [("model", "Deimos"), ("brand", "Ergonom"), ("type", "Enduro bikes"), ("price", "4972")]
},Err(e)=>{println!("Error getting bike:1: {e}");return;}};You can get a complete overview of available data types in this documentation site's data types section. Each data type has commands allowing you to manipulate or retrieve data. The commands reference provides a sophisticated explanation.
Scan the keyspace
Each item within Redis has a unique key. All items live within the Redis keyspace. You can scan the Redis keyspace via the SCAN command. Here is an example that scans for the first 100 keys that have the prefix bike::
SCAN 0 MATCH "bike:*" COUNT 100
SCAN returns a cursor position, allowing you to scan iteratively for the next batch of keys until you reach the cursor value 0.
Next steps
You can address more use cases with Redis by reading these additional quick start guides:
Continue learning with Redis University
See the Get Started with Redis learning path for courses.
