内容
# 本地向量数据库
一款高性能、以文档为中心的向量数据库,支持 SQLite + FAISS 作为后端,提供智能分段、统一搜索和可选的 HTTP 服务器。
[](LICENSE)
## ✨ 功能特点
### 🗃️ **以文档为中心架构**
- **智能分段**:具有完美文档重建的位置跟踪分段
- **元数据模式**:具有验证的结构化、索引元数据字段
- **统一 API**:向量、关键词和混合搜索的单一接口
### 🔍 **高级搜索**
- **向量搜索**:使用 Ollama 或 OpenAI 嵌入的语义相似性
- **关键词搜索**:使用 SQLite FTS5 的全文搜索
- **混合搜索**:可配置权重的向量 + 关键词组合
- **元数据过滤**:结构化元数据上的类 SQL 查询
### 🌐 **灵活部署**
- **本地数据库**:直接使用 SQLite + FAISS 以获得最大性能
- **HTTP 服务器**:具有基于权限的身份验证、速率限制和 CORS 的 RESTful API
- **远程客户端**:通过工厂模式实现无缝本地/远程切换
- **多工作进程**:基于 Redis 的分布式部署协调
### 📄 **文件处理**
- **文本提取**:支持 PDF、DOCX、PPTX、XLSX、RTF、EPUB
- **批量上传**:多文件处理与元数据提取
- **格式检测**:自动 MIME 类型检测和处理
### 🤖 **AI / LLM 集成**
- **MCP 服务器**:内置 [模型上下文协议](https://modelcontextprotocol.io/) 服务器,适用于 Claude Desktop、Claude Code 等 MCP 客户端
- **默认只读**:安全的知识库访问;显式选择读写
- **TypeScript SDK**:一流的浏览器/节点客户端 (`@localvectordb/sdk`)
### 🛠️ **开发者体验**
- **CLI 工具**:数据库管理、服务器控制、交互式 Shell
- **配置**:支持环境变量的 TOML/JSON 配置
- **全面日志记录**:具有性能监控的结构化日志记录
- **类型安全**:完整的类型注释和验证
## 🚀 快速入门
### 安装
```bash
pip install localvectordb
# 可选:安装服务器功能
pip install localvectordb[server]
# 可选:安装所有文件提取格式
pip install localvectordb[server,file-extraction]
```
### 基本用法
```python
from localvectordb import VectorDB
# 创建或连接数据库
db = VectorDB("my_docs", "./data")
# 添加文档
doc_ids = db.upsert([
"Python 是一种编程语言",
"使用神经网络进行机器学习"
])
# 搜索文档
results = db.query("programming", k=5)
for result in results:
print(f"{result.id}: {result.content} (score: {result.score:.3f})")
# 获取特定文档
doc = db.get(doc_ids[0])
print(f"内容:{doc.content}")
```
### 含元数据模式
```python
from localvectordb import VectorDB
from localvectordb.core import MetadataField, MetadataFieldType
# 定义元数据模式
schema = {
'title': MetadataField(type=MetadataFieldType.TEXT, indexed=True),
'author': MetadataField(type=MetadataFieldType.TEXT, indexed=True),
'created_date': MetadataField(type=MetadataFieldType.DATE, indexed=True),
'tags': MetadataField(type=MetadataFieldType.JSON)
}
db = VectorDB("articles", "./data", metadata_schema=schema)
# 添加带有元数据的文档
db.upsert(
documents=["关于 Python 编程的文章"],
metadata=[{
'title': 'Python 指南',
'author': 'Jane Doe',
'created_date': '2024-01-15',
'tags': ['python', 'programming', 'tutorial']
}]
)
# 搜索并过滤元数据
results = db.query(
"programming tutorial",
filters={'author': 'Jane Doe', 'tags': {'contains': 'python'}}
)
```
### 远程服务器用法
```python
from localvectordb import VectorDB
# 使用 HTTP 服务器(通过 URL 自动检测)
db = VectorDB(
"my_docs",
"http://localhost:5000",
api_key="your_api_key"
)
# 与本地数据库相同的 API
doc_ids = db.upsert(["远程文档内容"])
results = db.query("content", search_type="hybrid")
```
## 🖥️ 服务器部署
### 启动服务器
```bash
# 快速启动,默认配置
lvdb serve
# 生产环境配置
lvdb serve --host 0.0.0.0 --port 5000 --config ./config.toml
```
### 配置
创建配置文件:
```bash
# 交互式设置向导
lvdb config init --interactive
# 生产环境设置,启用 Redis
lvdb config init --redis-registry redis://localhost:6379/1 \
--enable-cache --cache-type redis \
--enable-rate-limiting --enable-cors \
--enable-auth
```
示例配置文件 (`config.toml`):
```toml
[database]
root_dir = "./databases"
chunk_size = 500
chunking_method = "sentences"
chunk_overlap = 1
[embedding]
provider = "ollama"
model = "nomic-embed-text"
[server]
host = "0.0.0.0"
port = 5000
require_api_key = true
enable_rate_limiting = true
rate_limit = "100 per minute"
cors_enabled = true
cors_allowed_origins = ["http://localhost:3000"]
```
### API 密钥管理
```bash
# 创建具有权限级别的 API 密钥
lvdb auth create-key --description "生产 API" --permission-level read_write
# 为分析创建只读密钥
lvdb auth create-key --description "分析仪表盘" --permission-level read_only
# 列出具有权限的密钥
lvdb auth list-keys --active-only
# 撤销密钥
lvdb auth revoke-key key_20241201_abc123
```
## 🤖 MCP 服务器(Claude Desktop / Claude Code)
本地向量数据库自带一个 [模型上下文协议](https://modelcontextprotocol.io/) 服务器,允许 LLM 代理直接搜索和管理向量数据库。它与 **Claude Desktop**、**Claude Code** 和其他 MCP 客户端兼容。
```bash
# 安装支持 MCP
pip install localvectordb[mcp]
# 启动服务器(默认只读 - 安全用于知识库)
lvdb mcp serve
# 需要时启用写入
lvdb mcp serve --mode read-write
```
在 Claude Desktop 中注册(`claude_desktop_config.json`):
```json
{
"mcpServers": {
"localvectordb": {
"command": "lvdb",
"args": ["mcp", "serve"],
"env": {
"LVDB_MCP_MODE": "read-only",
"LVDB_MCP_DATABASES_ROOT": "/path/to/databases"
}
}
}
}
```
服务器暴露了专注的工具 - `query_database`、`filter_documents`、`get_document`、`list_databases`,以及(在读写模式下)`upsert_documents`、`create_database` 等。工具集可按部署配置。参见 [MCP 文档](https://thomas-villani.github.io/localvectordb/mcp.html),获取完整的工具列表、配置和安全指南。
## 🟦 TypeScript SDK
为 HTTP 服务器提供了一个零依赖的 TypeScript/JavaScript 客户端(Node.js 18+ 和现代浏览器):
```bash
npm install @localvectordb/sdk
```
```typescript
import { LocalVectorDBClient } from "@localvectordb/sdk";
const client = new LocalVectorDBClient({ baseUrl: "http://localhost:5000" });
const db = client.database("my_docs");
await db.upsert(["第一个文档", "第二个文档"]);
const results = await db.query("search text", { search_type: "hybrid", k: 5 });
```
参见 [`sdk/js/README.md`](sdk/js/README.md),获取完整的 SDK API。
## 📚 API 参考
### 核心方法
#### `upsert(documents, metadata=None, ids=None)`
插入或更新文档。
```python
# 单个文档
db.upsert("文档内容")
# 多个文档,带元数据
doc_ids = db.upsert(
documents=["文档 1", "文档 2"],
metadata=[{"type": "article"}, {"type": "blog"}],
ids=["doc_1", "doc_2"]
)
```
#### `query(query, search_type='vector', k=10, filters=None)`
统一搜索接口。
```python
# 向量搜索
results = db.query("搜索文本", search_type="vector", k=5)
# 混合搜索,带元数据过滤
results = db.query(
"机器学习",
search_type="hybrid",
vector_weight=0.7,
filters={"category": "AI"}
)
# 关键词搜索
results = db.query("精确短语", search_type="keyword")
```
#### `get(ids)` / `delete(ids)` / `exists(ids)`
文档管理。
```python
# 单个文档
doc = db.get("doc_1")
exists = db.exists("doc_1")
deleted_count = db.delete("doc_1")
# 多个文档
docs = db.get(["doc_1", "doc_2"])
exist_flags = db.exists(["doc_1", "doc_2"])
deleted_count = db.delete(["doc_1", "doc_2"])
```
#### `filter(where=None, sql=None, order_by=None, limit=None)`
基于元数据的类似 SQL 的过滤。
```python
# 简单过滤
docs = db.filter(where={"author": "Jane Doe", "status": "published"})
# 复杂查询
docs = db.filter(
where={"created_date": {">=": "2024-01-01"}},
order_by="created_date DESC",
limit=10
)
# 原始 SQL
docs = db.filter(sql="author LIKE '%Smith%' AND rating > 4.0")
```
### HTTP API 端点
| 方法 | 端点 | 描述 |
|--------|----------|-------------|
| `GET` | `/api/v1/databases` | 列出数据库 |
| `POST` | `/api/v1/databases` | 创建数据库 |
| `GET` | `/api/v1/{db}/info` | 数据库信息 |
| `POST` | `/api/v1/{db}/documents` | 插入/更新文档 |
| `GET` | `/api/v1/{db}/documents/{id}` | 获取文档 |
| `PUT` | `/api/v1/{db}/documents/{id}` | 更新文档 |
| `DELETE` | `/api/v1/{db}/documents/{id}` | 删除文档 |
| `POST` | `/api/v1/{db}/query` | 搜索文档 |
| `POST` | `/api/v1/{db}/query/stream` | 流式结果(SSE) |
| `POST` | `/api/v1/{db}/filter` | 过滤文档 |
| `POST` | `/api/v1/{db}/upload` | 上传文件 |
| `POST` | `/api/v1/{db}/compare` | 比较文档 |
| `POST` | `/api/v1/{db}/nearest-neighbors` | 查找相似文档 |
| `POST` | `/api/v1/{db}/factcheck` | 事实核查文本 |
示例 API 用法:
```bash
# 创建数据库
curl -X POST http://localhost:5000/api/v1/databases \
-H "Authorization: Bearer your_api_key" \
-H "Content-Type: application/json" \
-d '{"name": "my_db"}'
# 搜索文档
curl -X POST http://localhost:5000/api/v1/my_db/query \
-H "Authorization: Bearer your_api_key" \
-H "Content-Type: application/json" \
-d '{"query": "机器学习", "search_type": "hybrid", "k": 5}'
```
## 🛠️ CLI 参考
### 数据库管理
```bash
# 列出数据库
lvdb list --details
# 创建数据库
lvdb create mydb --embedding-model nomic-embed-text --chunk-size 500
# 删除数据库
lvdb delete mydb --confirm
```
### 数据库操作
```bash
# 添加文档
lvdb db mydb add document.txt
lvdb db mydb add "docs/*.py"
cat content.txt | lvdb db mydb add -
# 搜索文档
lvdb db mydb search "查询文本" --search-type hybrid --limit 10
# 获取文档
lvdb db mydb get doc_1 --json --metadata
# 交互式 Shell
lvdb db mydb shell
```
### 配置
```bash
# 查看配置
lvdb config show --section database
# 更新设置
lvdb config set server.port 8080
lvdb config set database.chunk_size 1000
```
## 🏗️ 架构
### 本地架构
```
┌─────────────────┐ ┌───────────────┐ ┌─────────────┐
│ 应用程序 │────│ 本地向量数据库 │────│ SQLite │
└─────────────────┘ └───────────────┘ └─────────────┘
│
┌──────────────┐
│ FAISS │
│ 索引 │
└──────────────┘
```
### 服务器架构
```
┌─────────────────┐ ┌──────────────┐ ┌─────────────┐
│ 客户端 │────│ HTTP 服务器 │────│ 数据库管理器 │
│ (远程向量数据库)│ │ (FastAPI) │ └─────────────┘
└─────────────────┘ └──────────────┘ │
│ ┌───────────────┐
┌──────────────┐ │ 多个数据库 │
│ 认证 │ │(本地向量数据库)│
│ 速率限制 │ └───────────────┘
│ CORS / SSE │
└──────────────┘
```
### 分段系统
- **位置跟踪**:精确的字符位置以实现完美的重建
- **多种方法**:句子、标记、段落、章节、代码块
- **重叠支持**:可配置的相邻分段之间的重叠
- **元数据保留**:所有分段继承文档元数据
## 📁 文件提取
文本提取由 [all2md](https://all2md.readthedocs.io/) 提供支持,[all2md](https://all2md.readthedocs.io/) 将 20+ 文档格式和 200+ 源/文本格式转换为 Markdown。常见格式开箱即用;扩展/小众格式和 OCR 是可选的额外功能。
| 格式 | 可用性 |
|---------|--------------|
| PDF, DOCX, PPTX, XLSX | 内置 |
| HTML, EPUB, RTF, ODT/ODP/ODS | 内置 |
| Markdown, reStructuredText, Org, CSV, JSON, YAML, `.eml`, `.ipynb` | 内置 |
| 源代码和纯文本(200+ 扩展名) | 内置 |
| LaTeX, MediaWiki, Textile, 归档文件, `.enex`, `.fb2`, CHM, Outlook | `localvectordb[file-extraction]` |
| 扫描的 PDF 的 OCR(Tesseract) | `localvectordb[file-extraction-ocr]` |
提取的内容是 **Markdown**,保留了标题、表格和列表,以获得更好的分段边界。
```python
# 通过 HTTP API 上传文件
files = {'files': open('document.pdf', 'rb')}
response = requests.post(
'http://localhost:5000/api/v1/mydb/upload',
files=files,
headers={'Authorization': 'Bearer your_api_key'}
)
```
## ⚙️ 配置选项
### 数据库设置
- `root_dir`: 数据库存储目录
- `chunk_size`: 最大分段大小
- `chunking_method`: 文本分割算法
- `chunk_overlap`: 相邻分段之间的重叠
- `default_metadata_schema`: 新数据库的模式
### 嵌入设置
- `provider`: "ollama" 或 "openai"
- `model`: 模型名称(例如 "nomic-embed-text")
- `base_url`: 自定义 API 端点
- `api_key`: 需要身份验证的提供商的 API 密钥
### 服务器设置
- `host` / `port`: 服务器绑定
- `require_api_key`: 启用身份验证
- `enable_rate_limiting`: 可配置限制的速率限制
- `cors_enabled`: Web 应用程序的 CORS 支持
- `cache_enabled`: 响应缓存(内存、文件、Redis)
## 🔧 生产环境部署
### Docker 部署
```dockerfile
FROM python:3.12-slim
RUN pip install localvectordb[server,file-extraction]
COPY config.toml /app/config.toml
WORKDIR /app
EXPOSE 5000
CMD ["lvdb", "serve", "--config", "config.toml"]
```
### 多工作进程设置
```bash
# 配置 Redis 注册表
lvdb config set server.db_registry_type "RedisCache"
lvdb config set server.db_registry_settings '{"host": "redis", "port": 6379, "db": 1}'
# 使用多个 uvicorn 工作进程启动
uvicorn "localvectordb_server.app:create_app" --factory --host 0.0.0.0 --port 5000 --workers 4
```
### 环境变量
```bash
export LVDB_SERVER_CONFIG="/path/to/config.toml"
export LVDB_DATABASE_ROOT_DIR="/data/databases"
export LVDB_EMBEDDING_PROVIDER="ollama"
export LVDB_EMBEDDING_MODEL="nomic-embed-text"
export OPENAI_API_KEY="your-openai-key" # 如果使用 OpenAI
```
## 🧪 示例
### 研究论文数据库
```python
from localvectordb import VectorDB
from localvectordb import get_common_metadata_schemas
# 使用预定义的学术论文模式
schema = get_common_metadata_schemas("research_papers")
db = VectorDB("papers", "./data", metadata_schema=schema)
# 添加论文
db.upsert(
documents=["论文内容..."],
metadata=[{
'title': 'Attention Is All You Need',
'authors': ['Vaswani', 'Shazeer', 'Parmar'],
'publication_date': '2017-06-12',
'journal': 'NIPS',
'keywords': ['attention', 'transformer', 'neural networks']
}]
)
# 按主题搜索并按日期过滤
results = db.query(
"transformer architecture",
filters={"publication_date": {">=": "2017-01-01"}},
search_type="hybrid"
)
```
### 代码仓库搜索
```python
# 为代码文件创建数据库
db = VectorDB("code", "./data",
chunking_method="code-blocks",
chunk_size=1000)
# 添加 Python 文件
import glob
for file_path in glob.glob("**/*.py", recursive=True):
with open(file_path, 'r') as f:
content = f.read()
db.upsert(
documents=[content],
metadata=[{
'file_path': file_path,
'language': 'python',
'last_modified': os.path.getmtime(file_path)
}]
)
# 搜索特定函数
results = db.query("async def", search_type="keyword")
```
## 🤝 贡献
贡献是受欢迎的!通过提交贡献,您同意根据项目的 [MIT License](LICENSE) 许可。
1. 复刻仓库
2. 创建一个功能分支 (`git checkout -b feature/amazing-feature`)
3. 提交您的更改 (`git commit -m 'Add amazing feature'`)
4. 推送到分支 (`git push origin feature/amazing-feature`)
5. 打开一个拉取请求
### 开发设置
```bash
git clone https://github.com/thomas-villani/localvectordb.git
cd localvectordb
# 安装开发工具 + 测试额外功能(添加 --extra mcp 以开发 MCP 服务器)
uv sync --dev
# 运行测试
uv run pytest
# 启动开发服务器
lvdb serve --debug
```
## 📄 许可证
该项目根据 [MIT License](LICENSE) 许可 - 请参阅 [LICENSE](LICENSE) 文件获取详细信息。
## 🆘 支持
- 🐛 **问题**: [GitHub Issues](https://github.com/thomas-villani/localvectordb/issues)
- 💬 **讨论**: [GitHub Discussions](https://github.com/thomas-villani/localvectordb/discussions)
- 📧 **联系**: thomas.villani@gmail.com
## 🙏 致谢
- [FAISS](https://github.com/facebookresearch/faiss) 用于向量相似性搜索
- [SQLite](https://sqlite.org/) 用于文档数据库
- [Ollama](https://ollama.ai/) 用于本地嵌入模型
- [FastAPI](https://fastapi.tiangolo.com/) 用于 HTTP 服务器
- [Click](https://click.palletsprojects.com/) 用于 Click CLI 库
- 所有使该项目成为可能的贡献者
MCP 配置
以下是此 MCP Server 的配置信息,可直接复制到 Cursor 或其他 MCP 客户端中使用。
mcp.json
连接信息
猜你喜欢
暂无推荐服务器