Filter on json data with in_() sqlalchemy

Question:

I want to filter features(Json field on database) with items = a or b, but here it returns 0, when I use other columns the filter works correctly. It returns correct data with ["a"] or ["b"] too, what is the reason? and what is the solution?

data.filter(Data.id.in_([1,2])) #works

data.filter(Data.features['items'].in_(["a"])) # returns 3

data.filter(Data.features['items'].in_(["b"])) # returns 1

data.filter(Data.features['items'].in_(["a","b"])) # returns 0 I exepect 4
Asked By: parastoo

||

Answers:

I am guessing here, but you might be looking to use contains instead of in_.

Please try the below queries instead:

q = select(Data).filter(Data.features['items'].contains("a"))
q = select(Data).filter(Data.features['items'].contains("b"))
q = select(Data).filter(or_(  # i assume it is OR, but you might have wanted AND instead
    Data.features['items'].contains("a"), 
    Data.features['items'].contains("b"),
))
Answered By: van

data.filter(Data.features[‘items’].in_(["a","b"])) returns 0 because data.filter() is looking features with BOTH ‘a’ and ‘b’ in the items field.

if you only want either ‘a’ or ‘b’ you’ll need to filter with an ‘or’ operator from sqlalchemy import.

data.filter(or_(Data.features['items'].in_(["a"]), Data.features['items'].in_(["b"])))

Answered By: Simran Farrukh
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.