跳到主要内容

通过 Python 体验嵌入式

seekdb 提供了嵌入式产品形态,支持以库的形式集成在用户的应用程序中,为开发者提供更强大灵活的数据管理解决方案,让数据管理无处不在(微控制器、物联网设备、边缘计算、移动应用、数据中心等),让用户可以快速上手使用 seekdb All-in-one (TP、AP、AI Native)的产品能力。

python

安装配置

环境要求

  • 支持的操作系统:Linux(glibc >= 2.28)

  • 支持的 Python 版本:CPython 3.8 ~ 3.14

  • 支持的系统架构:x86_64、aarch64

可以执行以下命令,检查您的环境是否满足要求。

python3 -c 'import sys;import platform; print(f"Python: {platform.python_implementation()} {platform.python_version()}, System: {platform.system()} {platform.machine()}, {platform.libc_ver()[0]}: {platform.libc_ver()[1]}");'

返回结果如下:

Python: CPython 3.8.17, System: Linux x86_64, glibc: 2.32

安装

使用 pip 安装,会自动识别默认的 Python 版本和平台。

pip install pylibseekdb
# 或指定安装源加速
pip install pylibseekdb -i https://pypi.tuna.tsinghua.edu.cn/simple

如果您的 pip 版本比较低,请先升级 pip 后再安装:

pip install --upgrade pip

体验 seekdb

完成 seekdb 的安装后,就可以开始体验 seekdb 了。

注意事项

  • 不支持 multi stmt 语句,默认只执行第一条语句。示例如下:

    cur.execute("insert into t1 values(100);insert into t1 values(200)")
  • 不支持 tmpfs 文件系统作为数据库目录。

  • 只支持流式查询模式。示例如下:

    cur = con.cursor()
    cur.execute("select * from t1")
    cur.fetchall()
  • execute 方法不支持参数化。

体验 seekdb 基础操作

以下示例演示了 seekdb 的一些基础操作,您可以创建数据库、连接到数据库、创建表、写入和查询数据等。

信息

有关 seekdb 全量语法的详细介绍,参见 SQL 语法

seekdb 默认提供了 test 数据库。以下示例演示了如何使用默认参数打开 test 数据库并连接,以及完成建表、写数据、事务提交、查询和安全关闭数据库。

import pylibseekdb

# 默认打开数据库目录 seekdb
pylibseekdb.open()
# 默认连接 test 库
conn = pylibseekdb.connect()
# 创建游标进行数据操作
cursor = conn.cursor()

# 执行建表语句
cursor.execute("create table t1(c1 int primary key, c2 int)")
# 执行写入数据
cursor.execute("insert into t1 values(1, 100)")
cursor.execute("insert into t1 values(2, 200)")
# 手动提交事务
conn.commit()

# 执行查询
cursor.execute("select * from t1")
# 获取结果
print(cursor.fetchall())

# 关闭连接
cursor.close()
conn.close()

您也可以手动指定数据库目录,并创建和使用新库。

import pylibseekdb

# 指定数据库目录
pylibseekdb.open("mydb")
# 不连接任何库
conn = pylibseekdb.connect("")
# 创建游标进行数据操作
cursor = conn.cursor()
# 手动创建库
cursor.execute("create database db1")
# 使用新创建的库
cursor.execute("use db1")

# 关闭连接
cursor.close()
conn.close()

以下示例演示了如何开启事务自动提交模式。

import pylibseekdb

# 指定数据库目录
pylibseekdb.open("seekdb")
# 连接test库
conn = pylibseekdb.connect(database="test", autocommit=True)
# 创建游标进行数据操作
cursor = conn.cursor()

# 执行建表语句
cursor.execute("create table t2(c1 int primary key, c2 int)")
# 执行写入数据, 事务自动提交
cursor.execute("insert into t2 values(1, 100)")
# 执行写入数据, 事务自动提交
cursor.execute("insert into t2 values(2, 200)")

# 使用新连接查询数据
conn2 = pylibseekdb.connect("test")
cursor2=conn2.cursor()
cursor2.execute("select * from t2")
# 逐行查看数据
print(cursor2.fetchone())
print(cursor2.fetchone())

# 关闭连接
cursor.close()
conn.close()
cursor2.close()
conn2.close()

体验 seekdb

体验 AI Native

体验向量搜索

seekdb 最高支持 16000 维的 Float 类型的稠密向量,支持稀疏向量,支持曼哈顿距离、欧式距离、内积、余弦距离等多种类型向量距离的计算,支持基于 HNSW/IVF 向量索引的创建,支持增量更新删除,同时增量更新删除操作不会影响召回率。

信息

关于 seekdb 向量搜索更详细的介绍,参见 向量搜索

以下示例演示了在 seekdb 中如何使用向量搜索。

import pylibseekdb

pylibseekdb.open("seekdb")
conn = pylibseekdb.connect("test")
cursor = conn.cursor()

# 创建包含向量索引的表
cursor.execute("create table test_vector(c1 int primary key, c2 vector(2), vector index idx1(c2) with (distance=l2, type=hnsw, lib=vsag))")

# 写入数据
cursor.execute("insert into test_vector values(1, [1, 1])")
cursor.execute("insert into test_vector values(2, [1, 2])")
cursor.execute("insert into test_vector values(3, [1, 3])")
conn.commit()

# 执行向量搜索
cursor.execute("SELECT c1,c2 FROM test_vector ORDER BY l2_distance(c2, '[1, 2.5]') APPROXIMATE LIMIT 2;")
# 获取结果
print(cursor.fetchall())

# 关闭连接
cursor.close()
conn.close()

体验全文搜索

seekdb 提供了全文索引能力。通过构建全文索引,能够对整个文档或大段文本内容进行全面的索引,从而在面对大规模文本数据和复杂搜索需求时,显著提高查询性能,使得用户能够更高效地获取所需信息。

以下示例演示了如何使用 seekdb 的全文搜索功能。

import pylibseekdb

pylibseekdb.open("seekdb")
conn = pylibseekdb.connect("test")
cursor = conn.cursor()

# 创建包含全文索引的表
sql='''create table articles (title VARCHAR(200) primary key, body Text,
FULLTEXT fts_idx(title, body));
'''
cursor.execute(sql)

# 写入数据
sql='''insert into articles(title, body) values
('OceanBase Tutorial', 'This is a tutorial about OceanBase Fulltext.'),
('Fulltext Index', 'Fulltext index can be very useful.'),
('OceanBase Test Case', 'Writing test cases helps ensure quality.')
'''
cursor.execute(sql)
conn.commit()

# 执行全文搜索
sql='''select
title,
match (title, body) against ("OceanBase") as score
from
articles
where
match (title, body) against ("OceanBase")
order by
score desc
'''
cursor.execute(sql)
# 获取结果
print(cursor.fetchall())

# 关闭连接
cursor.close()
conn.close()

体验混合搜索

混合搜索(Hybrid Search)结合了基于向量的语义搜索和基于全文索引的关键词搜索,通过综合排序提供更准确、全面的搜索结果。向量搜索擅长语义近似匹配,但对精确的关键字、数字和专有名词等匹配能力较弱,而全文搜索能有效弥补这一不足。因此,混合搜索已成为向量数据库的关键特性之一,广泛应用于各类产品中。

seekdb 基于多模一体化,在 SQL+AI 的基础上,提供了面向多模数据的混合搜索能力,能够在一套数据库系统里实现对多种数据的融合查询。

以下示例演示了如何使用 seekdb 的混合搜索功能。

import pylibseekdb

pylibseekdb.open("seekdb")
conn = pylibseekdb.connect("test")
cursor = conn.cursor()

# 创建包含向量索引、全文索引的表
cursor.execute("create table doc_table(c1 int, vector vector(3), query varchar(255), content varchar(255), vector index idx1(vector) with (distance=l2, type=hnsw, lib=vsag), fulltext idx2(query), fulltext idx3(content))")

# 写入数据
sql = '''insert into doc_table values(1, '[1,2,3]', "hello world", "oceanbase Elasticsearch database"),
(2, '[1,2,1]', "hello world, what is your name", "oceanbase mysql database"),
(3, '[1,1,1]', "hello world, how are you", "oceanbase oracle database"),
(4, '[1,3,1]', "real world, where are you from", "postgres oracle database"),
(5, '[1,3,2]', "real world, how old are you", "redis oracle database"),
(6, '[2,1,1]', "hello world, where are you from", "starrocks oceanbase database");'''
cursor.execute(sql)
conn.commit()


sql = '''set @parm = '{
"query": {
"bool": {
"must": [
{"match": {"query": "hi hello"}},
{"match": { "content": "oceanbase mysql" }}
]
}
},
"knn" : {
"field": "vector",
"k": 5,
"num_candidates": 10,
"query_vector": [1,2,3],
"boost": 0.7
},
"_source" : ["query", "content", "_keyword_score", "_semantic_score"]
}';'''
cursor.execute(sql)

# 执行混合搜索
sql = '''select dbms_hybrid_search.search('doc_table', @parm);'''
cursor.execute(sql)
# 获取结果
print(cursor.fetchall())

# 关闭连接
cursor.close()
conn.close()

体验分析能力(OLAP)

seekdb 实现了事务处理(TP)与分析处理(AP)的结合。依托 LSM-Tree 架构,实现行存列存存储一体化,同时推出了基于列存的全新向量化引擎以及代价评估模型,大幅提升了处理宽表的效率,显著增强了 AP 场景下的查询性能,同时也支持了实时导入、二级索引、高并发主键查询等实时 OLAP 常见需求。

体验数据导入

seekdb 支持了多种灵活的数据入库方式,可以将多种数据源的数据导入到数据库中。不同的导入方式适用于不同的场景,可以根据数据源类型、业务场景,选择合适的导数工具进行数据入库,随着场景的复杂多变,多种导入方式可以配合使用。在数据入库时,除了考虑数据源、数据文件格式也会考虑导数工具的支持情况。当业务场景已经明确数据源、数据文件格式时,需要从数据源出发,并结合导数工具来考虑导数方案的设计;当业务有熟练使用的导数工具时,需要考虑工具的支持情况,结合业务场景考虑导数的可能性。

以下示例以 load data 方式为例介绍如何快速导入 csv 数据到 seekdb 中。

  1. 创建外部数据源

    cat /data/1/example.csv
    1,10
    2,20
    3,30
  2. 使用嵌入式方式导入外部数据。

    import pylibseekdb

    pylibseekdb.open("seekdb")
    conn = pylibseekdb.connect("test")
    cursor = conn.cursor()

    # 创建表
    cursor.execute("create table test_olap(c1 int, c2 int)")
    # 执行快速导入
    cursor.execute("load data /*+ direct(true, 0) */ infile '/data/1/example.csv' into table test_olap fields terminated by ','")
    # 查询数据
    cursor.execute("select count(*) from test_olap")
    # 获取结果
    print(cursor.fetchall())

    # 关闭连接
    cursor.close()
    conn.close()

体验列存

在大规模数据复杂分析或海量数据即席查询场景中,列式存储是 AP 数据库的关键能力之一。seekdb 存储引擎在支持行存的基础上进一步增强,实现了对列存的支持,实现了存储一体化,一套代码一个架构一个实例,列存数据和行存数据共存。

以下本示例演示了如何在 seekdb 中创建列存表。

import pylibseekdb

pylibseekdb.open("seekdb")
conn = pylibseekdb.connect("test")
cursor = conn.cursor()

# 创建列存表
sql='''create table each_column_group (col1 varchar(30) not null, col2 varchar(30) not null, col3 varchar(30) not null, col4 varchar(30) not null, col5 int)
with column group (each column);
'''
cursor.execute(sql)

# 写入数据
sql='''insert into each_column_group values('a', 'b', 'c', 'd', 1)
'''
cursor.execute(sql)
conn.commit()

# 执行查询
cursor.execute("select col1,col2 from each_column_group")

# 获取结果
print(cursor.fetchall())

# 关闭连接
cursor.close()
conn.close()

体验物化视图

物化视图(Materialized View,MV)是支撑 AP 业务的一个关键特性,它通过预计算和存储视图的查询结果,减少实时计算,从而提升查询性能并简化复杂查询逻辑,常用于快速报表生成和数据分析场景。seekdb 支持了非实时和实时物化视图,支持为物化视图指定主键或创建索引,并引入了嵌套物化视图,能够游侠提升查询性能。

以下示例演示如何在 seekdb 中使用物化视图。

import pylibseekdb
import time

pylibseekdb.open("seekdb")
conn = pylibseekdb.connect("test")
cursor = conn.cursor()

# 创建基表
cursor.execute("create table base_t1(a int primary key, b int)")
cursor.execute("create table base_t2(c int primary key, d int)")

# 创建物化视图日志
cursor.execute("create materialized view log on base_t1 with(b)")
cursor.execute("create materialized view log on base_t2 with(d)")

# 基于表 base_t1 和 base_t2 创建名为 mv 的物化视图,指定物化视图的刷新策略为增量刷新,物化视图的刷新计划中初始刷新时间为当前日期,之后每隔 1 秒刷新一次物化视图。。
cursor.execute("create materialized view mv REFRESH fast START WITH sysdate() NEXT sysdate() + INTERVAL 1 second as select a,b,c,d from base_t1 join base_t2 on base_t1.a=base_t2.c")

# 基表写入数据
cursor.execute("insert into base_t1 values(1, 10)")
cursor.execute("insert into base_t2 values(1, 100)")
conn.commit()

# 等待物化视图后台刷新完成
time.sleep(10)

# 查询数据
cursor.execute("select * from mv")
# 获取结果
print(cursor.fetchall())

# 关闭连接
cursor.close()
conn.close()

体验外表

通常,数据库中的表数据存放在数据库的存储空间中,而外表的数据存储在外部存储服务中。创建外表时,需要定义数据文件路径和数据文件的格式。创建成功后,用户就可以通过外表从外部存储服务中读取文件中的数据。

以下示例如何通过 seekdb 的外表功能访问外部 csv 文件。

  1. 创建外部数据源

    cat /data/1/example.csv
    1,10
    2,20
    3,30
  2. 使用嵌入式方式访问外表数据

    import pylibseekdb

    pylibseekdb.open("seekdb")
    conn = pylibseekdb.connect("test")
    cursor = conn.cursor()

    # 创建外表
    sql='''CREATE EXTERNAL TABLE test_external_table(c1 int, c2 int) LOCATION='/data/1' FORMAT=(TYPE='CSV' FIELD_DELIMITER=',') PATTERN='example.csv';
    '''
    cursor.execute(sql)

    # 查询数据
    cursor.execute("select * from test_external_table")

    # 获取结果
    print(cursor.fetchall())

    # 关闭连接
    cursor.close()
    conn.close()

体验事务能力(OLTP)

以下示例演示了 seekdb 的事务能力。

import pylibseekdb

pylibseekdb.open("seekdb")
conn = pylibseekdb.connect("test")
cursor = conn.cursor()

# 创建表
cursor.execute("create table test_oltp(c1 int primary key, c2 int)")

# 写入数据
cursor.execute("insert into test_oltp values(1, 10)")
cursor.execute("insert into test_oltp values(2, 20)")
cursor.execute("insert into test_oltp values(3, 30)")
# 事务提交
conn.commit()

# 查询数据,ORA_ROWSCN即为数据提交版本号
cursor.execute("select *,ORA_ROWSCN from test_oltp")
# 获取结果
print(cursor.fetchall())

# 关闭连接
cursor.close()
conn.close()

平滑切换至分布式版本

用户通过嵌入式版本快速验证好产品原型后,如果想切换至 seekdb Server 模式或者使用 OceanBase 分布式版本的集群处理能力,只需要修改导入包和相关配置即可,主体应用逻辑保持不变。

import pylibseekdb
pylibseekdb.open()
conn = pylibseekdb.connect()

只需要将上面的三行修改为下面的两行,使用 pymysql 包替换 pylibseekdb,去掉 pylibseekdb 的 open 阶段,使用 pymysql 的 connect 方法连接数据库服务器。

import pymysql
conn = pymysql.connect(host='127.0.0.1', port=11002, user='root@sys', database='test')