我有一个包含两个jsonb_each语句的查询,我需要将其转换为 sqlalchemy。我尝试过使用子查询、别名,甚至 fnop来逐字翻译查询,但失败并显示InternalError.
我特别困惑的是我不知道如何访问{key: value}从第一个函数返回的对jsonb_each。
这就是我到目前为止所拥有的
v = column('value', type_=JSONB)
k = column('key', type_=JSONB)
polarity = v['polarity'].astext
q = 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_content
SELECT
count(d.value ->> 'polarity') as count,
d.value ->> 'polarity' as polarity,
d.key as key
from myTable t
join jsonb_each(t.json_content -> 'myMap') m on true
join jsonb_each((m.value -> 'data') - 'text') d on true
group by d.value ->> 'polarity', d.key;
我想要得到的结果集
count polarity category
----------------------------
1 positive cate2
1 positive cate4
2 negative cate1
1 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"
}
}
}
}
}
如果需要更多信息,请告诉我
MMTTMM
相关分类