简体   繁体   中英

SQLALchemy: Query a single key or subset of keys of a Postgres JSONB column

I have a Postgres table that has a JSONB column. How do I query data of this column without loading the whole column at once in SQLAlchemy?

Let's say the JSONB column myjsonb contains {'a': 1, 'b': 2, 'c': 3, ... 'z': 26} . I only want the value of 'a' and not all 26 values. How do I specify a query to do that?

For example,

query = session.query(MyTable).options(defer('myjsonb')).join(MyTable.myjsonb['a'])

does not work.

Any idea how I can only retrieve 'a' ? And what happens if the key 'a' is not present? And how can I load multiple keys, let's say 'b' to ' f' , but not all of them at once? Thanks!

This is actually pretty straight forward, you just query for the keys you are interested as in:

query = session.query(MyTable.myjsonb['a'])

If you want multiple keys from the json object, lets say a and c , you do

query = session.query(MyTable.myjsonb['a'], MyTable.myjsonb['c'])

If any of the keys are not present, it will just return None for that row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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