How to query JSON Array in Postgres with SqlAlchemy?

前端 未结 1 1538
梦毁少年i
梦毁少年i 2021-01-02 11:44

I have a SqlAlchemy model defined

from sqlalchemy.dialects.postgresql import JSONB

class User(db.Model):
    __tablename__ = \"user\"
    id = db.Column(db.         


        
1条回答
  •  -上瘾入骨i
    2021-01-02 12:21

    You just forgot that your JSON path should include the outermost array as well:

    User.query.filter(User.contact_list.contains([{"phone": ["147889"]}])).all()
    

    will return the user you are looking for. The original query would match, if your JSON contained an object with key "phone" etc. Note that this returns the User object in question, not the specific object/name from the JSON structure. If you want that, as seems to be the end goal, you could expand the array elements of each user, filter based on the resulting records, and select the name:

    val = db.column('value', type_=JSONB)
    db.session.query(val['name'].astext).\
        select_from(User,
                    db.func.jsonb_array_elements(User.contact_list).alias()).\
        filter(val.contains({"phone": ["147889"]})).\
        all()
    

    On the other hand the above query is not as index friendly as the first one can be, because it has to expand all the arrays before filtering, so it might be beneficial to first find the users that contain the phone in their contact list in a subquery or CTE, and then expand and filter.

    0 讨论(0)
提交回复
热议问题