我有一个包含两个jsonb_each语句的查询,我需要将其转换为 sqlalchemy。我尝试过使用子查询、别名,甚至 fnop来逐字翻译查询,但失败并显示InternalError.我特别困惑的是我不知道如何访问{key: value}从第一个函数返回的对jsonb_each。这就是我到目前为止所拥有的v = column('value', type_=JSONB)k = column('key', type_=JSONB)polarity = v['polarity'].astextq = db.session.query( db.func.count(polarity).label('count'), ## other fields )\ .select_from(MyModel)\ .join(db.func.jsonb_each(MyModel.json_content['myMap']).alias('items'), sa.true())\ .join( # ... stuck here # I want to access the returned data from the previous join here )\ # group by and order by here .all()查询-- myTable-- - id-- - json_contentSELECT count(d.value ->> 'polarity') as count, d.value ->> 'polarity' as polarity, d.key as keyfrom myTable tjoin jsonb_each(t.json_content -> 'myMap') m on truejoin jsonb_each((m.value -> 'data') - 'text') d on truegroup by d.value ->> 'polarity', d.key;我想要得到的结果集count polarity category----------------------------1 positive cate21 positive cate42 negative cate11 negative cate2我试图查询的示例 json 对象{ "myMap": { "0": { "data": { "text": "koolaid", "cate1": { "polarity": "negative" }, "cate2": { "polarity": "positive" } } }, "1": { "data": { "text": "some other text", "cate1": { "polarity": "negative" }, "cate2": { "polarity": "negative" }, "cate4": { "polarity": "positive" } } } }}如果需要更多信息,请告诉我
1 回答
MMTTMM
TA贡献1869条经验 获得超4个赞
代码会是这样的:
first_alias = aliased(jsonb_each(MyModel.json_content['myMap'])))
second_alias = aliased(jsonb_each(first_alias.c.value.op("->")("data").op("-")("text")))
polarity = second_alias.c.value.op('->>')('polarity')
q = db.session.query(
db.func.count(polarity).label('count'),
## other fields
)\
.select_from(MyModel)\
.join(first_alias, sa.true())\
.join(second_alias, sa.true())\
# group by and order by here
.all()
该jsonb_each
函数不是从 Sqlalchemy 函数导入的。
添加回答
举报
0/150
提交
取消