redis / redis-om-python

Object mapping, and more, for Redis and Python
MIT License
1.12k stars 112 forks source link

`find` fails on a `JsonModel` when querying more than one `HashModel` field using two or more expressions #357

Open wiseaidev opened 2 years ago

wiseaidev commented 2 years ago

Code to reproduce the issue:

from typing import Optional, Any

from fastapi import FastAPI

from pydantic import BaseModel, Field as PydanticField, EmailStr
import datetime

from aredis_om import (
    Field,
    HashModel,
    JsonModel,
    Migrator,
    get_redis_connection
)

redis_conn = get_redis_connection(
    url=f"redis://localhost:6379",
    decode_responses=True
)

class User(HashModel):
    first_name: Optional[str] = Field(index=True)
    last_name: Optional[str] = Field(index=True)
    email: EmailStr = Field(index=True)
    password: str = Field(index=True)
    created_on: Optional[datetime.datetime] = Field(default_factory=datetime.datetime.now)

    class Meta:
        database = redis_conn

class Contact(JsonModel):
    user: User = Field(index=True)
    contact: User = Field(index=True)
    message: Optional[str] = Field(index=True, default="yo")
    created_on: Optional[datetime.datetime] = Field(default_factory=datetime.datetime.now)
    class Meta:
        database = redis_conn

router = FastAPI(title=__name__)

@router.on_event("startup")
async def startup():
    await Migrator().run()
    user1 = await User(email="business@wiseai.dev", password="S3C11R3P@ssW0rD").save()
    user2 = await User(email="yo@wiseai.dev", password="P@ssW0rD").save()
    contact1 = await Contact(user=user1, contact=user2).save()
    contact2 = await Contact.find((Contact.user.email == "business@wiseai.dev") & (Contact.contact.email == "yo@wiseai.dev")).all()
    print(contact2)

However, the following expressions work as expected:

    contact2 = await Contact.find((Contact.user.email == "business@wiseai.dev") & (Contact.message == "yo")).all()
    contact2 = await Contact.find(Contact.user.email == "business@wiseai.dev").all()

This confirms my hypothesis that a JsonModel object can index at most one HashModel field. Is that intentional or a bug?

DasLukas commented 2 years ago

Have you try EmbeddedJsonModel instead of HashModel?

mrkprdo commented 2 years ago

@wiseaidev Does this line work? await Migrator().run()

tihmels commented 1 year ago

Try using and instead of &

XChikuX commented 1 year ago

@wiseaidev Does this line work? await Migrator().run()

I've tried this in my asynchronous code. It does seem to work. I'm not sure what happens under the hood though. There doesn't seem to be much documentation to how exactly this helps redis-om 'create indices' in redis.

@wiseaidev I've opened up this issue to track a related 'potential' bug: #462