基于lancedb的本地轻量知识库
配置
引入依赖
1 | npm install @lancedb/lancedb@preview |
连接数据库
1 | import * as lancedb from "@lancedb/lancedb"; |
常见API
Database 对象 (db)
db.tableNames() 获取所有表名
db.hasTable(name) 判断表是否存在
db.openTable(name) 打开已存在的表
db.createTable(name, rows, options?) 新建表
rows: JS 对象数组或 Arrow Table
options.vectorColumn: 指定向量列
options.vectorIndex: 指定索引(IVFFlat / HNSW 等)
1
2
3
4
5
6
7
8
9
10
11
12
13
14//建表时
await db.createTable("docs", rows, {
vectorColumn: "embedding", // 指定向量字段
vectorIndex: {
type: "IVFFlat", // 索引类型
metric: "cosine" // 相似度度量方式
}
});
//已有表上添加
await table.createIndex("embedding", {
type: "IVFFlat",
metric: "cosine"
});db.dropTable(name) 删除表
Table 对象 (table)
数据操作
table.add(rows) → 插入数据
table.update(rows, filter) → 更新数据(需带条件)
table.delete(filter) → 删除数据
查询
table.query() → 普通查询构造器
.where(“id > 2”)
.select([“id”, “text”])
.limit(5)
.toArray() → 执行查询并返回数组
1
2
3
4
5const result = await table.query()
.where("id > 2") // 条件过滤(支持 SQL-like 表达式)
.select(["id", "text"]) // 选择字段
.limit(5) // 限制返回条数
.toArray(); // 执行并返回数组table.vectorSearch(queryVector) → 向量搜索构造器
.limit(3)
.select([“id”, “text”])
.toArray()
1
2
3
4
5
6const queryVector = [0.1, 0.2, 0.3];
const result = await table.vectorSearch(queryVector)
.limit(3) // Top-K
.select(["id", "text"]) // 只取需要的字段
.toArray(); // 返回结果索引
table.createIndex(column, options) → 给指定列建索引
例:await table.createIndex(“vector”, { type: “IVFFlat”, metric: “cosine” })
- 查询结果
查询结果通常是一个 Array<{ …fields }>,带上你存的字段。
索引类型
IVFFlat
HNSW
DiskANN
度量方式(metric):
“cosine”
“l2”
“dot”
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 Pisland!
评论








