You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ibis框架持久化数据库后端变更的技术咨询

Ibis框架数据持久化操作指南

问题0:理解确认

你的理解完全正确。Ibis中的Table是不可变的查询构建对象,每一步操作(关联、筛选、聚合等)都会基于原对象生成新的Table实例,本质是在构建SQL查询逻辑。只有调用execute()方法时,才会将这些逻辑编译为SQL并在数据库中执行,返回最终结果。它和数据库中物理存储的表不是同一个概念,更接近动态构建的SQL语句。


问题1:向表中插入新行

Ibis提供insert()方法实现数据插入,支持两种数据源:

从Python对象插入

可直接传入字典列表、pandas DataFrame等Python数据结构:

# 从字典列表插入
new_rows = [
    {'id': 101, 'name': 'Alice', 'age': 25},
    {'id': 102, 'name': 'Bob', 'age': 30}
]
con.insert('person', new_rows)

# 从pandas DataFrame插入(需提前安装pandas)
import pandas as pd
df = pd.DataFrame({'id': [103], 'name': ['Charlie'], 'age': [35]})
con.insert('person', df)

从Ibis Table查询结果插入

直接将查询得到的Table对象传入insert():

# 从temp_person表筛选符合条件的数据插入person
temp_table = con.table('temp_person')
filtered_data = temp_table.filter(temp_table.age > 18)
con.insert('person', filtered_data)

问题2:从表中删除行

使用delete()方法结合筛选条件定义删除范围,最后调用execute()执行:

# 删除age小于18的行
person_table.filter(person_table.age < 18).delete().execute()

# 删除特定id的行
person_table.filter(person_table.id == 101).delete().execute()

问题3:修改底层数据库表结构

Ibis支持常见的ALTER TABLE操作,可通过连接对象或表对象的专用方法实现:

添加列

# 方法1:通过表对象操作
person_table.add_column('email', 'string').execute()

# 方法2:通过连接对象批量添加
con.alter_table(
    'person',
    add_columns=[('email', 'string'), ('phone', 'varchar(20)')]
)

修改列类型

# 将age列类型从int改为bigint
person_table.alter_column('age', 'bigint').execute()

# 或者通过连接对象操作
con.alter_table('person', alter_columns=[('age', 'bigint')])

重命名列

# 将name列重命名为full_name
person_table.rename_column('name', 'full_name').execute()

# 或者通过连接对象操作
con.alter_table('person', rename_columns={'name': 'full_name'})

删除列

# 删除phone列
person_table.drop_column('phone').execute()

# 或者通过连接对象操作
con.alter_table('person', drop_columns=['phone'])

内容的提问来源于stack exchange,提问作者Sirion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 00:52:13