chdb-core 是 chDB 生态的基础引擎 - 一个由 ClickHouse 驱动的进程内 SQL OLAP 引擎 1
chDB 项目拆分为两个包:
| 包 | 定位 | 安装 |
|---|---|---|
| chdb-core(本仓库) | C++ 引擎 + Session / Connection / DB-API 接口 | pip install chdb-core |
| chDB | 基于 chdb-core 构建的 Pandas 兼容 DataStore API | pip install chdb |
┌───────────────────────────────────────────┐ │ chDB (pip install chdb) │ │ ┌─────────────────────────────────────┐ │ │ │ DataStore: pandas-like lazy API │ │ │ │ QueryPlanner / dual-engine exec │ │ │ └──────────────────┬──────────────────┘ │ │ │ │ │ ┌──────────────────▼──────────────────┐ │ │ │ chdb-core (pip install chdb-core) │ │ │ │ C++ ClickHouse Engine │ │ │ │ Session / Connection / DB-API │ │ │ │ query() / UDF / Stream │ │ │ └─────────────────────────────────────┘ │ └───────────────────────────────────────────┘
chdb-core 提供了使用 ClickHouse 性能运行 SQL 查询所需的一切 - 无需安装服务器。如果需要更高层次的 Pandas 兼容 DataFrame API,请安装 chDB。
- 由 ClickHouse 驱动的进程内 SQL OLAP 引擎
- 无需安装 ClickHouse
- 通过 python memoryview 最小化 C++ 到 Python 的数据拷贝
- 输入输出支持 Parquet、CSV、JSON、Arrow、ORC 等 60+ 种格式
- Session 和 Connection 管理,支持有状态查询
- 流式查询支持,常量内存处理大数据集
- 兼容 Python DB-API 2.0
- 支持用户自定义函数(UDF)
- AI 辅助 SQL 生成
目前 chdb-core 支持 macOS 和 Linux(x86_64 及 ARM64)上的 Python 3.9+。
pip install chdb-coreimport chdb
result = chdb.query("SELECT version()", "Pretty")
print(result)一次性查询
最简单的 SQL 执行方式 - 无需 session 或 connection:
import chdb
# 基本查询,默认 CSV 输出
result = chdb.query("SELECT 1, 'hello'")
print(result)
# Pandas DataFrame 输出
df = chdb.query("SELECT number, number * 2 AS double FROM numbers(10)", "DataFrame")
print(df)
# 参数化查询
df = chdb.query(
"SELECT toDate({base_date:String}) + number AS date "
"FROM numbers({total_days:UInt64}) "
"LIMIT {items_per_page:UInt64}",
"DataFrame",
params={"base_date": "2025-01-01", "total_days": 10, "items_per_page": 5},
)
print(df)查询文件(Parquet、CSV、JSON、Arrow、ORC 等 60+ 种格式)
import chdb
res = chdb.query('SELECT * FROM file("data.parquet", Parquet)', "JSON")
print(res)
res = chdb.query('SELECT * FROM file("data.csv", CSV)', "CSV")
print(res)
# 查询结果统计
print(f"SQL read {res.rows_read()} rows, {res.bytes_read()} bytes, "
f"storage read {res.storage_rows_read()} rows, {res.storage_bytes_read()} bytes, "
f"elapsed {res.elapsed()} seconds")
# Pandas DataFrame 输出
chdb.query('SELECT * FROM file("data.parquet", Parquet)', "Dataframe")Connection API
基于连接的 API,支持游标风格交互,同时支持内存数据库和基于文件的持久化数据库:
import chdb
conn = chdb.connect(":memory:")
cur = conn.cursor()
cur.execute("CREATE TABLE test (id UInt32, name String) ENGINE = Memory")
cur.execute("INSERT INTO test VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie')")
cur.execute("SELECT * FROM test ORDER BY id")
print(cur.fetchone()) # (1, 'Alice')
print(cur.fetchmany(2)) # ((2, 'Bob'), (3, 'Charlie'))
print(cur.column_names()) # ['id', 'name']
print(cur.column_types()) # ['UInt32', 'String']
# 将游标用作迭代器
cur.execute("SELECT number FROM system.numbers LIMIT 3")
for row in cur:
print(row)
# 使用完毕后关闭资源
cur.close()
conn.close()更多详情见 examples/connect.py。
# 基于文件的持久化数据库
conn = chdb.connect("mydata.db")
conn.query("CREATE TABLE IF NOT EXISTS logs (ts DateTime, msg String) ENGINE = MergeTree ORDER BY ts")
conn.query("INSERT INTO logs VALUES (now(), 'started')")
result = conn.query("SELECT * FROM logs", "Pretty")
print(result)
conn.close()有状态 Session
Session 提供了更高层次的 API,支持自动资源管理:
from chdb import session as chs
sess = chs.Session()
sess.query("CREATE DATABASE IF NOT EXISTS db_xxx ENGINE = Atomic")
sess.query("CREATE TABLE IF NOT EXISTS db_xxx.log_table (x String, y Int) ENGINE = Log")
sess.query("INSERT INTO db_xxx.log_table VALUES ('a', 1), ('b', 3), ('c', 2), ('d', 5)")
sess.query("CREATE VIEW db_xxx.view_xxx AS SELECT * FROM db_xxx.log_table LIMIT 4")
print(sess.query("SELECT * FROM db_xxx.view_xxx", "Pretty"))另见: test_stateful.py。
流式查询
通过分块流式处理大数据集,保持恒定内存使用:
from chdb import session as chs
sess = chs.Session()
rows_cnt = 0
with sess.send_query("SELECT * FROM numbers(200000)", "CSV") as stream_result:
for chunk in stream_result:
rows_cnt += chunk.rows_read()
print(rows_cnt) # 200000
# 示例 2:使用 fetch() 手动迭代
rows_cnt = 0
stream_result = sess.send_query("SELECT * FROM numbers(200000)", "CSV")
while True:
chunk = stream_result.fetch()
if chunk is None:
break
rows_cnt += chunk.rows_read()
print(rows_cnt) # 200000更多详情见 test_streaming_query.py。
Python DB-API 2.0
import chdb.dbapi as dbapi
print("chdb driver version: {0}".format(dbapi.get_client_info()))
conn1 = dbapi.connect()
cur1 = conn1.cursor()
cur1.execute('select version()')
print("description: ", cur1.description)
print("data: ", cur1.fetchone())
cur1.close()
conn1.close()查询表(Pandas DataFrame、Parquet 文件/字节、Arrow 字节)
import chdb.dataframe as cdf
import pandas as pd
# 关联两个 DataFrame
df1 = pd.DataFrame({'a': [1, 2, 3], 'b': ["one", "two", "three"]})
df2 = pd.DataFrame({'c': [1, 2, 3], 'd': ["①", "②", "③"]})
ret_tbl = cdf.query(sql="select * from __tbl1__ t1 join __tbl2__ t2 on t1.a = t2.c",
tbl1=df1, tbl2=df2)
print(ret_tbl)
# 在 DataFrame Table 上继续查询
print(ret_tbl.query('select b, sum(a) from __table__ group by b'))
# Pandas DataFrame 会自动注册为 ClickHouse 中的临时表
chdb.query("SELECT * FROM Python(df1) t1 JOIN Python(df2) t2 ON t1.a = t2.c").show()Python Table Engine
import chdb
import pandas as pd
df = pd.DataFrame(
{
"a": [1, 2, 3, 4, 5, 6],
"b": ["tom", "jerry", "auxten", "tom", "jerry", "auxten"],
}
)
chdb.query("SELECT b, sum(a) FROM Python(df) GROUP BY b ORDER BY b").show()import chdb
import pyarrow as pa
arrow_table = pa.table(
{
"a": [1, 2, 3, 4, 5, 6],
"b": ["tom", "jerry", "auxten", "tom", "jerry", "auxten"],
}
)
chdb.query("SELECT b, sum(a) FROM Python(arrow_table) GROUP BY b ORDER BY b").show()另见: test_query_py.py。
用户自定义函数(UDF)
chDB 支持原生 Python UDF,在进程内直接运行,具备完整的类型安全。
import chdb
from chdb.session import Session
from chdb.sqltypes import INT64, STRING
sess = Session()
# 使用 @chdb.func 装饰器
@chdb.func([INT64, INT64], INT64)
def add(a, b):
return a + b
print(sess.query("SELECT add(12, 22)"))
# 通过类型注解自动推断类型
@chdb.func()
def multiply(a: int, b: int) -> int:
return a * b
print(sess.query("SELECT multiply(3, 7)"))
# 使用 chdb.create_function 直接注册
chdb.create_function("strlen", len, arg_types=[STRING], return_type=INT64)
print(sess.query("SELECT strlen('hello')"))
# 移除已注册的函数
chdb.drop_function("strlen")主要特性:
- 类型安全:支持
INT64、FLOAT64、STRING、BOOL、DATETIME64等,完整列表参见 chdb.sqltypes。 - 类型推断:从 Python 类型注解自动推断(
int、str、bool等) - NULL 处理:
on_null=NullHandling.SKIP(默认)跳过函数调用并返回 NULL;NullHandling.PASS将None传入函数。 - 异常处理:
on_error=ExceptionHandling.PROPAGATE(默认)将异常抛给调用方;ExceptionHandling.IGNORE对该行返回 NULL 并继续执行。
查询进度
import chdb
# 自动检测:终端中显示文本进度,Notebook 中显示进度条
conn = chdb.connect(":memory:?progress=auto")
conn.query("SELECT sum(number) FROM numbers_mt(1e10) GROUP BY number % 10 SETTINGS max_threads=4")进度选项:progress=auto | progress=tty | progress=err | progress=off
AI 辅助 SQL 生成
import chdb
conn = chdb.connect("file::memory:?ai_provider=openai&ai_model=gpt-4o-mini")
conn.query("CREATE TABLE nums (n UInt32) ENGINE = Memory")
conn.query("INSERT INTO nums VALUES (1), (2), (3)")
sql = conn.generate_sql("Select all rows from nums ordered by n desc")
print(sql) # SELECT * FROM nums ORDER BY n DESC
print(conn.ask("List the numbers table", format="Pretty"))命令行
python3 -m chdb SQL [OutputFormat]
python3 -m chdb "SELECT 1,'abc'" Pretty- 项目文档 和 使用示例
- Colab Notebooks 和其他脚本示例
---
- chDB 相关示例和文档请参考 chDB 文档
- SQL 语法请参考 ClickHouse SQL 参考
- Pandas 风格的 DataStore API 请参考 chDB
chDB 提供了 AI Skill,可以教会 AI 编程助手(Cursor、Claude Code 等)使用 chDB 的多源数据分析 API。安装后,你的 AI 助手就能开箱即用地编写正确的 chDB 代码:
curl -sL https://raw.githubusercontent.com/chdb-io/chdb/main/install_skill.sh | bash- 在 ClickHouse v23.7 livehouse! 演示 chDB 以及 幻灯片
贡献使得开源社区成为一个令人惊叹的学习、启发和创造的地方。我们非常感谢你的任何贡献。
- 帮助测试和报告 Bug
- 帮助改善文档
- 帮助提升代码质量和性能
我们欢迎其他语言的绑定,详情请参考 bindings。
详情请参考 VERSION-GUIDE.md。
Apache 2.0,详情见 LICENSE。
chDB 主要基于 ClickHouse 1 出于商标等原因,我将其命名为 chDB。
- Discord: https://discord.gg/D2Daa2fM5K
- Email: auxten@clickhouse.com
- Twitter: @chdb

