【问题标题】:SQLAlchemy Pandas read_sql from jsonb来自 jsonb 的 SQLAlchemy Pandas read_sql
【发布时间】:2018-07-12 23:13:03
【问题描述】:

我想从我的 sqlalchemy 查询中生成一个带有 pandas read_sql 的数据框,并将 PostgreSQL 的 jsonb 属性添加到列。

其实这会给我我的答案:

query = session.query(
    cls.id,
    cls._my_jsonb_column
).all()
pd.DataFrame.from_dict([dict(id=id_, **i) for id_,i in query])

但我更喜欢用 PostgreSQL 解压 jsonb,而不是在应用程序中。

我的尝试给了

query = session.query(
    cls.id,
    func.jsonb_to_record(cls._my_jsonb_column)
)
pd.read_sql(query.statement, query.session.bind)

(psycopg2.NotSupportedError) 函数返回在不能接受类型记录的上下文中调用的记录

【问题讨论】:

    标签: postgresql sqlalchemy jsonb


    【解决方案1】:

    json_to_record(和jsonb_to_recordset)返回记录,就好像它是SELECT 查询的结果一样。在 sqlalchemy 上下文中,它提供了一个可以像表格一样使用的可选择项。

    因此,您应该将func.jsonb_to_record(cls._my_jsonb_column) 的结果视为一种可以加入原始表格的表格。

    也就是说你的查询应该是这样的:

    jsonb_data = func.jsonb_to_record(cls._my_jsonb_column)
    query = session.query(
        select(
            [cls.id, <other columns>]
        ).select_from(
            cls.join(jsonb_data, <on_clause>)
        )
    )
    

    您甚至可以使用 JSON processing functions 将 JSON 数据展平,但如果不知道 JSON 数据的结构,就不可能更精确。

    另外,我最近发布了一个包,可以轻松地从 json 数据的描述中展平 JSONB 字段,我很乐意收到一些反馈:pg_jsonb_flattener

    【讨论】:

      猜你喜欢
      • 2020-01-11
      • 2021-12-06
      • 2014-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多