3

I have data stored in a jsonb field like so:

class Test(Base):
    __tablename__ = 'test'
    id = Column(Integer, primary_key=True)
    data = Column(JSONB)

In the data column there is a json of the form:

{depth: [0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06]}

I want to determine the max depth for each record and came up with the following query in raw SQL which does the job:

SELECT test.id, test.name,
  (SELECT max(elem::float)
   FROM jsonb_array_elements_text(test.data -> 'depth') As elem
   ) AS maxdepth
FROM test
ORDER BY maxdepth DESC

As I am using SQLAlchemy ORM in my application I want to write this query with SQLAlchemy ORM, but I cannot come up with the proper form.

I was thinking I need something like this:

subq = session.query(
    func.max().label('maxdepth')).\
    select_from(func.jsonb_array_elements(Test.data['depth'])).\
    subquery()

stmnt = session.query(
    Test.id, subq.c.maxdepth).\
    order_by(subq.c.maxdepth)

But this obviously doesn't work as I don't know how to query from the fields extracted by jsonb_array_elements

1 Answer 1

2

[NOTE: AS OF SQLAlchemy 1.0, Oct. 26 2015. This may change in a future release] these special PG syntaxes are not built in to SQLAlchemy right now, please see the recipe at https://bitbucket.org/zzzeek/sqlalchemy/issues/3566/figure-out-how-to-support-all-of-pgs#comment-22842678 which illustrates your query.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your help, I can confirm this works. I hope you find a way to improve the built-in SQLAlchemy PG/JSON support in future releases!
I wish there was a current document that has this support documentation, as of 2019-08-08, the documentation for SQLAlchemy and JSONB is pretty hard to dig up.
I can't see this page. Is the repo private now?
The repository was moved to Github and is now here: github.com/sqlalchemy/sqlalchemy/issues/…. I'm not sure which specific comment was to be linked, but one of those in the thread should be what was intended

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.