且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用SqlAlchemy在Postgres中查询JSON数组?

更新时间:2023-01-21 22:04:39

您只是忘记了JSON路径应包括最外层数组:

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

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

将返回您要查找的用户。如果您的JSON包含一个键为 phone等的对象,则原始查询将匹配。请注意,这将返回所讨论的 User 对象,而不是返回的特定对象/名称。 JSON结构。如果您希望这样做(这似乎是最终目标),则可以扩展每个用户的数组元素,根据结果记录进行过滤,然后选择名称:

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()

另一方面,上述查询的索引友好性不如第一个是,因为它必须在过滤之前扩展所有数组,因此首先在子查询或CTE的联系人列表中找到包含电话的用户,然后进行扩展和过滤可能是有益的。

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.