Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlAlchemy: Querying the length json field having an array

I have a table with a field of type JSON. The JSON field contains a JSON object with an array. How do I query the length of this array for each row?

class Post(Base):
    __tablename__ = 'posts'
    id = Column(Integer, primary_key=True)
    items = Column(JSON)

Example rows in this table:

id: 1, items: [2,3,5]
id: 2, items: [2,3,5, 8, 12]
id: 3, items: [2,5]
id: 4, items: []

Expected result:

1 3
2 5
3 2
4 0

Is there something like this:

session.query(Post.id, len(Post.items))

Note: The JSON field contains an array of complex objects, I have used integers here only for the purpose of illustration.

like image 458
vrtx54234 Avatar asked Apr 14 '14 12:04

vrtx54234


1 Answers

Found a solution

Create a class that extends FunctionElement like this

from sqlalchemy.sql.expression import FunctionElement
from sqlalchemy.ext.compiler import compiles
class json_array_length(FunctionElement):
    name = 'json_array_len'

@compiles(json_array_length)
def compile(element, compiler, **kw):
    return "json_array_length(%s)" % compiler.process(element.clauses)

and use it like this

session.query(Post.id, json_array_length(Post.items))

Note: this will work on postgres because the function 'json_array_length' is defined in it. If you want this for a different DB that function will need to change. Refer http://docs.sqlalchemy.org/en/rel_0_9/core/compiler.html#further-examples

like image 197
Avinash Avatar answered Oct 19 '22 23:10

Avinash