Python guide

Connect your Python application to a Redis database

redis-py is the Python client for Redis. The sections below explain how to install redis-py and connect your application to a Redis database.

redis-py requires a running Redis or Redis Stack server. See Getting started for Redis installation instructions.


To install redis-py, enter:

pip install redis

For faster performance, install Redis with hiredis support. This provides a compiled response parser, and for most cases requires zero code changes. By default, if hiredis >= 1.0 is available, redis-py attempts to use it for response parsing.

The Python distutils packaging scheme is no longer part of Python 3.12 and greater. If you're having difficulties getting redis-py installed in a Python 3.12 environment, consider updating to a recent release of redis-py.
pip install redis[hiredis]


Connect to localhost on port 6379, set a value in Redis, and retrieve it. All responses are returned as bytes in Python. To receive decoded strings, set decode_responses=True. For more connection options, see these examples.

r = redis.Redis(host='localhost', port=6379, decode_responses=True)

Store and retrieve a simple string.

r.set('foo', 'bar')
# True
# bar

Store and retrieve a dict.

r.hset('user-session:123', mapping={
    'name': 'John',
    "surname": 'Smith',
    "company": 'Redis',
    "age": 29
# True

# {'surname': 'Smith', 'name': 'John', 'company': 'Redis', 'age': '29'}

Connect to a Redis cluster

To connect to a Redis cluster, use RedisCluster.

from redis.cluster import RedisCluster

rc = RedisCluster(host='localhost', port=16379)

# [[host=,port=16379,name=,server_type=primary,redis_connection=Redis<ConnectionPool<Connection<host=,port=16379,db=0>>>], ...

rc.set('foo', 'bar')
# True

# b'bar'

For more information, see redis-py Clustering.

Connect to your production Redis with TLS

When you deploy your application, use TLS and follow the Redis security guidelines.

import redis

r = redis.Redis(
    host="", port=6379,
    username="default", # use your Redis user. More info
    password="secret", # use your Redis password
r.set('foo', 'bar')
# True

# b'bar'

For more information, see redis-py TLS examples.

Example: Indexing and querying JSON documents

Make sure that you have Redis Stack and redis-py installed. Import dependencies:

import redis
from redis.commands.json.path import Path
import as aggregations
import as reducers
from import TextField, NumericField, TagField
from import IndexDefinition, IndexType
from import NumericFilter, Query

Connect to your Redis database.

r = redis.Redis(host='localhost', port=6379)

Let's create some test data to add to your database.

user1 = {
    "name": "Paul John",
    "email": "",
    "age": 42,
    "city": "London"
user2 = {
    "name": "Eden Zamir",
    "email": "",
    "age": 29,
    "city": "Tel Aviv"
user3 = {
    "name": "Paul Zamir",
    "email": "",
    "age": 35,
    "city": "Tel Aviv"

Define indexed fields and their data types using schema. Use JSON path expressions to map specific JSON elements to the schema fields.

schema = (
    TextField("$.name", as_name="name"), 
    TagField("$.city", as_name="city"), 
    NumericField("$.age", as_name="age")

Create an index. In this example, all JSON documents with the key prefix user: will be indexed. For more information, see Query syntax.

rs = r.ft("idx:users")
        prefix=["user:"], index_type=IndexType.JSON
# b'OK'

Use JSON.SET to set each user value at the specified path.

r.json().set("user:1", Path.root_path(), user1)
r.json().set("user:2", Path.root_path(), user2)
r.json().set("user:3", Path.root_path(), user3)

Let's find user Paul and filter the results by age.

res =
    Query("Paul @age:[30 40]")
# Result{1 total, docs: [Document {'id': 'user:3', 'payload': None, 'json': '{"name":"Paul Zamir","email":"","age":35,"city":"Tel Aviv"}'}]}

Query using JSON Path expressions.
    Query("Paul").return_field("$.city", as_field="city")
# [Document {'id': 'user:1', 'payload': None, 'city': 'London'}, Document {'id': 'user:3', 'payload': None, 'city': 'Tel Aviv'}]

Aggregate your results using FT.AGGREGATE.

req = aggregations.AggregateRequest("*").group_by('@city', reducers.count().alias('count'))
# [[b'city', b'Tel Aviv', b'count', b'2'], [b'city', b'London', b'count', b'1']]

Learn more

Back to top ↑