# Gomog 用户手册 **版本**: v1.0.0-alpha **最后更新**: 2026-03-14 **许可证**: MIT --- ## 📖 目录 1. [简介](#简介) 2. [快速开始](#快速开始) 3. [安装与配置](#安装与配置) 4. [基本使用](#基本使用) 5. [高级功能](#高级功能) 6. [最佳实践](#最佳实践) 7. [故障排查](#故障排查) 8. [常见问题](#常见问题) --- ## 简介 ### 什么是 Gomog? Gomog 是一个兼容 MongoDB 风格 API 的内存查询引擎,支持多数据库适配(SQLite、PostgreSQL、达梦 DM8)。它提供了丰富的聚合管道、查询操作符和更新操作符,让你能够以熟悉的方式操作关系型数据库。 ### 核心特性 - ✅ **MongoDB 风格 API**: 熟悉的查询语法,零学习成本 - ✅ **多数据库支持**: SQLite、PostgreSQL、达梦 DM8 - ✅ **完整的聚合管道**: 18+ 个聚合阶段,50+ 个聚合表达式 - ✅ **丰富的查询操作符**: 16+ 个查询操作符 - ✅ **强大的更新操作符**: 17+ 个更新操作符 - ✅ **HTTP 和 TCP 双协议**: RESTful API 和 MongoDB 线协议支持 - ✅ **高性能**: 内存优化,并发安全 ### 适用场景 - 快速原型开发 - 数据分析和报表 - 遗留系统现代化 - 多数据库统一访问层 - 教学和实验环境 --- ## 快速开始 ### 1. 下载与安装 ```bash # 从源码编译 git clone https://github.com/gomog/gomog.git cd gomog make build # 或使用 Docker docker pull gomog:latest ``` ### 2. 配置文件 复制示例配置文件: ```bash cp config.yaml.example config.yaml ``` 编辑 `config.yaml`: ```yaml server: http_addr: ":8080" tcp_addr: ":27017" mode: "dev" database: type: "sqlite" dsn: "gomog.db" max_open: 10 max_idle: 5 log: level: "info" format: "text" ``` ### 3. 启动服务 ```bash # 直接运行 ./bin/gomog -config config.yaml # 或使用 make make run # Docker 运行 docker run -p 8080:8080 -p 27017:27017 gomog:latest ``` ### 4. 验证安装 ```bash # HTTP 健康检查 curl http://localhost:8080/health # 插入测试数据 curl -X POST http://localhost:8080/api/v1/testdb/users/insert \ -H "Content-Type: application/json" \ -d '{"documents": [{"name": "Alice", "age": 30}]}' # 查询数据 curl -X POST http://localhost:8080/api/v1/testdb/users/find \ -H "Content-Type: application/json" \ -d '{"filter": {"age": {"$gt": 25}}}' ``` --- ## 安装与配置 ### 系统要求 - **操作系统**: Linux, macOS, Windows - **Go 版本**: 1.21+ - **内存**: 最少 512MB,推荐 1GB+ - **磁盘**: 最少 100MB 可用空间 ### 安装方式 #### 方式一:源码编译(推荐) ```bash # 克隆仓库 git clone https://github.com/gomog/gomog.git cd gomog # 编译 make build # 验证 ./bin/gomog --version ``` #### 方式二:Docker ```bash # 拉取镜像 docker pull gomog:latest # 运行 docker run -d \ --name gomog \ -p 8080:8080 \ -p 27017:27017 \ -v $(pwd)/data:/data \ gomog:latest ``` #### 方式三:包管理器(待提供) ```bash # Ubuntu/Debian sudo apt install gomog # CentOS/RHEL sudo yum install gomog # macOS (Homebrew) brew install gomog ``` ### 配置详解 #### 服务器配置 ```yaml server: # HTTP 监听地址 # 格式:[host]:port # 默认:":8080" http_addr: ":8080" # TCP 监听地址(MongoDB 线协议) # 格式:[host]:port # 默认:":27017" tcp_addr: ":27017" # 运行模式 # 可选值:dev, prod # dev: 详细日志,调试信息 # prod: 精简日志,性能优化 mode: "dev" ``` #### 数据库配置 ```yaml database: # 数据库类型 # 可选值:sqlite, postgres, dm8 type: "sqlite" # 数据源名称 # SQLite: 文件路径或 :memory: # PostgreSQL: postgresql://user:pass@host:port/dbname?sslmode=disable # DM8: dm://user:pass@host:port/dbname dsn: "gomog.db" # 最大打开连接数 # 默认:10 max_open: 10 # 最大空闲连接数 # 默认:5 max_idle: 5 # 连接最大生命周期(可选) # 格式:时间 Duration 字符串 # 默认:"4h" max_lifetime: "4h" ``` #### 日志配置 ```yaml log: # 日志级别 # 可选值:debug, info, warn, error # debug: 所有日志 # info: 常规信息 # warn: 警告信息 # error: 错误信息 level: "info" # 日志格式 # 可选值:text, json # text: 人类可读格式 # json: 结构化 JSON 格式 format: "text" # 日志输出文件(可选) # 默认:stdout output: "/var/log/gomog/gomog.log" ``` ### 环境变量 Gomog 支持通过环境变量覆盖配置文件: | 环境变量 | 配置项 | 示例 | |---------|--------|------| | `GOMOG_HTTP_ADDR` | server.http_addr | `GOMOG_HTTP_ADDR=:9000` | | `GOMOG_TCP_ADDR` | server.tcp_addr | `GOMOG_TCP_ADDR=:27018` | | `GOMOG_DB_TYPE` | database.type | `GOMOG_DB_TYPE=postgres` | | `GOMOG_DB_DSN` | database.dsn | `GOMOG_DB_DSN=mydb.db` | | `GOMOG_LOG_LEVEL` | log.level | `GOMOG_LOG_LEVEL=debug` | --- ## 基本使用 ### 数据库和集合管理 #### 创建数据库 Gomog 会自动创建不存在的数据库,无需手动创建。 #### 创建集合 同样,集合会在首次插入数据时自动创建。 #### 列出所有数据库 ```bash curl -X POST http://localhost:8080/api/v1/admin/listDatabases ``` #### 列出所有集合 ```bash curl -X POST http://localhost:8080/api/v1/{database}/listCollections ``` ### CRUD 操作 #### 插入(Insert) ```bash # 单条插入 curl -X POST http://localhost:8080/api/v1/testdb/users/insert \ -H "Content-Type: application/json" \ -d '{"documents": [{"name": "Alice", "age": 30}]}' # 批量插入 curl -X POST http://localhost:8080/api/v1/testdb/users/insert \ -H "Content-Type: application/json" \ -d '{ "documents": [ {"name": "Bob", "age": 25}, {"name": "Charlie", "age": 35} ] }' ``` #### 查询(Find) ```bash # 查询所有 curl -X POST http://localhost:8080/api/v1/testdb/users/find \ -H "Content-Type: application/json" \ -d '{}' # 条件查询 curl -X POST http://localhost:8080/api/v1/testdb/users/find \ -H "Content-Type: application/json" \ -d '{"filter": {"age": {"$gt": 28}}}' # 投影(选择字段) curl -X POST http://localhost:8080/api/v1/testdb/users/find \ -H "Content-Type: application/json" \ -d '{ "filter": {"age": {"$gt": 28}}, "projection": {"name": 1, "age": 1} }' ``` #### 更新(Update) ```bash # 更新单个文档 curl -X POST http://localhost:8080/api/v1/testdb/users/update \ -H "Content-Type: application/json" \ -d '{ "filter": {"name": "Alice"}, "update": {"$set": {"age": 31}} }' # 更新多个文档 curl -X POST http://localhost:8080/api/v1/testdb/users/update \ -H "Content-Type: application/json" \ -d '{ "filter": {}, "update": {"$inc": {"age": 1}}, "multi": true }' # Upsert(不存在则插入) curl -X POST http://localhost:8080/api/v1/testdb/users/update \ -H "Content-Type: application/json" \ -d '{ "filter": {"name": "David"}, "update": {"$setOnInsert": {"name": "David", "age": 28}}, "upsert": true }' ``` #### 删除(Delete) ```bash # 删除单个文档 curl -X POST http://localhost:8080/api/v1/testdb/users/delete \ -H "Content-Type: application/json" \ -d '{"filter": {"name": "Alice"}}' # 删除多个文档 curl -X POST http://localhost:8080/api/v1/testdb/users/delete \ -H "Content-Type: application/json" \ -d '{"filter": {"age": {"$lt": 30}}, "multi": true}' ``` ### 聚合操作 ```bash # 简单聚合 curl -X POST http://localhost:8080/api/v1/testdb/users/aggregate \ -H "Content-Type: application/json" \ -d '{ "pipeline": [ {"$match": {"age": {"$gte": 30}}}, {"$group": { "_id": "$department", "count": {"$sum": 1}, "avgAge": {"$avg": "$age"} }} ] }' ``` --- ## 高级功能 ### 聚合管道 Gomog 支持完整的 MongoDB 聚合管道,包括: #### 1. 数据过滤 ```json { "pipeline": [ {"$match": {"status": "active"}}, {"$limit": 10}, {"$skip": 5} ] } ``` #### 2. 数据转换 ```json { "pipeline": [ {"$addFields": {"fullName": {"$concat": ["$firstName", " ", "$lastName"]}}}, {"$project": {"_id": 0, "fullName": 1, "email": 1}} ] } ``` #### 3. 数据分组 ```json { "pipeline": [ {"$group": { "_id": "$category", "total": {"$sum": "$amount"}, "average": {"$avg": "$price"} }} ] } ``` #### 4. 数据排序 ```json { "pipeline": [ {"$sort": {"created_at": -1}}, {"$limit": 10} ] } ``` #### 5. 关联查询(Lookup) ```json { "pipeline": [ {"$lookup": { "from": "orders", "localField": "_id", "foreignField": "userId", "as": "orders" }} ] } ``` ### 文本搜索 ```bash curl -X POST http://localhost:8080/api/v1/testdb/articles/aggregate \ -H "Content-Type: application/json" \ -d '{ "pipeline": [ {"$match": {"$text": {"$search": "database performance"}}}, {"$sort": {"score": {"$meta": "textScore"}}} ] }' ``` ### 窗口函数 ```bash curl -X POST http://localhost:8080/api/v1/testdb/sales/aggregate \ -H "Content-Type: application/json" \ -d '{ "pipeline": [{ "$setWindowFields": { "partitionBy": "$region", "sortBy": {"date": 1}, "output": { "runningTotal": { "$sum": "$amount", "window": {"documents": ["unbounded", "current"]} }, "rank": {"$documentNumber": {}} } } }] }' ``` ### 递归查找 ```bash curl -X POST http://localhost:8080/api/v1/testdb/orgs/aggregate \ -H "Content-Type: application/json" \ -d '{ "pipeline": [{ "$graphLookup": { "from": "orgs", "startWith": "$parentId", "connectFromField": "_id", "connectToField": "parentId", "as": "subOrgs", "maxDepth": 5 } }] }' ``` --- ## 最佳实践 ### 性能优化 #### 1. 合理使用索引 ```bash # 为常用查询字段创建索引 curl -X POST http://localhost:8080/api/v1/testdb/users/createIndex \ -H "Content-Type: application/json" \ -d '{"keys": {"email": 1}, "unique": true}' ``` #### 2. 避免全表扫描 ```bash # ❌ 不推荐:全表扫描 {"filter": {"$expr": {"$gt": ["$age", 25]}}} # ✅ 推荐:使用索引 {"filter": {"age": {"$gt": 25}}} ``` #### 3. 限制返回结果 ```bash # 总是使用 limit 限制返回数量 {"limit": 100} ``` #### 4. 使用投影减少数据传输 ```bash # 只返回需要的字段 {"projection": {"name": 1, "email": 1}} ``` ### 数据安全 #### 1. 输入验证 始终在应用层验证用户输入,不要完全依赖数据库验证。 #### 2. 参数化查询 使用 Gomog 的参数化机制,避免注入攻击。 #### 3. 权限控制 在生产环境中使用数据库的权限控制机制。 ### 监控与日志 #### 1. 启用慢查询日志 ```yaml log: level: "debug" slow_query_threshold: "100ms" ``` #### 2. 监控关键指标 - QPS(每秒查询数) - 平均响应时间 - 错误率 - 连接池使用率 --- ## 故障排查 ### 常见问题 #### 1. 无法启动服务 **症状**: 启动时报错 "address already in use" **解决**: ```bash # 检查端口占用 lsof -i :8080 lsof -i :27017 # 修改配置文件使用其他端口 server: http_addr: ":8081" tcp_addr: ":27018" ``` #### 2. 数据库连接失败 **症状**: "failed to connect to database" **解决**: ```bash # 检查数据库配置 cat config.yaml | grep -A 5 database # 验证数据库服务是否运行 # PostgreSQL pg_isready -h localhost -p 5432 # SQLite ls -la gomog.db ``` #### 3. 查询性能慢 **症状**: 查询响应时间超过预期 **解决**: ```bash # 1. 查看执行计划 curl -X POST http://localhost:8080/api/v1/testdb/users/explain \ -H "Content-Type: application/json" \ -d '{"filter": {"age": {"$gt": 25}}}' # 2. 添加索引 curl -X POST http://localhost:8080/api/v1/testdb/users/createIndex \ -H "Content-Type: application/json" \ -d '{"keys": {"age": 1}}' # 3. 优化查询 # 避免使用 $expr,改用原生操作符 ``` #### 4. 内存不足 **症状**: OOM killer 杀死进程 **解决**: ```yaml # 限制连接池大小 database: max_open: 5 max_idle: 2 ``` ### 日志分析 #### 查看日志 ```bash # 实时查看日志 tail -f /var/log/gomog/gomog.log # 搜索错误 grep "ERROR" /var/log/gomog/gomog.log ``` #### 日志级别说明 - **DEBUG**: 详细调试信息,包含所有查询和响应 - **INFO**: 常规运行信息 - **WARN**: 警告信息,不影响正常运行 - **ERROR**: 错误信息,需要关注 --- ## 常见问题 ### Q: Gomog 与 MongoDB 有什么区别? A: Gomog 是一个兼容 MongoDB 风格 API 的查询引擎,底层可以使用 SQLite、PostgreSQL 等关系型数据库。它不是 MongoDB 的直接替代品,而是提供了一种熟悉的方式来操作关系型数据库。 ### Q: 支持哪些 MongoDB 操作符? A: Gomog 支持 16+ 个查询操作符、17+ 个更新操作符、18+ 个聚合阶段和 50+ 个聚合表达式。详见 [API 参考文档](API_REFERENCE.md)。 ### Q: 如何在生产环境使用? A: 1. 设置 `mode: "prod"` 2. 配置合适的连接池大小 3. 启用日志持久化 4. 配置监控告警 5. 定期备份数据 ### Q: 是否支持事务? A: 取决于底层数据库。PostgreSQL 和达梦 DM8 支持事务,SQLite 支持有限的事务。 ### Q: 如何备份数据? A: - **SQLite**: 直接复制 `.db` 文件 - **PostgreSQL**: 使用 `pg_dump` - **DM8**: 使用 DM 的备份工具 ### Q: 性能如何? A: 对于中小规模数据集(<100 万条记录),Gomog 能提供亚秒级的查询响应。对于大规模数据,建议使用原生数据库客户端以获得最佳性能。 --- ## 获取帮助 - **文档**: `/manual` 目录 - **示例**: [API_EXAMPLES.md](../doc/API_EXAMPLES.md) - **问题反馈**: GitHub Issues - **社区讨论**: GitHub Discussions --- **维护者**: Gomog Team **许可证**: MIT