Skip to content

Instantly share code, notes, and snippets.

@abrookins
Created November 20, 2021 01:44
Show Gist options
  • Save abrookins/91afc5adfdace1d72819b0d758cf23f4 to your computer and use it in GitHub Desktop.
Save abrookins/91afc5adfdace1d72819b0d758cf23f4 to your computer and use it in GitHub Desktop.
Embedded JSON models with Redis OM for Python
import datetime
from typing import Optional
from redis_om import (
EmbeddedJsonModel,
JsonModel,
Field,
Migrator,
)
from redis_om import get_redis_connection
class Address(EmbeddedJsonModel):
address_line_1: str
address_line_2: Optional[str]
city: str = Field(index=True)
state: str = Field(index=True)
country: str
postal_code: str = Field(index=True)
class Customer(JsonModel):
first_name: str = Field(index=True)
last_name: str = Field(index=True)
email: str = Field(index=True)
join_date: datetime.date
age: int = Field(index=True)
bio: Optional[str] = Field(index=True, full_text_search=True,
default="")
# Creates an embedded model.
address: Address
# With these two models and a Redis deployment with the RedisJSON
# and RediSearch modules installed, we can run queries like the
# following.
# Before running queries, we need to run migrations to set up the
# indexes that Redis OM will use. You can also use the `migrate`
# CLI tool for this!
redis = get_redis_connection()
Migrator(redis).run()
# Find all customers who live in San Antonio, TX
Customer.find(Customer.address.city == "San Antonio",
Customer.address.state == "TX")
@chakri622
Copy link

Hi All,

I am getting the above error when using a remote redis instance.

Traceback (most recent call last):
File "/Users/austinward/activeresource/redis_om_test.py", line 44, in
Migrator(redis.class).run()
File "/Users/austinward/.pyenv/versions/3.9.10/lib/python3.9/site-packages/redi
s_om/model/migrations/migrator.py", line 156, in run
self.detect_migrations()
File "/Users/austinward/.pyenv/versions/3.9.10/lib/python3.9/site-packages/redi
s_om/model/migrations/migrator.py", line 94, in detect_migrations
import_submodules(self.module)
File "/Users/austinward/.pyenv/versions/3.9.10/lib/python3.9/site-packages/redi
s_om/model/migrations/migrator.py", line 24, in import_submodules
root_module = importlib.import_module(root_module_name)
File "/Users/austinward/.pyenv/versions/3.9.10/lib/python3.9/importlib/init
.py", line 118, in import_module
if name.startswith('.'):
AttributeError: type object 'Redis' has no attribute 'startswith'

Please let me know the resolution.

Thanks in Advance.

@dhavalaprashanth
Copy link

dhavalaprashanth commented Feb 16, 2023

@chakri622 change to Migrate().run() it will work . Error is that Migrator expects a optional python package to load in background but we are providing redis connection which is not a python package . Its optional and no need to send anything for Migrator just leave it as Migrator().run() .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment