我有一個包含兩個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
提交
取消