Redis OM Python

1.1.0 · active · verified Thu Apr 16

Redis OM Python is an object-mapping library that provides high-level abstractions to easily model, validate, and query data in Redis with modern Python applications. It leverages Pydantic for robust data validation and supports both Redis Hashes (`HashModel`) and JSON documents (`JsonModel`) for data storage, including automatic index generation and a fluent query API. Currently at version 1.1.0, the library maintains an active development pace with frequent updates and major version releases every few months.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates defining a `HashModel`, connecting to Redis via an environment variable, running schema migrations, creating and saving model instances, and retrieving them by primary key and through a basic query. It assumes a Redis Stack instance is running locally (e.g., via Docker).

import os
from datetime import date
from redis_om import HashModel, Migrator

# Ensure Redis Stack is running, e.g., with Docker:
# docker run -d -p 6379:6379 -p 8001:8001 redis/redis-stack

# Set the Redis connection URL (or it defaults to redis://localhost:6379)
os.environ['REDIS_OM_URL'] = os.environ.get('REDIS_OM_URL', 'redis://localhost:6379')

class Customer(HashModel):
    first_name: str
    last_name: str
    email: str
    join_date: date
    age: int

    class Meta:
        global_key_prefix = "my_app"
        model_key_prefix = "customers"
        # By default, all fields are indexed in 1.0+, but can be specified individually
        # for more granular control if not using a model-level index.

# Run index migrations at application startup
# For models defined as `HashModel` or `JsonModel`
Migrator().run()

# Create a customer
new_customer = Customer(
    first_name="John",
    last_name="Doe",
    email="john.doe@example.com",
    join_date=date(2023, 1, 15),
    age=30
)

# Save the customer to Redis
new_customer.save()
print(f"Saved customer with PK: {new_customer.pk}")

# Retrieve the customer by its primary key (pk)
found_customer = Customer.get(new_customer.pk)
print(f"Retrieved customer: {found_customer.first_name} {found_customer.last_name}")

# Find customers by query
old_customers = Customer.find(Customer.age > 25).all()
for c in old_customers:
    print(f"Old customer: {c.first_name} (Age: {c.age})")

view raw JSON →