亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將帶有 jsonb_each 的 Postgresql 查詢轉換為 sqlalchemy

將帶有 jsonb_each 的 Postgresql 查詢轉換為 sqlalchemy

料青山看我應如是 2023-07-18 15:22:05
我有一個包含兩個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 函數導入的。



查看完整回答
反對 回復 2023-07-18
  • 1 回答
  • 0 關注
  • 93 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號