简体   繁体   中英

Is it possible to search a JSONB List for a value using "LIKE" and SqlAlchemy?

For example, if I have a JSONB column, and it is stored as:

["oranges","apples","bananas"]

How can I check using a LIKE type search if the substring "app" is in the list?

Ideally I would like be able to do something like:

Basket['fruits'].contains_like('%app%')

Is this possible with sqlalchemy?

Using inspiration from the pure PostgreSQL answer here , you can create the following condition:

from sqlalchemy import exists, func, literal_column

exists().select_from(
  func.jsonb_array_elements_text(Basket['fruits']).alias('fruit')
).where(literal_column('fruit').like('%app%'))

The answer raises the issue of performance and potentially adding an index in special cases (when you're only interested in strings starting with a certain value). Have a look if that applies to you and if you experience performance issues

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