Skip to main content

Getting Started


Profile picture for Prasan Kumar
Author:
Prasan Kumar, Technical Solutions Developer at Redis
Profile picture for Will Johnston
Author:
Will Johnston, Developer Growth Manager at Redis

Welcome to the getting started for the official Redis Developer Hub!

If you are new to Redis, we recommend starting with Redis University (RU101). RU101 is an introductory course, perfect for developers new to Redis. In this course, you’ll learn about the data structures in Redis, and you’ll see how to practically apply them in the real world.

If you have questions related to Redis, come join the Redis Discord server. Our Discord server is a place where you can learn, share, and collaborate about anything and everything Redis. Connect with users from the community and Redis University. Get your questions answered and learn cool new tips and tricks! Watch for notifications of the latest content from Redis and the community. And share your own content with the community.

Setup Redis

There are essentially two ways you can use Redis:

  • Cloud Redis: A hosted and serverless Redis database-as-a-service (DBaaS). The fastest way to deploy Redis Cloud via Amazon AWS, Google Cloud Platform, or Microsoft Azure.
  • On-prem/local Redis: Self-managed Redis using your own server and any operating system (Mac OS, Windows, or Linux).

If you choose to use local Redis we strongly recommend using Docker. If you choose not to use Docker, use the following instructions based on your OS:

The docker run command below exposes redis-server on port 6379 and RedisInsight on port 8001. You can use RedisInsight by pointing your browser to http://localhost:8001.

# install
$ docker run -d --name redis-stack -p 6379:6379 -p 8001:8001 redis/redis-stack:latest

You can use redis-cli to connect to the server at localhost:6379. If you don’t have redis-cli installed locally, you can run it from the Docker container like below:

# connect
$ docker exec -it redis-stack redis-cli

Basic Querying with Redis

  • Connect to Redis using CLI or RedisInsight (a GUI tool to visualize data & run commands)

RedisInsight RedisInsight

# syntax 1 : connect using host & port, followed by password
$ redis-cli -h host -p port
> AUTH password
OK

# example 1
$ redis-cli -h redis15.localnet.org -p 6390
> AUTH myUnguessablePassword
OK

# syntax 2 : connect using uri
$ redis-cli -u redis://user:password@host:port/dbnum

# example 2
$ redis-cli -u redis://LJenkins:p%40ssw0rd@redis-16379.hosted.com:16379/0

  • Basic CLI / RedisInsight workbench commands
# syntax : Check specific keys
> KEYS pattern

# example
> KEYS *

#------------
# syntax : Check number of keys in database
> DBSIZE

#------------
# syntax : set a key value
> SET key value EX expirySeconds

# example
> SET company redis EX 60

#------------
# syntax : get value by key
> GET key

# example
> GET company

#------------
# syntax : delete keys
> DEL key1 key2 key3 ... keyN

# example
> DEL company

#------------
# syntax : Check if key exists
> EXISTS key1

# example
> EXISTS company

#------------
# syntax : set expiry to key
> EXPIRE key seconds

# example
> EXPIRE lastname 60

#------------
# syntax : remove expiry from key
> PERSIST key

# example
> PERSIST lastname

#------------
# syntax : find (remaining) time to live of a key
> TTL key

# example
> TTL lastname

#------------
# syntax : increment a number
> INCR key

# example
> INCR counter

#------------
# syntax : decrement a number
> DECR key

# example
> DECR counter

Detailed CLI instructions can be viewed here and commands can be checked here

Secondary Indexing and Searching with Redis

Redis Stack enables the JSON data type in Redis.

# syntax : set an object value to a key
> JSON.SET objKey $ value

# example
> JSON.SET person $ '{"name":"Leonard Cohen","dob":1478476800,"isActive": true, "hobbies":["music", "cricket"]}'

#------------
# syntax : get object value of a key
> JSON.GET objKey $

# example
> JSON.GET person $

#------------
# syntax : find object key length
> JSON.OBJLEN objKey $

# example
> JSON.OBJLEN person $

#------------
# syntax : find object keys
> JSON.OBJKEYS objKey $

# example
> JSON.OBJKEYS person $

#------------
# syntax : update nested property
> JSON.SET objKey $.prop value

# example
> JSON.SET person $.name '"Alex"'

#------------
# syntax : update nested array
> JSON.SET objKey $.arrayProp fullValue
> JSON.SET objKey $.arrayProp[index] value

# example
> JSON.SET person $.hobbies '["music", "cricket"]'
> JSON.SET person $.hobbies[1] '"dance"'

#------------
# syntax : remove nested array item by index
> JSON.ARRPOP objKey $.arrayProp index

# example
> JSON.ARRPOP person $.hobbies 1

More details can be found in the Redis Stack docs


Redis Stack enables a query and indexing engine for Redis, providing secondary indexing, full-text search and aggregations capabilities.

  • We have to create index on schema to be able to search on its data
# syntax
> FT.CREATE {index_name} ON JSON PREFIX {count} {prefix} SCHEMA {json_path} AS {attribute} {type}
# NOTE: attribute = logical name, json_path = JSONPath expressions

# example
> FT.CREATE userIdx ON JSON PREFIX 1 users: SCHEMA $.user.name AS name TEXT $.user.hobbies AS hobbies TAG $.user.age as age NUMERIC
# NOTE: You can search by any attribute mentioned in the above index for keys that start with users: (e.g. users:1).
  • More details on Indexing JSON can be found here

Once index is created, any pre-existing/ new/ modified JSON document is automatically indexed.

//sample json document
{
"user": {
"name": "John Smith",
"hobbies": "foo,bar",
"age": 23
}
}
# adding JSON document
> JSON.SET myDoc $ '{"user":{"name":"John Smith","hobbies":"foo,bar","age":23}}'
  • Search
# search all user documents with name 'John'
> FT.SEARCH userIdx '@name:(John)'
1) (integer) 1
2) "myDoc"
3) 1) "$"
2) {"user":{"name":"John Smith","hobbies":"foo,bar","age":23}}"
  • Search & project required fields
# search documents with name 'John' & project only age field
> FT.SEARCH userIdx '@name:(John)' RETURN 1 $.user.age
1) (integer) 1
2) "myDoc"
3) 1) "$.user.age"
2) "23"
# project multiple fields
> FT.SEARCH userIdx '@name:(John)' RETURN 2 $.user.age $.user.name
1) (integer) 1
2) "myDoc"
3) 1) "$.user.age"
2) "23"
3) "$.user.name"
4) "John Smith"

#------------
# project with alias name
> FT.SEARCH userIdx '@name:(John)' RETURN 3 $.user.age AS userAge

1) (integer) 1
2) "myDoc"
3) 1) "userAge"
2) "23"
#------------

# multi field query
> FT.SEARCH userIdx '@name:(John) @hobbies:{foo | me} @age:[20 30]'
1) (integer) 1
2) "myDoc"
3) 1) "$"
2) {"user":{"name":"John Smith","hobbies":"foo,bar","age":23}}"

More details on query syntax

  • Drop index
> FT.DROPINDEX userIdx

Useful Resources

  1. Redis and JSON explained (Revisited in 2022) video
  2. Searching with Redis Stack
  3. Redis University 204, Storing, Querying, and Indexing JSON at Speed

Sync Redis with Other Databases

RedisGears adds a dynamic execution framework for your Redis data that enables you to write and execute functions that implement data flows in Redis.

Consider following example to sync data with MongoDB.

  • Create the below python file and update the MongoDB connection details, database, collection and primary key name to be synced
write-behind.py
# Gears Recipe for a single write behind

# import redis gears & mongo db libs
from rgsync import RGJSONWriteBehind, RGJSONWriteThrough
from rgsync.Connectors import MongoConnector, MongoConnection

# change mongodb connection
connection = MongoConnection("", "", "", "", "ENV_MONGODB_CONNECTION_URL")

# change MongoDB database
db = 'ENV_DB_NAME'

# change MongoDB collection & it's primary key
collection1Connector = MongoConnector(connection, db, 'ENV_COLLECTION1_NAME', 'ENV_COLLECTION1_PRIMARY_KEY')

# change redis keys with prefix that must be synced with mongodb collection
RGJSONWriteBehind(GB, keysPrefix='ENV_COLLECTION1_PREFIX_KEY',
connector=collection1Connector, name='Collection1WriteBehind',
version='99.99.99')
ENV_MONGODB_CONNECTION_URL=mongodb://usrAdmin:passwordAdmin@10.10.20.2:27017/dbSpeedMernDemo?authSource=admin
ENV_DB_NAME=dbSpeedMernDemo
ENV_COLLECTION1_NAME=movies
ENV_COLLECTION1_PRIMARY_KEY=movieId
ENV_COLLECTION1_PREFIX_KEY=movie

The code above demonstrates how you would sync a "movies" collection in MongoDB with Redis using the "movie" key prefix.

To get this working you first need to load the python file into redis-server:

$ redis-cli rg.pyexecute "`cat write-behind.py`" REQUIREMENTS rgsync pymongo==3.12.0

Now, insert a JSON item in to Redis starting with the prefix specified in the python file (i.e. "movie"):

# redis-cli command
> JSON.SET movie:123 $ '{"movieId":123,"name":"RRR","isActive": true}'

Now, verify whether the JSON is inserted into MongoDB.

Additional Resources For Syncing with Redis and Other Databases

  1. Redis gear sync with MongoDB
  2. RG.PYEXECUTE
  3. rgsync
  4. gears-cli

Probabilistic Data and Queries with Redis

Redis Stack supports probabilistic datatypes and queries. Below you will find a stock leaderboard example:

# Reserve a new leaderboard filter
> TOPK.RESERVE trending-stocks 12 50 4 0.9
"OK"

# Add a new entries to the leaderboard
> TOPK.ADD trending-stocks AAPL AMD MSFT INTC GOOG FB NFLX GME AMC TSLA
1) "null" ...

# Get the leaderboard
> TOPK.LIST trending-stocks
1) "AAPL"
2) "AMD"
2) "MSFT" ...

# Get information about the leaderboard
> TOPK.INFO trending-stocks
1) "k"
2) "12"
3) "width"
4) "50"
5) "depth"
6) "4"
7) "decay"
8) "0.90000000000000002"

More details in docs

TimeSeries Data and Queries with Redis

Redis Stack supports time-series use cases such as IoT, stock prices, and telemetry. You can ingest and query millions of samples and events at the speed of Redis. You can also use a variety of queries for visualization and monitoring with built-in connectors to popular tools like Grafana, Prometheus, and Telegraf.

The following example demonstrates how you might store temperature sensor readings in Redis Stack:

# Create new time-series, for example temperature readings
> TS.CREATE temperature:raw DUPLICATE_POLICY LAST
"OK"

# Create a bucket for monthly aggregation
> TS.CREATE temperature:monthly DUPLICATE_POLICY LAST
"OK"

# Automatically aggregate based on time-weighted average
> TS.CREATERULE temperature:raw temperature:monthly AGGREGATION twa 2629800000
"OK"

# Add data to the raw time-series
> TS.MADD temperature:raw 1621666800000 52 ...
1) "1621666800000" ...

# View the monthly time-weighted average temperatures
> TS.RANGE temperature:monthly 0 +
1) 1) "1621666800000"
2) "52" ...

# Delete compaction rule
> TS.DELETERULE temperature:raw temperature:monthly
"OK"

# Delete partial time-series
> TS.DEL temperature:raw 0 1621666800000
(integer) 1

More details in docs

Additional Resources