SQLAlchemy: filtering on values stored in nested list of the JSONB field

[*]

SQLAlchemy’s JSONB type has the contains() method for the @> operator in Postgresql. The @> operator is used to check if the left value contains the right JSON path/value entries at the top level. In your case

data @> '{"nested_list": [{"nested_key": "one"}]}'::jsonb

Or in python

the_value="one"

Session().query(Item).filter(Item.data.contains(
    {'nested_list': [{'nested_key': the_value}]}
))

The method converts your python structure to suitable JSON string for the database.

In Postgresql 12 you can use the JSON path functions:

import json

Session().query(Item).\
    filter(func.jsonb_path_exists(
        Item.data,
        '$.nested_list[*].nested_key ? (@ == $val)',
        json.dumps({"val": the_value})))

Leave a Comment