【问题标题】:How to find nested value in postgres JSONB using sqlalchemy?如何使用 sqlalchemy 在 postgres JSONB 中查找嵌套值?
【发布时间】:2021-04-22 15:04:18
【问题描述】:

我有一个带有 JSONB 列名称 entity 的 postgres 表。 json结构的例子是:

{
  "some_key": "some value",
  "properties": {
    "name": ["name_value"],
  }
}

我需要查找name_value 的记录。我可以通过查询得到它:

SELECT entity FROM my_table where entity->'properties' @> {"name": ["name_value"]};

问题是:我找不到使用 sqlalchemy ORM 创建相同查询的方法。

更新: 我的模型是动态的,因为多个表使用相同的结构只是不同的表名。代码如下:

...
Base = declarative_base(engine)

class ForeignBase(AbstractConcreteBase, Base):
    pass

def make_model(name):
    class Entity(ForeignBase):
        __tablename__ = name
        __mapper_args__ = {"polymorphic_identity": name, "concrete": True}
        __table_args__ = {"extend_existing": True}

        id = Column(String, primary_key=True)
        entity = Column(JSONB, nullable=True)
        ...
    configure_mappers()
    return Entity

然后我使用 3 个函数来启动我的模型并获得我当前需要的一个:

def get_model_list():
    tables_names_list = get_table_name_list()
    model_list = [make_model(PREFIX + table_name) for table_name in tables_names_list]
    return model_list

def get_tables_dict():
    return {table.__tablename__: table for table in ForeignBase.__subclasses__()}

def get_table_object(table_name):
    return get_tables_dict().get(table_name)

【问题讨论】:

    标签: python postgresql sqlalchemy


    【解决方案1】:

    您可以使用以下 SQLAlchemy 表达式。运算符 @> 是 SQLAlchemy 中 JSONB 列的 contains()

    Session().query(MyTable).filter(MyTable.entity["properties"].contains({"name": ["name_value"]})).with_entities(MyTable.entity).all()
    

    【讨论】:

    • 感谢您的回答。不幸的是,它返回一个空列表[]。没有with_entities 部分,它也会返回相同的结果。
    • 打印并检查它正在生成的查询。可能缺少某些过滤器
    • 我已尝试打印该声明并得到 SELECT my_table.entity FROM my_table WHERE ((my_table.entity -> %(entity_1)s)) @> %(param_1)s 。好像应该没问题。只是不确定那些双括号。
    • 查询看起来没问题。双括号不是问题。也许数据库中没有数据?
    • 数据在 db 中,我已将原始选择放入 db shell 并找到记录。我已经仔细检查了。相同的记录也出现在其他查询中。可以和MyTable模型配置有什么关系吗?
    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 2019-03-14
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    • 2023-04-03
    • 2022-01-02
    相关资源
    最近更新 更多