简体   繁体   English

如何使用带有 sqlalchemy 和 postgres 的嵌套 jsonb 过滤

[英]How to filterby with nested jsonb with sqlalchemy and postgres

I can't work out how to use SQLAlchemy to query a table that contains JSONB data.我不知道如何使用 SQLAlchemy 查询包含 JSONB 数据的表。

The JSON structure is similar to this: JSON 结构类似于:

example = {
  "product": "Widget",
  "version": 1,
  "release_date": "2019-07-01T00:00:00.000Z",
  "widget": {
    "code": "ABCDEF",
    "name": "my widget",
    "uses": {
        "rain": "yes",
        "snow": "no",
        "heat": "sometimes",
...

I'm trying to execute a query with this functionality:我正在尝试使用此功能执行查询:

SELECT
    json  AS acdata
FROM
    aircraft.aircraft
WHERE json -> 'widget' -> 'uses' ->> 'rain' = 'No';

in this form:以这种形式:

widget= session.query(Widget).filter_by(rain='No').first()

I know the rain='No' isn't correct but I can't work out what should go there!我知道rain='No' 不正确,但我不知道应该去那里! The objective is to get the first Widget whose key widget.uses.rain = 'No'目标是获得第一个 Widget,其 key widget.uses.rain = 'No'

I have this definition for my Widget class我的 Widget 类有这个定义

from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.dialects.postgresql import JSONB, UUID

class Widget(Base):
    __tablename__ = 'widgets'
    __table_args__ = {'schema' : 'factory'}

    id = Column(UUID(as_uuid=True), primary_key=True)
    json = Column(JSONB, nullable=False)
...

To access a nested jsonb value use a tuple of keys (path index operation) and astext to convert the value as text:要访问嵌套的jsonb值,请使用键元组(路径索引操作)和astext将值转换为文本:

widget = session.query(Widget).\
    filter(Widget.json["widget", "uses", "rain"].astext == 'No').\
    first()

The resulting query uses the #>> operator for the path index + astext operation.结果查询使用#>>运算符进行路径索引 + astext 操作。 You cannot use filter_by() for this kind of predicate, as it is used for simple equality checks against attributes of a model class.您不能将filter_by()用于这种谓词,因为它用于针对模型类的属性进行简单的相等性检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM