geo/.qoder/repowiki/zh/content/数据库设计/数据库设计.md

1622 lines
69 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 数据库设计
<cite>
**本文档引用的文件**
- [backend/app/database.py](file://backend/app/database.py)
- [backend/app/models/user.py](file://backend/app/models/user.py)
- [backend/app/models/query.py](file://backend/app/models/query.py)
- [backend/app/models/citation_record.py](file://backend/app/models/citation_record.py)
- [backend/app/models/query_task.py](file://backend/app/models/query_task.py)
- [backend/app/models/subscription.py](file://backend/app/models/subscription.py)
- [backend/app/models/lifecycle.py](file://backend/app/models/lifecycle.py)
- [backend/app/models/analytics.py](file://backend/app/models/analytics.py)
- [backend/app/models/alert.py](file://backend/app/models/alert.py)
- [backend/app/models/knowledge.py](file://backend/app/models/knowledge.py)
- [backend/app/models/__init__.py](file://backend/app/models/__init__.py)
- [backend/alembic/env.py](file://backend/alembic/env.py)
- [backend/alembic/versions/488d0bd5ab01_initial_migration.py](file://backend/alembic/versions/488d0bd5ab01_initial_migration.py)
- [backend/alembic/versions/b2c4d6e8fa10_add_confidence_match_type_to_citation_records.py](file://backend/alembic/versions/b2c4d6e8fa10_add_confidence_match_type_to_citation_records.py)
- [backend/alembic/versions/c3d5e7f9ab12_add_user_management_fields.py](file://backend/alembic/versions/c3d5e7f9ab12_add_user_management_fields.py)
- [backend/alembic/versions/d4f6g8h0ab23_add_geo_lifecycle_tables.py](file://backend/alembic/versions/d4f6g8h0ab23_add_geo_lifecycle_tables.py)
- [backend/alembic/versions/e5f7a9b1cd34_add_alerts_and_alert_settings_tables.py](file://backend/alembic/versions/e5f7a9b1cd34_add_alerts_and_alert_settings_tables.py)
- [backend/alembic/versions/e5f7g9h1cd45_add_knowledge_base_tables.py](file://backend/alembic/versions/e5f7g9h1cd45_add_knowledge_base_tables.py)
- [backend/alembic/versions/f6g8h0i2de56_add_analytics_tables.py](file://backend/alembic/versions/f6g8h0i2de56_add_analytics_tables.py)
- [backend/alembic.ini](file://backend/alembic.ini)
- [backend/app/config.py](file://backend/app/config.py)
- [docker-compose.yml](file://docker-compose.yml)
- [backend/app/services/query.py](file://backend/app/services/query.py)
- [backend/app/services/citation.py](file://backend/app/services/citation.py)
- [backend/app/services/auth.py](file://backend/app/services/auth.py)
- [backend/app/schemas/auth.py](file://backend/app/schemas/auth.py)
- [backend/app/api/auth.py](file://backend/app/api/auth.py)
- [backend/app/api/citations.py](file://backend/app/api/citations.py)
- [backend/app/api/reports.py](file://backend/app/api/reports.py)
- [backend/app/api/lifecycle.py](file://backend/app/api/lifecycle.py)
- [backend/app/api/analytics.py](file://backend/app/api/analytics.py)
- [backend/app/api/alerts.py](file://backend/app/api/alerts.py)
- [backend/app/api/knowledge.py](file://backend/app/api/knowledge.py)
</cite>
## 更新摘要
**变更内容**
- 新增业务生命周期管理系统:组织、项目、阶段、代理、内容、规则、知识库等表
- 新增分析监控系统:发布记录、内容指标、优化洞察等表
- 新增告警系统:告警记录和告警设置表
- 新增知识库系统:支持向量检索的完整知识管理架构
- 更新数据库迁移版本链包含11个版本的完整架构演进
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构总览](#架构总览)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排查指南](#故障排查指南)
9. [结论](#结论)
10. [附录](#附录)
## 简介
本文件为 GEO 智能检索与引用监测平台的数据库设计文档,聚焦于基于 PostgreSQL 的关系型数据库架构,涵盖:
- 表结构设计与实体关系映射ER
- 索引策略与查询优化
- SQLAlchemy ORM 模型实现(模型定义、关系配置、查询封装)
- 数据库迁移管理、版本控制与部署策略
- 数据完整性约束、事务处理与并发控制
- 性能优化、查询分析与缓存策略
- 备份、恢复与维护最佳实践
**更新** 新增完整的业务生命周期、分析监控、告警系统、知识库等企业级功能架构,形成从用户管理到智能代理的完整数据体系。
## 项目结构
后端采用 FastAPI + SQLAlchemy Async + Alembic 迁移的典型分层架构:
- 配置层:读取环境变量,提供数据库连接字符串
- 数据库引擎与会话:异步连接池与会话工厂
- ORM 模型层:用户、查询、引用记录、任务、订阅、生命周期、分析监控、告警、知识库
- 迁移层Alembic 初始化迁移脚本
- 服务层:业务查询封装,统一事务边界
- 容器编排Docker Compose 启动 Postgres 与 Redis
```mermaid
graph TB
subgraph "应用层"
AuthAPI["API: 认证<br/>backend/app/api/auth.py"]
LifeCycleAPI["API: 生命周期<br/>backend/app/api/lifecycle.py"]
AnalyticsAPI["API: 分析监控<br/>backend/app/api/analytics.py"]
AlertsAPI["API: 告警系统<br/>backend/app/api/alerts.py"]
KnowledgeAPI["API: 知识库<br/>backend/app/api/knowledge.py"]
CitationsAPI["API: 引用<br/>backend/app/api/citations.py"]
ReportsAPI["API: 报告<br/>backend/app/api/reports.py"]
end
subgraph "服务层"
SvcAuth["服务: 认证<br/>backend/app/services/auth.py"]
SvcLifeCycle["服务: 生命周期<br/>backend/app/services/lifecycle.py"]
SvcAnalytics["服务: 分析监控<br/>backend/app/services/analytics.py"]
SvcAlerts["服务: 告警系统<br/>backend/app/services/alert_engine.py"]
SvcKnowledge["服务: 知识库<br/>backend/app/services/knowledge/"]
SvcCitations["服务: 引用<br/>backend/app/services/citation.py"]
SvcReports["服务: 报告<br/>backend/app/services/reports.py"]
end
subgraph "ORM 层"
MUser["模型: 用户<br/>backend/app/models/user.py"]
MLifeCycle["模型: 生命周期<br/>backend/app/models/lifecycle.py"]
MAnalytics["模型: 分析监控<br/>backend/app/models/analytics.py"]
MAlerts["模型: 告警系统<br/>backend/app/models/alert.py"]
MKnowledge["模型: 知识库<br/>backend/app/models/knowledge.py"]
MQuery["模型: 查询<br/>backend/app/models/query.py"]
MCitation["模型: 引用记录<br/>backend/app/models/citation_record.py"]
MTask["模型: 查询任务<br/>backend/app/models/query_task.py"]
MSubscription["模型: 订阅<br/>backend/app/models/subscription.py"]
end
subgraph "基础设施"
DB["PostgreSQL 数据库"]
RD["Redis 缓存"]
Vector["向量数据库"]
end
Cfg["配置: DATABASE_URL<br/>backend/app/config.py"]
Eng["引擎与会话<br/>backend/app/database.py"]
Alembic["迁移: Alembic<br/>backend/alembic/*"]
Cfg --> Eng
Eng --> DB
AuthAPI --> SvcAuth
LifeCycleAPI --> SvcLifeCycle
AnalyticsAPI --> SvcAnalytics
AlertsAPI --> SvcAlerts
KnowledgeAPI --> SvcKnowledge
CitationsAPI --> SvcCitations
ReportsAPI --> SvcReports
SvcAuth --> Eng
SvcLifeCycle --> Eng
SvcAnalytics --> Eng
SvcAlerts --> Eng
SvcKnowledge --> Eng
SvcCitations --> Eng
SvcReports --> Eng
MUser --> Eng
MLifeCycle --> Eng
MAnalytics --> Eng
MAlerts --> Eng
MKnowledge --> Eng
MQuery --> Eng
MCitation --> Eng
MTask --> Eng
MSubscription --> Eng
Alembic --> DB
SvcAuth --> RD
SvcCitations --> RD
SvcKnowledge --> Vector
```
**图表来源**
- [backend/app/config.py:1-23](file://backend/app/config.py#L1-L23)
- [backend/app/database.py:1-29](file://backend/app/database.py#L1-L29)
- [backend/app/models/user.py:1-48](file://backend/app/models/user.py#L1-L48)
- [backend/app/models/lifecycle.py:1-92](file://backend/app/models/lifecycle.py#L1-L92)
- [backend/app/models/analytics.py:1-64](file://backend/app/models/analytics.py#L1-L64)
- [backend/app/models/alert.py:1-75](file://backend/app/models/alert.py#L1-L75)
- [backend/app/models/knowledge.py:1-213](file://backend/app/models/knowledge.py#L1-L213)
- [backend/alembic/env.py:1-89](file://backend/alembic/env.py#L1-L89)
- [docker-compose.yml:1-71](file://docker-compose.yml#L1-L71)
**章节来源**
- [backend/app/config.py:1-23](file://backend/app/config.py#L1-L23)
- [backend/app/database.py:1-29](file://backend/app/database.py#L1-L29)
- [backend/alembic/env.py:1-89](file://backend/alembic/env.py#L1-L89)
- [docker-compose.yml:1-71](file://docker-compose.yml#L1-L71)
## 核心组件
- 数据库引擎与会话
- 使用异步引擎与会话工厂,开启自动提交、自动刷新、自动回滚等参数,确保事务一致性与资源释放。
- 提供依赖注入式 get_db 生成器,保证每个请求生命周期内复用同一会话。
- ORM 模型
- 所有模型继承自统一的 Base表名与字段类型均在模型中显式声明。
- 关系通过 relationship 显式配置,支持级联删除与孤儿对象清理。
- 迁移与版本控制
- Alembic 环境集成 SQLAlchemy Base 元数据,支持离线/在线迁移。
- 初始迁移脚本定义了用户、查询、引用记录、查询任务、订阅五张表及必要索引。
- 新增迁移版本支持confidence和match_type字段增强报告功能。
- **新增** 生命周期迁移(d4f6g8h0ab23):新增组织、项目、阶段、代理、内容、规则、知识库等完整业务架构。
- **新增** 分析监控迁移(f6g8h0i2de56):新增发布记录、内容指标、优化洞察等分析监控表。
- **新增** 告警系统迁移(e5f7a9b1cd34):新增告警记录和告警设置表。
- **新增** 知识库迁移(e5f7g9h1cd45):新增支持向量检索的知识库完整架构。
- **新增** 最新迁移版本添加用户管理相关字段,支持完整的用户认证和管理功能。
- 服务层封装
- 查询与引用统计、导出等业务逻辑封装在服务层,统一执行 SQL 并返回结果。
- 对外暴露清晰的查询接口,内部进行权限校验与计数限制。
- **新增** 认证服务封装用户注册、登录、验证等功能。
- **新增** 生命周期服务管理项目全生命周期。
- **新增** 分析监控服务处理内容发布和指标收集。
- **新增** 告警引擎服务处理实时告警。
- **新增** 知识库服务处理向量检索和RAG。
**章节来源**
- [backend/app/database.py:1-29](file://backend/app/database.py#L1-L29)
- [backend/app/models/__init__.py:1-14](file://backend/app/models/__init__.py#L1-L14)
- [backend/alembic/versions/488d0bd5ab01_initial_migration.py:1-128](file://backend/alembic/versions/488d0bd5ab01_initial_migration.py#L1-L128)
- [backend/alembic/versions/b2c4d6e8fa10_add_confidence_match_type_to_citation_records.py:1-37](file://backend/alembic/versions/b2c4d6e8fa10_add_confidence_match_type_to_citation_records.py#L1-L37)
- [backend/alembic/versions/c3d5e7f9ab12_add_user_management_fields.py:1-41](file://backend/alembic/versions/c3d5e7f9ab12_add_user_management_fields.py#L1-L41)
- [backend/alembic/versions/d4f6g8h0ab23_add_geo_lifecycle_tables.py:1-398](file://backend/alembic/versions/d4f6g8h0ab23_add_geo_lifecycle_tables.py#L1-L398)
- [backend/alembic/versions/f6g8h0i2de56_add_analytics_tables.py:1-125](file://backend/alembic/versions/f6g8h0i2de56_add_analytics_tables.py#L1-L125)
- [backend/alembic/versions/e5f7a9b1cd34_add_alerts_and_alert_settings_tables.py:1-86](file://backend/alembic/versions/e5f7a9b1cd34_add_alerts_and_alert_settings_tables.py#L1-L86)
- [backend/alembic/versions/e5f7g9h1cd45_add_knowledge_base_tables.py:1-224](file://backend/alembic/versions/e5f7g9h1cd45_add_knowledge_base_tables.py#L1-L224)
- [backend/app/services/query.py:1-130](file://backend/app/services/query.py#L1-L130)
- [backend/app/services/citation.py:1-429](file://backend/app/services/citation.py#L1-L429)
- [backend/app/services/auth.py:1-175](file://backend/app/services/auth.py#L1-L175)
## 架构总览
下图展示数据库层与应用层的交互关系,以及迁移与容器编排对数据库的影响。
```mermaid
sequenceDiagram
participant Client as "客户端"
participant AuthAPI as "认证API"
participant LifeCycleAPI as "生命周期API"
participant AnalyticsAPI as "分析监控API"
participant AlertsAPI as "告警API"
participant KnowledgeAPI as "知识库API"
participant SvcAuth as "认证服务"
participant SvcLifeCycle as "生命周期服务"
participant SvcAnalytics as "分析监控服务"
participant SvcAlerts as "告警引擎服务"
participant SvcKnowledge as "知识库服务"
participant DB as "PostgreSQL"
participant Alembic as "迁移工具"
Client->>AuthAPI : 请求 /auth/register 登录
AuthAPI->>SvcAuth : 调用认证服务
SvcAuth->>DB : 执行用户注册/验证
Client->>LifeCycleAPI : 请求生命周期管理
LifeCycleAPI->>SvcLifeCycle : 调用生命周期服务
SvcLifeCycle->>DB : 执行项目/阶段管理
Client->>AnalyticsAPI : 请求分析监控
AnalyticsAPI->>SvcAnalytics : 调用分析监控服务
SvcAnalytics->>DB : 执行发布记录/指标收集
Client->>AlertsAPI : 请求告警管理
AlertsAPI->>SvcAlerts : 调用告警引擎服务
SvcAlerts->>DB : 执行告警记录/设置
Client->>KnowledgeAPI : 请求知识检索
KnowledgeAPI->>SvcKnowledge : 调用知识库服务
SvcKnowledge->>DB : 执行向量检索
SvcKnowledge->>Vector : 执行相似度搜索
DB-->>SvcKnowledge : 返回检索结果
DB-->>SvcAlerts : 返回告警数据
DB-->>SvcAnalytics : 返回监控数据
DB-->>SvcLifeCycle : 返回生命周期数据
DB-->>SvcAuth : 返回用户信息
SvcKnowledge-->>KnowledgeAPI : 返回检索结果
SvcAlerts-->>AlertsAPI : 返回告警数据
SvcAnalytics-->>AnalyticsAPI : 返回监控数据
SvcLifeCycle-->>LifeCycleAPI : 返回生命周期数据
SvcAuth-->>AuthAPI : 返回认证结果
AuthAPI-->>Client : 响应认证数据
Note over Alembic,DB : 首次启动或升级时执行迁移
```
**图表来源**
- [backend/app/services/citation.py:1-429](file://backend/app/services/citation.py#L1-L429)
- [backend/app/services/auth.py:1-175](file://backend/app/services/auth.py#L1-L175)
- [backend/alembic/env.py:1-89](file://backend/alembic/env.py#L1-L89)
## 详细组件分析
### 实体关系映射ER
- 用户users主键 id唯一邮箱计划与配额字段活跃状态**新增**组织关联、角色字段邮箱验证状态、验证码及其过期时间、重置令牌及其过期时间、头像URL、管理员权限时间戳。
- 组织organizations主键 id名称、slug唯一约束、描述、logo、计划、最大成员数时间戳。
- 生命周期项目lifecycle_projects主键 id组织外键品牌名称、别名列表、当前阶段、状态、创建者外键时间戳。
- 项目阶段project_stages主键 id项目外键阶段编号、状态、开始/完成时间、备注、指标,唯一索引(project_id, stage_number)。
- 代理注册表agent_registry主键 id名称唯一约束、显示名称、代理类型、描述、版本、端点、状态、能力、心跳时间索引(name, agent_type, status)。
- 代理配置agent_configs主键 id代理外键配置键唯一约束配置值、描述、更新时间、更新者外键。
- 代理任务agent_tasks主键 id代理外键任务类型、状态、优先级、输入输出数据、错误信息、创建者、组织、项目外键索引(agent_id, status, organization_id, project_id, created_by, task_type)。
- 代理任务日志agent_task_logs主键 id任务外键代理外键日志级别、消息、元数据索引(task_id, agent_id, created_at)。
- 内容contents主键 id组织外键项目外键标题、类型、正文、状态、目标平台、关键词、元数据、创建者外键索引(organization_id, project_id, status, content_type, created_by)。
- 内容版本content_versions主键 id内容外键版本号、标题、正文、变更摘要、创建者外键唯一索引(content_id, version_number)。
- 内容审核content_reviews主键 id内容外键审核者外键状态、评论索引(content_id, reviewer_id)。
- 平台规则platform_rules主键 id平台、规则类别、规则名称、描述、检查标准、严重程度、激活状态索引(platform, rule_category, is_active)。
- 品牌知识brand_knowledge主键 id组织外键类别、标题、内容、元数据、激活状态、创建者外键索引(organization_id, category, is_active)。
- 关键词keywords主键 id组织外键项目外键关键词、类别、优先级、搜索量、竞争等级、状态索引(organization_id, project_id, category, status, keyword)。
- 发布记录publish_records主键 id组织外键内容标题、内容ID、平台、发布URL、状态、发布时间索引(organization_id, platform, status, created_at)。
- 内容指标content_metrics主键 id发布记录外键记录时间互动指标、AI引用次数、搜索曝光点击、阅读指标索引(publish_record_id, recorded_at)。
- 优化洞察optimization_insights主键 id组织外键内容ID、洞察类型、标题、描述、建议、严重程度、是否已应用索引(organization_id, insight_type, created_at)。
- 告警alerts主键 id品牌外键用户外键告警类型、严重程度、标题、消息、数据、是否已读索引(user_id, brand_id, alert_type, is_read, created_at)。
- 告警设置alert_settings主键 id品牌外键用户外键告警类型、是否启用、阈值索引(brand_id, user_id, brand_id, alert_type)。
- 知识库knowledge_bases主键 id组织外键名称、类型、描述、文档数量、状态、创建者外键索引(organization_id, type, status)。
- 知识文档knowledge_documents主键 id知识库外键标题、来源类型、URL、内容、内容哈希、分块数量、状态、错误信息、元数据索引(knowledge_base_id, status, content_hash)。
- 知识分块knowledge_chunks主键 id文档外键内容、嵌入向量、分块索引、token数量、元数据索引(document_id, document_id, chunk_index)。
- 知识检索日志knowledge_search_logs主键 id组织外键用户外键查询、知识库ID列表、结果数量、延迟毫秒索引(organization_id, user_id, created_at)。
**更新** 新增完整的业务生命周期、分析监控、告警系统、知识库等企业级功能架构,形成从用户管理到智能代理的完整数据体系。
```mermaid
erDiagram
USERS {
uuid id PK
string email UK
string password_hash
string name
string plan
integer max_queries
boolean is_active
uuid organization_id FK
string role
boolean email_verified
string verification_code
timestamptz verification_code_expires
string reset_token
timestamptz reset_token_expires
string avatar_url
boolean is_admin
timestamptz created_at
timestamptz updated_at
}
ORGANIZATIONS {
uuid id PK
string name
string slug UK
text description
string logo_url
string plan
integer max_members
timestamptz created_at
timestamptz updated_at
}
LIFECYCLE_PROJECTS {
uuid id PK
uuid organization_id FK
string brand_name
jsonb brand_aliases
integer current_stage
string status
uuid created_by FK
timestamptz created_at
timestamptz updated_at
}
PROJECT_STAGES {
uuid id PK
uuid project_id FK
integer stage_number
string status
timestamptz started_at
timestamptz completed_at
text notes
jsonb metrics
}
AGENT_REGISTRY {
uuid id PK
string name UK
string display_name
string agent_type
text description
string version
string endpoint
string status
jsonb capabilities
timestamptz last_heartbeat
timestamptz created_at
timestamptz updated_at
}
AGENT_CONFIGS {
uuid id PK
uuid agent_id FK
string config_key
jsonb config_value
string description
timestamptz updated_at
uuid updated_by FK
}
AGENT_TASKS {
uuid id PK
uuid agent_id FK
string task_type
string status
integer priority
jsonb input_data
jsonb output_data
text error_message
uuid created_by FK
uuid organization_id FK
uuid project_id FK
timestamptz scheduled_at
timestamptz started_at
timestamptz completed_at
timestamptz created_at
}
AGENT_TASK_LOGS {
uuid id PK
uuid task_id FK
uuid agent_id FK
string log_level
text message
jsonb metadata
timestamptz created_at
}
CONTENTS {
uuid id PK
uuid organization_id FK
uuid project_id FK
string title
string content_type
text body
string status
jsonb target_platforms
jsonb keywords
jsonb metadata
uuid created_by FK
integer current_version
timestamptz created_at
timestamptz updated_at
}
CONTENT_VERSIONS {
uuid id PK
uuid content_id FK
integer version_number
string title
text body
string change_summary
uuid created_by FK
timestamptz created_at
}
CONTENT_REVIEWS {
uuid id PK
uuid content_id FK
uuid reviewer_id FK
string status
text comments
timestamptz created_at
}
PLATFORM_RULES {
uuid id PK
string platform
string rule_category
string rule_name
text description
jsonb check_criteria
string severity
boolean is_active
timestamptz updated_at
}
BRAND_KNOWLEDGE {
uuid id PK
uuid organization_id FK
string category
string title
text content
jsonb metadata
boolean is_active
uuid created_by FK
timestamptz created_at
timestamptz updated_at
}
KEYWORDS {
uuid id PK
uuid organization_id FK
uuid project_id FK
string keyword
string category
integer priority
integer search_volume
string competition_level
string status
timestamptz created_at
}
PUBLISH_RECORDS {
string id PK
string organization_id FK
string content_title
string content_id
string platform
string published_url
string status
timestamptz published_at
timestamptz created_at
}
CONTENT_METRICS {
string id PK
string publish_record_id FK
timestamptz recorded_at
integer views
integer likes
integer comments
integer shares
integer bookmarks
integer ai_citation_count
integer search_impressions
integer search_clicks
float avg_read_duration
float read_completion_rate
}
OPTIMIZATION_INSIGHTS {
string id PK
string organization_id FK
string content_id
string insight_type
string title
text description
text recommendation
string severity
boolean applied
timestamptz created_at
}
ALERTS {
uuid id PK
uuid brand_id FK
uuid user_id FK
string alert_type
string severity
string title
text message
jsonb data
boolean is_read
timestamptz created_at
}
ALERT_SETTINGS {
uuid id PK
uuid brand_id FK
uuid user_id FK
string alert_type
boolean enabled
float threshold
timestamptz created_at
timestamptz updated_at
}
KNOWLEDGE_BASES {
uuid id PK
uuid organization_id FK
string name
string type
text description
integer document_count
string status
uuid created_by FK
timestamptz created_at
timestamptz updated_at
}
KNOWLEDGE_DOCUMENTS {
uuid id PK
uuid knowledge_base_id FK
string title
string source_type
string source_url
text content
string content_hash
integer chunk_count
string status
text error_message
jsonb metadata
timestamptz created_at
timestamptz updated_at
}
KNOWLEDGE_CHUNKS {
uuid id PK
uuid document_id FK
text content
vector embedding
integer chunk_index
integer token_count
jsonb metadata
timestamptz created_at
}
KNOWLEDGE_SEARCH_LOGS {
uuid id PK
uuid organization_id FK
uuid user_id FK
text query
jsonb knowledge_base_ids
integer results_count
integer latency_ms
timestamptz created_at
}
USERS ||--o{ ORGANIZATIONS : "属于"
ORGANIZATIONS ||--o{ LIFECYCLE_PROJECTS : "拥有"
LIFECYCLE_PROJECTS ||--o{ PROJECT_STAGES : "包含"
USERS ||--o{ LIFECYCLE_PROJECTS : "创建"
USERS ||--o{ AGENT_TASKS : "创建"
ORGANIZATIONS ||--o{ AGENT_TASKS : "拥有"
LIFECYCLE_PROJECTS ||--o{ AGENT_TASKS : "关联"
AGENT_REGISTRY ||--o{ AGENT_TASKS : "注册"
AGENT_TASKS ||--o{ AGENT_TASK_LOGS : "产生"
ORGANIZATIONS ||--o{ CONTENTS : "拥有"
LIFECYCLE_PROJECTS ||--o{ CONTENTS : "关联"
USERS ||--o{ CONTENTS : "创建"
CONTENTS ||--o{ CONTENT_VERSIONS : "版本化"
CONTENTS ||--o{ CONTENT_REVIEWS : "审核"
ORGANIZATIONS ||--o{ PLATFORM_RULES : "拥有"
ORGANIZATIONS ||--o{ BRAND_KNOWLEDGE : "拥有"
ORGANIZATIONS ||--o{ KEYWORDS : "拥有"
LIFECYCLE_PROJECTS ||--o{ KEYWORDS : "关联"
ORGANIZATIONS ||--o{ PUBLISH_RECORDS : "拥有"
PUBLISH_RECORDS ||--o{ CONTENT_METRICS : "产生"
ORGANIZATIONS ||--o{ OPTIMIZATION_INSIGHTS : "拥有"
USERS ||--o{ ALERTS : "拥有"
BRANDS ||--o{ ALERTS : "关联"
USERS ||--o{ ALERT_SETTINGS : "拥有"
BRANDS ||--o{ ALERT_SETTINGS : "关联"
ORGANIZATIONS ||--o{ KNOWLEDGE_BASES : "拥有"
KNOWLEDGE_BASES ||--o{ KNOWLEDGE_DOCUMENTS : "包含"
KNOWLEDGE_DOCUMENTS ||--o{ KNOWLEDGE_CHUNKS : "分块"
ORGANIZATIONS ||--o{ KNOWLEDGE_SEARCH_LOGS : "拥有"
USERS ||--o{ KNOWLEDGE_SEARCH_LOGS : "使用"
```
**图表来源**
- [backend/app/models/user.py:11-48](file://backend/app/models/user.py#L11-L48)
- [backend/app/models/lifecycle.py:12-92](file://backend/app/models/lifecycle.py#L12-L92)
- [backend/app/models/analytics.py:9-64](file://backend/app/models/analytics.py#L9-L64)
- [backend/app/models/alert.py:24-75](file://backend/app/models/alert.py#L24-L75)
- [backend/app/models/knowledge.py:22-213](file://backend/app/models/knowledge.py#L22-L213)
**章节来源**
- [backend/app/models/user.py:1-48](file://backend/app/models/user.py#L1-L48)
- [backend/app/models/lifecycle.py:1-92](file://backend/app/models/lifecycle.py#L1-L92)
- [backend/app/models/analytics.py:1-64](file://backend/app/models/analytics.py#L1-L64)
- [backend/app/models/alert.py:1-75](file://backend/app/models/alert.py#L1-L75)
- [backend/app/models/knowledge.py:1-213](file://backend/app/models/knowledge.py#L1-L213)
### 索引策略
- 查询表queries
- idx_queries_user_id按用户过滤
- idx_queries_status按状态过滤
- idx_queries_next_query_at按下次查询时间调度
- 引用记录表citation_records
- idx_citation_records_query_id按查询聚合
- idx_citation_records_queried_at按时间排序/范围
- idx_citation_records_platform按平台统计
- **新增** idx_citation_records_confidence按匹配置信度过滤建议
- **新增** idx_citation_records_match_type按匹配类型过滤建议
- **新增** 用户表users
- idx_users_email按邮箱快速查找
- idx_users_organization_id按组织关联
- idx_users_verification_code按验证码快速验证
- idx_users_reset_token按重置令牌快速验证
- **新增** 组织表organizations
- idx_organizations_slug按slug快速查找
- **新增** 生命周期项目表lifecycle_projects
- idx_lifecycle_projects_organization_id按组织过滤
- idx_lifecycle_projects_status按状态过滤
- idx_lifecycle_projects_brand_name按品牌名称过滤
- **新增** 项目阶段表project_stages
- idx_project_stages_project_id按项目过滤
- idx_project_stages_status按状态过滤
- idx_project_stages_project_stage按项目和阶段唯一约束
- **新增** 代理注册表agent_registry
- idx_agent_registry_name按名称快速查找
- idx_agent_registry_agent_type按代理类型过滤
- idx_agent_registry_status按状态过滤
- **新增** 代理任务表agent_tasks
- idx_agent_tasks_agent_id按代理过滤
- idx_agent_tasks_status按状态过滤
- idx_agent_tasks_organization_id按组织过滤
- idx_agent_tasks_project_id按项目过滤
- idx_agent_tasks_created_by按创建者过滤
- idx_agent_tasks_task_type按任务类型过滤
- **新增** 内容表contents
- idx_contents_organization_id按组织过滤
- idx_contents_project_id按项目过滤
- idx_contents_status按状态过滤
- idx_contents_content_type按类型过滤
- idx_contents_created_by按创建者过滤
- **新增** 知识库表knowledge_bases
- idx_knowledge_bases_organization_id按组织过滤
- idx_knowledge_bases_type按类型过滤
- idx_knowledge_bases_status按状态过滤
- **新增** 知识文档表knowledge_documents
- idx_knowledge_documents_knowledge_base_id按知识库过滤
- idx_knowledge_documents_status按状态过滤
- idx_knowledge_documents_content_hash按内容哈希过滤
- **新增** 知识分块表knowledge_chunks
- idx_knowledge_chunks_document_id按文档过滤
- idx_knowledge_chunks_chunk_index按分块索引过滤
- **新增** 向量索引ix_knowledge_chunks_embeddingHNSW近似最近邻搜索
- **新增** 分析监控表
- idx_publish_records_organization_id按组织过滤
- idx_publish_records_platform按平台过滤
- idx_publish_records_status按状态过滤
- idx_publish_records_created_at按创建时间过滤
- idx_content_metrics_publish_record_id按发布记录过滤
- idx_content_metrics_recorded_at按记录时间过滤
- idx_optimization_insights_organization_id按组织过滤
- idx_optimization_insights_insight_type按洞察类型过滤
- idx_optimization_insights_created_at按创建时间过滤
- **新增** 告警系统表
- idx_alerts_user_id按用户过滤
- idx_alerts_brand_id按品牌过滤
- idx_alerts_alert_type按告警类型过滤
- idx_alerts_is_read按是否已读过滤
- idx_alerts_created_at按创建时间过滤
- idx_alerts_user_read按用户和已读状态组合过滤
- idx_alert_settings_brand_id按品牌过滤
- idx_alert_settings_user_id按用户过滤
- idx_alert_settings_brand_type按品牌和类型组合唯一约束
**更新** 新增针对所有新增表的索引策略,特别是知识库的向量索引和告警系统的复合索引。
这些索引覆盖了常见查询路径与统计场景,有助于提升分页、过滤、排序与聚合的性能。
**章节来源**
- [backend/alembic/versions/488d0bd5ab01_initial_migration.py:57-94](file://backend/alembic/versions/488d0bd5ab01_initial_migration.py#L57-L94)
- [backend/alembic/versions/b2c4d6e8fa10_add_confidence_match_type_to_citation_records.py:21-37](file://backend/alembic/versions/b2c4d6e8fa10_add_confidence_match_type_to_citation_records.py#L21-L37)
- [backend/alembic/versions/c3d5e7f9ab12_add_user_management_fields.py:21-41](file://backend/alembic/versions/c3d5e7f9ab12_add_user_management_fields.py#L21-L41)
- [backend/alembic/versions/d4f6g8h0ab23_add_geo_lifecycle_tables.py:24-398](file://backend/alembic/versions/d4f6g8h0ab23_add_geo_lifecycle_tables.py#L24-L398)
- [backend/alembic/versions/f6g8h0i2de56_add_analytics_tables.py:24-125](file://backend/alembic/versions/f6g8h0i2de56_add_analytics_tables.py#L24-L125)
- [backend/alembic/versions/e5f7a9b1cd34_add_alerts_and_alert_settings_tables.py:24-86](file://backend/alembic/versions/e5f7a9b1cd34_add_alerts_and_alert_settings_tables.py#L24-L86)
- [backend/alembic/versions/e5f7g9h1cd45_add_knowledge_base_tables.py:30-224](file://backend/alembic/versions/e5f7g9h1cd45_add_knowledge_base_tables.py#L30-L224)
### SQLAlchemy ORM 模型实现
- 字段类型与默认值
- UUID 主键与外键JSONB 存储数组/字典,布尔、整数、文本、数值、时间戳等。
- 默认值通过 server_default/onupdate 设置,减少应用层重复逻辑。
- **新增** 组织表slug唯一约束max_members默认5plan默认'free'。
- **新增** 生命周期项目表current_stage默认1status默认'active'。
- **新增** 项目阶段表status默认'pending'stage_number非空。
- **新增** 代理注册表name唯一约束status默认'offline'。
- **新增** 代理配置表config_key唯一约束updated_at自动更新。
- **新增** 代理任务表多个索引字段status默认'pending'priority默认0。
- **新增** 内容表status默认'draft'current_version默认1。
- **新增** 内容版本表version_number非空unique约束。
- **新增** 内容审核表status非空。
- **新增** 平台规则表severity非空is_active默认true。
- **新增** 品牌知识表is_active默认true。
- **新增** 关键词表priority默认0status默认'active'。
- **新增** 发布记录表status默认'draft'。
- **新增** 内容指标表多个默认值avg_read_duration默认0.0。
- **新增** 优化洞察表severity默认'info'applied默认false。
- **新增** 告警表is_read默认false。
- **新增** 告警设置表enabled默认truethreshold可为空。
- **新增** 知识库表document_count默认0status默认'active'。
- **新增** 知识文档表chunk_count默认0status默认'processing'。
- **新增** 知识分块表token_count默认0。
- **新增** 知识检索日志表results_count默认0latency_ms默认0。
- **新增** email_verified字段Boolean类型默认False用于邮箱验证状态。
- **新增** verification_code字段String类型长度6nullable=True用于存储6位验证码。
- **新增** verification_code_expires字段DateTime类型nullable=True用于验证码过期时间。
- **新增** reset_token字段String类型长度255nullable=True用于密码重置令牌。
- **新增** reset_token_expires字段DateTime类型nullable=True用于重置令牌过期时间。
- **新增** avatar_url字段String类型长度500nullable=True用于用户头像URL。
- **新增** is_admin字段Boolean类型默认False用于管理员权限控制。
- **新增** confidence字段Float类型nullable=True用于存储匹配的可信度评分。
- **新增** match_type字段String类型长度20nullable=True用于标识匹配类型。
- 关系配置
- 用户与组织多对一支持NULL值用户未加入组织
- 组织与生命周期项目:一对多,级联删除。
- 项目与阶段:一对多,级联删除与孤儿对象清理。
- 代理注册与配置:一对多,级联删除。
- 代理注册与任务:一对多,级联删除。
- 代理任务与日志:一对多,级联删除。
- 组织与内容:一对多,级联删除。
- 内容与版本:一对多,级联删除与唯一约束。
- 内容与审核:一对多,级联删除。
- 组织与平台规则:一对多,级联删除。
- 组织与品牌知识:一对多,级联删除。
- 组织与关键词:一对多,级联删除。
- 项目与关键词:一对多,级联删除。
- 知识库与文档:一对多,级联删除。
- 文档与分块:一对多,级联删除。
- 组织与发布记录:一对多,级联删除。
- 发布记录与指标:一对多,级联删除。
- 组织与优化洞察:一对多,级联删除。
- 用户与告警:一对多,级联删除。
- 品牌与告警:一对多,级联删除。
- 用户与告警设置:一对多,级联删除。
- 品牌与告警设置:一对多,级联删除。
- 组织与知识库:一对多,级联删除。
- 组织与知识检索日志:一对多,级联删除。
- 用户与知识检索日志:一对多,级联删除。
- 查询封装
- 服务层使用 select + func + join 封装复杂查询,统一处理分页与计数。
- 权限校验:仅允许访问当前用户的资源,防止越权。
- **新增** 生命周期服务:管理项目全生命周期,支持阶段转换和状态管理。
- **新增** 分析监控服务:处理内容发布流程和指标收集。
- **新增** 告警引擎服务:实时处理告警规则和通知。
- **新增** 知识库服务处理向量检索和RAG应用。
**更新** 新增完整的生命周期、分析监控、告警系统、知识库等ORM模型实现支持复杂的业务关系和查询需求。
```mermaid
classDiagram
class User {
+id : uuid
+email : string
+password_hash : string
+name : string
+plan : string
+max_queries : int
+is_active : bool
+organization_id : uuid
+role : string
+email_verified : bool
+verification_code : string
+verification_code_expires : datetime
+reset_token : string
+reset_token_expires : datetime
+avatar_url : string
+is_admin : bool
+created_at : datetime
+updated_at : datetime
+organization
+queries
+subscriptions
+lifecycle_projects
+agent_tasks
+contents
+knowledge_bases
}
class Organization {
+id : uuid
+name : string
+slug : string
+description : string
+logo_url : string
+plan : string
+max_members : int
+created_at : datetime
+updated_at : datetime
+users
+lifecycle_projects
+agent_tasks
+contents
+platform_rules
+brand_knowledge
+keywords
+knowledge_bases
+publish_records
+optimization_insights
+knowledge_search_logs
}
class LifecycleProject {
+id : uuid
+organization_id : uuid
+brand_name : string
+brand_aliases : list
+current_stage : int
+status : string
+created_by : uuid
+created_at : datetime
+updated_at : datetime
+organization
+stages
+creator
+agent_tasks
+contents
+keywords
}
class ProjectStage {
+id : uuid
+project_id : uuid
+stage_number : int
+status : string
+started_at : datetime
+completed_at : datetime
+notes : string
+metrics : dict
+project
}
class AgentRegistry {
+id : uuid
+name : string
+display_name : string
+agent_type : string
+description : string
+version : string
+endpoint : string
+status : string
+capabilities : dict
+last_heartbeat : datetime
+created_at : datetime
+updated_at : datetime
+configs
+tasks
}
class AgentConfig {
+id : uuid
+agent_id : uuid
+config_key : string
+config_value : dict
+description : string
+updated_at : datetime
+updated_by : uuid
+agent
}
class AgentTask {
+id : uuid
+agent_id : uuid
+task_type : string
+status : string
+priority : int
+input_data : dict
+output_data : dict
+error_message : string
+created_by : uuid
+organization_id : uuid
+project_id : uuid
+scheduled_at : datetime
+started_at : datetime
+completed_at : datetime
+created_at : datetime
+agent
+logs
}
class AgentTaskLog {
+id : uuid
+task_id : uuid
+agent_id : uuid
+log_level : string
+message : string
+metadata : dict
+created_at : datetime
+task
+agent
}
class Content {
+id : uuid
+organization_id : uuid
+project_id : uuid
+title : string
+content_type : string
+body : string
+status : string
+target_platforms : list
+keywords : list
+metadata : dict
+created_by : uuid
+current_version : int
+created_at : datetime
+updated_at : datetime
+versions
+reviews
+metrics
}
class ContentVersion {
+id : uuid
+content_id : uuid
+version_number : int
+title : string
+body : string
+change_summary : string
+created_by : uuid
+created_at : datetime
+content
}
class ContentReview {
+id : uuid
+content_id : uuid
+reviewer_id : uuid
+status : string
+comments : string
+created_at : datetime
+content
+reviewer
}
class PlatformRule {
+id : uuid
+platform : string
+rule_category : string
+rule_name : string
+description : string
+check_criteria : dict
+severity : string
+is_active : bool
+updated_at : datetime
}
class BrandKnowledge {
+id : uuid
+organization_id : uuid
+category : string
+title : string
+content : string
+metadata : dict
+is_active : bool
+created_by : uuid
+created_at : datetime
+updated_at : datetime
+organization
+creator
}
class Keyword {
+id : uuid
+organization_id : uuid
+project_id : uuid
+keyword : string
+category : string
+priority : int
+search_volume : int
+competition_level : string
+status : string
+created_at : datetime
+organization
+project
}
class PublishRecord {
+id : string
+organization_id : string
+content_title : string
+content_id : string
+platform : string
+published_url : string
+status : string
+published_at : datetime
+created_at : datetime
+metrics
}
class ContentMetrics {
+id : string
+publish_record_id : string
+recorded_at : datetime
+views : int
+likes : int
+comments : int
+shares : int
+bookmarks : int
+ai_citation_count : int
+search_impressions : int
+search_clicks : int
+avg_read_duration : float
+read_completion_rate : float
+publish_record
}
class OptimizationInsight {
+id : string
+organization_id : string
+content_id : string
+insight_type : string
+title : string
+description : string
+recommendation : string
+severity : string
+applied : bool
+created_at : datetime
+organization
}
class Alert {
+id : uuid
+brand_id : uuid
+user_id : uuid
+alert_type : string
+severity : string
+title : string
+message : string
+data : dict
+is_read : bool
+created_at : datetime
+brand
}
class AlertSetting {
+id : uuid
+brand_id : uuid
+user_id : uuid
+alert_type : string
+enabled : bool
+threshold : float
+created_at : datetime
+updated_at : datetime
+brand
+user
}
class KnowledgeBase {
+id : uuid
+organization_id : uuid
+name : string
+type : string
+description : string
+document_count : int
+status : string
+created_by : uuid
+created_at : datetime
+updated_at : datetime
+organization
+creator
+documents
}
class KnowledgeDocument {
+id : uuid
+knowledge_base_id : uuid
+title : string
+source_type : string
+source_url : string
+content : string
+content_hash : string
+chunk_count : int
+status : string
+error_message : string
+metadata : dict
+created_at : datetime
+updated_at : datetime
+knowledge_base
+chunks
}
class KnowledgeChunk {
+id : uuid
+document_id : uuid
+content : string
+embedding : vector
+chunk_index : int
+token_count : int
+metadata : dict
+created_at : datetime
+document
}
class KnowledgeSearchLog {
+id : uuid
+organization_id : uuid
+user_id : uuid
+query : string
+knowledge_base_ids : list
+results_count : int
+latency_ms : int
+created_at : datetime
+organization
+user
}
User "1" <-- "many" Organization : "属于"
Organization "1" <-- "many" LifecycleProject : "拥有"
LifecycleProject "1" <-- "many" ProjectStage : "包含"
User "1" <-- "many" LifecycleProject : "创建"
AgentRegistry "1" <-- "many" AgentTask : "注册"
AgentTask "1" <-- "many" AgentTaskLog : "产生"
Organization "1" <-- "many" Content : "拥有"
LifecycleProject "1" <-- "many" Content : "关联"
User "1" <-- "many" Content : "创建"
Content "1" <-- "many" ContentVersion : "版本化"
Content "1" <-- "many" ContentReview : "审核"
Organization "1" <-- "many" PlatformRule : "拥有"
Organization "1" <-- "many" BrandKnowledge : "拥有"
Organization "1" <-- "many" Keyword : "拥有"
LifecycleProject "1" <-- "many" Keyword : "关联"
Organization "1" <-- "many" KnowledgeBase : "拥有"
KnowledgeBase "1" <-- "many" KnowledgeDocument : "包含"
KnowledgeDocument "1" <-- "many" KnowledgeChunk : "分块"
Organization "1" <-- "many" PublishRecord : "拥有"
PublishRecord "1" <-- "many" ContentMetrics : "产生"
Organization "1" <-- "many" OptimizationInsight : "拥有"
User "1" <-- "many" Alert : "拥有"
User "1" <-- "many" AlertSetting : "拥有"
Organization "1" <-- "many" KnowledgeSearchLog : "拥有"
User "1" <-- "many" KnowledgeSearchLog : "使用"
```
**图表来源**
- [backend/app/models/user.py:11-48](file://backend/app/models/user.py#L11-L48)
- [backend/app/models/lifecycle.py:12-92](file://backend/app/models/lifecycle.py#L12-L92)
- [backend/app/models/analytics.py:9-64](file://backend/app/models/analytics.py#L9-L64)
- [backend/app/models/alert.py:24-75](file://backend/app/models/alert.py#L24-L75)
- [backend/app/models/knowledge.py:22-213](file://backend/app/models/knowledge.py#L22-L213)
**章节来源**
- [backend/app/models/user.py:1-48](file://backend/app/models/user.py#L1-L48)
- [backend/app/models/lifecycle.py:1-92](file://backend/app/models/lifecycle.py#L1-L92)
- [backend/app/models/analytics.py:1-64](file://backend/app/models/analytics.py#L1-L64)
- [backend/app/models/alert.py:1-75](file://backend/app/models/alert.py#L1-L75)
- [backend/app/models/knowledge.py:1-213](file://backend/app/models/knowledge.py#L1-L213)
### 数据库迁移管理、版本控制与部署策略
- 迁移入口
- Alembic 环境加载 Base 元数据,支持离线/在线迁移。
- 在线迁移通过异步引擎连接数据库,避免阻塞。
- 迁移版本
- **初始版本** (488d0bd5ab01):创建 users、queries、citation_records、query_tasks、subscriptions 表,并建立必要索引。
- **版本2** (b2c4d6e8fa10):向 citation_records 表添加 confidence 和 match_type 字段,支持增强的报告功能。
- **版本3** (c3d5e7f9ab12):向 users 表添加 email_verified、verification_code、verification_code_expires、reset_token、reset_token_expires、avatar_url、is_admin 等用户管理字段。
- **新增版本4** (d4f6g8h0ab23):新增完整的业务生命周期架构,包括 organizations、lifecycle_projects、project_stages、agent_registry、agent_configs、agent_tasks、agent_task_logs、contents、content_versions、content_reviews、platform_rules、brand_knowledge、keywords 等表。
- **新增版本5** (e5f7a9b1cd34):新增告警系统,包括 alerts 和 alert_settings 表,支持品牌监控和用户告警。
- **新增版本6** (e5f7g9h1cd45):新增知识库系统,包括 knowledge_bases、knowledge_documents、knowledge_chunks含向量索引、knowledge_search_logs 表支持pgvector向量检索。
- **新增版本7** (f6g8h0i2de56):新增分析监控系统,包括 publish_records、content_metrics、optimization_insights 表。
- 外键约束与级联删除策略明确,确保数据一致性。
- 部署策略
- Docker Compose 启动 PostgreSQL 与 Redis应用容器依赖数据库健康检查。
- 生产环境建议将数据库与缓存分离,使用独立卷持久化数据。
- **新增** 向量数据库部署知识库功能需要pgvector扩展支持。
- **新增** 分区策略大数据量表建议按时间分区如content_metrics、knowledge_search_logs。
**更新** 新增完整的7个版本迁移涵盖业务生命周期、分析监控、告警系统、知识库等企业级功能。
```mermaid
flowchart TD
Start(["开始"]) --> CheckEnv["检查 DATABASE_URL"]
CheckEnv --> LoadBase["加载 Base 元数据"]
LoadBase --> Mode{"运行模式"}
Mode --> |离线| Offline["配置 URL 与元数据"]
Mode --> |在线| Online["创建异步引擎并连接"]
Offline --> RunMigs["执行迁移"]
Online --> RunMigs
RunMigs --> Version{"检查版本"}
Version --> |488d0bd5ab01| InitMigration["初始迁移"]
Version --> |b2c4d6e8fa10| AddConfidence["添加置信度字段"]
Version --> |c3d5e7f9ab12| AddUserFields["添加用户管理字段"]
Version --> |d4f6g8h0ab23| AddLifecycle["添加生命周期架构"]
Version --> |e5f7a9b1cd34| AddAlerts["添加告警系统"]
Version --> |e5f7g9h1cd45| AddKnowledge["添加知识库系统"]
Version --> |f6g8h0i2de56| AddAnalytics["添加分析监控"]
InitMigration --> AddConfidence --> AddUserFields --> AddLifecycle --> AddAlerts --> AddKnowledge --> AddAnalytics --> Done(["完成"])
```
**图表来源**
- [backend/alembic/env.py:33-88](file://backend/alembic/env.py#L33-L88)
- [backend/alembic/versions/488d0bd5ab01_initial_migration.py:21-128](file://backend/alembic/versions/488d0bd5ab01_initial_migration.py#L21-L128)
- [backend/alembic/versions/b2c4d6e8fa10_add_confidence_match_type_to_citation_records.py:21-37](file://backend/alembic/versions/b2c4d6e8fa10_add_confidence_match_type_to_citation_records.py#L21-L37)
- [backend/alembic/versions/c3d5e7f9ab12_add_user_management_fields.py:21-41](file://backend/alembic/versions/c3d5e7f9ab12_add_user_management_fields.py#L21-L41)
- [backend/alembic/versions/d4f6g8h0ab23_add_geo_lifecycle_tables.py:21-398](file://backend/alembic/versions/d4f6g8h0ab23_add_geo_lifecycle_tables.py#L21-L398)
- [backend/alembic/versions/e5f7a9b1cd34_add_alerts_and_alert_settings_tables.py:21-86](file://backend/alembic/versions/e5f7a9b1cd34_add_alerts_and_alert_settings_tables.py#L21-L86)
- [backend/alembic/versions/e5f7g9h1cd45_add_knowledge_base_tables.py:21-224](file://backend/alembic/versions/e5f7g9h1cd45_add_knowledge_base_tables.py#L21-L224)
- [backend/alembic/versions/f6g8h0i2de56_add_analytics_tables.py:20-125](file://backend/alembic/versions/f6g8h0i2de56_add_analytics_tables.py#L20-L125)
- [docker-compose.yml:1-71](file://docker-compose.yml#L1-L71)
**章节来源**
- [backend/alembic/env.py:1-89](file://backend/alembic/env.py#L1-L89)
- [backend/alembic/versions/488d0bd5ab01_initial_migration.py:1-128](file://backend/alembic/versions/488d0bd5ab01_initial_migration.py#L1-L128)
- [backend/alembic/versions/b2c4d6e8fa10_add_confidence_match_type_to_citation_records.py:1-37](file://backend/alembic/versions/b2c4d6e8fa10_add_confidence_match_type_to_citation_records.py#L1-L37)
- [backend/alembic/versions/c3d5e7f9ab12_add_user_management_fields.py:1-41](file://backend/alembic/versions/c3d5e7f9ab12_add_user_management_fields.py#L1-L41)
- [backend/alembic/versions/d4f6g8h0ab23_add_geo_lifecycle_tables.py:1-398](file://backend/alembic/versions/d4f6g8h0ab23_add_geo_lifecycle_tables.py#L1-L398)
- [backend/alembic/versions/e5f7a9b1cd34_add_alerts_and_alert_settings_tables.py:1-86](file://backend/alembic/versions/e5f7a9b1cd34_add_alerts_and_alert_settings_tables.py#L1-L86)
- [backend/alembic/versions/e5f7g9h1cd45_add_knowledge_base_tables.py:1-224](file://backend/alembic/versions/e5f7g9h1cd45_add_knowledge_base_tables.py#L1-L224)
- [backend/alembic/versions/f6g8h0i2de56_add_analytics_tables.py:1-125](file://backend/alembic/versions/f6g8h0i2de56_add_analytics_tables.py#L1-L125)
- [docker-compose.yml:1-71](file://docker-compose.yml#L1-L71)
### 数据完整性约束、事务处理与并发控制
- 完整性约束
- 唯一约束用户邮箱唯一组织slug唯一代理name唯一关键词(organization_id, project_id, keyword)唯一,代理配置(agent_id, config_key)唯一,项目阶段(project_id, stage_number)唯一,告警设置(brand_id, alert_type)唯一。
- 外键约束所有外键均设置适当的ondelete策略CASCADE/SET NULL确保数据一致性。
- JSONB字段默认值空数组/字典避免NULL导致的条件判断复杂化。
- **新增** 组织表max_members默认5plan默认'free'。
- **新增** 生命周期项目表current_stage默认1status默认'active'。
- **新增** 项目阶段表stage_number非空status默认'pending'。
- **新增** 代理注册表name唯一status默认'offline'。
- **新增** 代理配置表config_key唯一updated_at自动更新。
- **新增** 代理任务表:多个默认值和索引字段。
- **新增** 内容表status默认'draft'current_version默认1。
- **新增** 知识库表document_count默认0status默认'active'。
- **新增** email_verified字段默认Falseis_admin字段默认False。
- **新增** verification_code长度限制为6位reset_token长度限制为255位。
- **新增** avatar_url长度限制为500字符match_type长度限制为20字符。
- 事务处理
- 服务层方法在单个事务内执行插入/更新/删除,提交后刷新对象状态。
- 会话工厂设置 expire_on_commit=False减少后续查询的额外开销。
- **新增** 生命周期服务:事务边界严格控制项目状态转换。
- **新增** 分析监控服务:发布记录与指标的原子性操作。
- **新增** 告警引擎服务:告警规则评估的事务一致性。
- **新增** 知识库服务:文档处理与向量嵌入的事务保障。
- 并发控制
- 异步连接池与会话隔离,避免阻塞。
- 服务层在执行前进行权限校验与配额检查,降低并发冲突概率。
- **新增** 向量索引并发HNSW索引支持高并发相似度搜索。
- **新增** 分布式锁:代理任务的分布式并发控制。
**更新** 新增针对所有新增表的完整性约束说明,包括复合唯一约束和外键策略。
**章节来源**
- [backend/alembic/versions/488d0bd5ab01_initial_migration.py:36-111](file://backend/alembic/versions/488d0bd5ab01_initial_migration.py#L36-L111)
- [backend/alembic/versions/b2c4d6e8fa10_add_confidence_match_type_to_citation_records.py:21-37](file://backend/alembic/versions/b2c4d6e8fa10_add_confidence_match_type_to_citation_records.py#L21-L37)
- [backend/alembic/versions/c3d5e7f9ab12_add_user_management_fields.py:21-41](file://backend/alembic/versions/c3d5e7f9ab12_add_user_management_fields.py#L21-L41)
- [backend/alembic/versions/d4f6g8h0ab23_add_geo_lifecycle_tables.py:24-398](file://backend/alembic/versions/d4f6g8h0ab23_add_geo_lifecycle_tables.py#L24-L398)
- [backend/alembic/versions/e5f7a9b1cd34_add_alerts_and_alert_settings_tables.py:24-86](file://backend/alembic/versions/e5f7a9b1cd34_add_alerts_and_alert_settings_tables.py#L24-L86)
- [backend/alembic/versions/e5f7g9h1cd45_add_knowledge_base_tables.py:30-224](file://backend/alembic/versions/e5f7g9h1cd45_add_knowledge_base_tables.py#L30-L224)
- [backend/alembic/versions/f6g8h0i2de56_add_analytics_tables.py:24-125](file://backend/alembic/versions/f6g8h0i2de56_add_analytics_tables.py#L24-L125)
- [backend/app/services/query.py:45-81](file://backend/app/services/query.py#L45-L81)
- [backend/app/database.py:12-18](file://backend/app/database.py#L12-L18)
### 查询流程与优化要点
- 查询列表与计数
- 分页查询与计数分离,避免重复扫描全表
- 使用索引覆盖 user_id 与 created_at 排序
- **新增** 支持按confidence和match_type过滤查询
- 引用统计
- 使用 JOIN 查询限定到用户所属的查询
- 按平台分组统计,利用索引加速 queried_at 与 platform
- **新增** 支持按匹配置信度和匹配类型进行统计分析
- 导出 CSV
- 以查询为维度导出,先验证所有权再执行导出
- **新增** 输出confidence和match_type字段到CSV文件
- **新增** 用户管理查询
- 支持按邮箱验证状态、管理员权限等条件过滤用户
- 支持验证码和重置令牌的有效性检查
- **新增** 生命周期查询
- 支持按组织、状态、品牌名称过滤项目
- 支持按阶段状态和项目阶段组合查询
- 支持项目全生命周期统计分析
- **新增** 分析监控查询
- 支持按平台、状态、时间范围过滤发布记录
- 支持内容指标的时间序列分析
- 支持优化洞察的分类统计
- **新增** 告警查询
- 支持按用户、品牌、告警类型、严重程度过滤
- 支持告警设置的阈值比较查询
- 支持用户未读告警的统计
- **新增** 知识库查询
- 支持向量相似度搜索cosine距离
- 支持知识库文档的状态过滤
- 支持关键词检索和内容哈希去重
- **新增** 性能优化
- 知识库向量索引HNSW近似最近邻搜索支持大规模向量相似度计算
- 复合索引:告警系统(brand_id, alert_type)、关键词(keyword)等
- 分区策略大表按时间分区如content_metrics、knowledge_search_logs
**更新** 新增针对所有新增功能的查询流程和优化策略,特别是向量检索和复合查询的性能优化。
**章节来源**
- [backend/app/services/query.py:12-32](file://backend/app/services/query.py#L12-L32)
- [backend/app/services/citation.py:30-79](file://backend/app/services/citation.py#L30-L79)
- [backend/app/services/auth.py:40-56](file://backend/app/services/auth.py#L40-L56)
### 报告功能增强
- **匹配置信度分析**
- confidence字段用于存储匹配的可信度评分0.0-1.0
- 支持按置信度区间进行统计分析
- 在CSV导出中显示详细的置信度信息
- **匹配类型分类**
- match_type字段标识匹配类型exact精确匹配、alias别名匹配、fuzzy模糊匹配
- 支持按匹配类型进行分组统计
- 在报告中提供中文显示(精确匹配、别名匹配、模糊匹配)
- **增强的统计指标**
- 支持按置信度和匹配类型的组合进行交叉分析
- 提供更精细的引用质量评估
**新增** 报告功能章节详细介绍新增的confidence和match_type字段的应用。
**章节来源**
- [backend/app/services/citation.py:298-308](file://backend/app/services/citation.py#L298-L308)
- [backend/app/services/citation.py:342-429](file://backend/app/services/citation.py#L342-L429)
- [backend/app/schemas/citation.py:7-18](file://backend/app/schemas/citation.py#L7-L18)
### 用户管理功能
- **邮箱验证系统**
- email_verified字段跟踪邮箱验证状态
- verification_code和verification_code_expires字段管理验证码
- 支持验证码重发和过期检查
- **密码重置系统**
- reset_token和reset_token_expires字段管理重置令牌
- 支持安全的密码重置流程
- **用户资料管理**
- name字段存储用户姓名
- avatar_url字段存储用户头像URL
- 支持资料更新和头像上传
- **管理员权限控制**
- is_admin字段标识管理员身份
- 支持管理员专用功能和权限控制
- **组织管理**
- **新增** organization_id字段关联用户到组织
- **新增** role字段标识用户在组织中的角色
- **新增** 支持多组织成员管理
**新增** 用户管理功能章节详细介绍新增的用户管理字段和相关API。
**章节来源**
- [backend/app/services/auth.py:74-107](file://backend/app/services/auth.py#L74-L107)
- [backend/app/services/auth.py:110-140](file://backend/app/services/auth.py#L110-L140)
- [backend/app/schemas/auth.py:8-55](file://backend/app/schemas/auth.py#L8-L55)
- [backend/app/api/auth.py:33-115](file://backend/app/api/auth.py#L33-L115)
### 业务生命周期管理
- **组织管理**
- 组织作为业务单元,支持多用户协作
- plan字段支持免费/付费计划管理
- max_members限制组织规模
- **项目管理**
- lifecycle_projects表管理品牌项目全生命周期
- current_stage跟踪项目当前所处阶段
- status支持active/inactive状态管理
- **阶段管理**
- project_stages表管理项目各阶段状态
- 支持started_at/completed_at时间跟踪
- metrics字段存储阶段关键指标
- **代理系统**
- agent_registry注册可用代理
- agent_configs管理代理配置
- agent_tasks执行代理任务
- agent_task_logs记录任务执行日志
- **内容管理**
- contents表管理内容创作
- content_versions支持版本控制
- content_reviews支持审核流程
- **规则管理**
- platform_rules定义平台合规规则
- 支持不同严重程度的规则
- **知识管理**
- brand_knowledge存储品牌知识
- 支持分类和激活状态管理
- **关键词管理**
- keywords管理SEO关键词
- 支持优先级和搜索量统计
**新增** 业务生命周期管理章节,详细介绍完整的项目管理架构。
**章节来源**
- [backend/app/models/lifecycle.py:12-92](file://backend/app/models/lifecycle.py#L12-L92)
- [backend/app/api/lifecycle.py](file://backend/app/api/lifecycle.py)
### 分析监控系统
- **发布管理**
- publish_records跟踪内容发布状态
- 支持多平台发布(微信、知乎、小红书等)
- published_url记录发布链接
- **指标分析**
- content_metrics收集互动指标点赞、评论、分享等
- GEO核心指标AI引用次数、搜索曝光、搜索点击
- 阅读指标:平均阅读时长、完读率
- **优化洞察**
- optimization_insights提供内容优化建议
- 支持不同类型洞察(趋势、异常、机会、建议)
- severity字段标识严重程度
- applied字段跟踪建议实施状态
**新增** 分析监控系统章节,详细介绍内容发布和指标分析架构。
**章节来源**
- [backend/app/models/analytics.py:9-64](file://backend/app/models/analytics.py#L9-L64)
- [backend/app/api/analytics.py](file://backend/app/api/analytics.py)
### 告警系统
- **告警类型**
- score_drop评分下降告警
- score_rise评分上升告警
- negative_sentiment负面情绪告警
- competitor_overtake竞争对手超越告警
- new_platform_mention新平台提及告警
- **严重程度**
- critical严重
- warning警告
- info信息
- **告警设置**
- alert_settings表管理用户告警偏好
- 支持阈值设置和启用状态控制
- 支持按品牌和用户维度配置
**新增** 告警系统章节,详细介绍实时监控和告警机制。
**章节来源**
- [backend/app/models/alert.py:24-75](file://backend/app/models/alert.py#L24-L75)
- [backend/app/api/alerts.py](file://backend/app/api/alerts.py)
### 知识库系统
- **向量检索**
- knowledge_chunks表存储文档分块
- embedding字段使用pgvector向量类型
- HNSW索引支持近似最近邻搜索
- 维度1536匹配OpenAI text-embedding-3-small
- **文档管理**
- knowledge_documents管理知识文档
- content_hash去重机制
- 支持多种文档类型text、url、pdf、markdown
- **检索日志**
- knowledge_search_logs记录检索行为
- 支持延迟毫秒统计
- 支持知识库ID列表过滤
**新增** 知识库系统章节详细介绍向量检索和RAG应用架构。
**章节来源**
- [backend/app/models/knowledge.py:22-213](file://backend/app/models/knowledge.py#L22-L213)
- [backend/app/api/knowledge.py](file://backend/app/api/knowledge.py)
## 依赖分析
- 模块耦合
- 模型层仅依赖 Base 与 SQLAlchemy 类型,低耦合
- 服务层依赖模型与会话,职责清晰
- Alembic 依赖 Base 与配置,迁移脚本与模型同步演进
- **新增** API层依赖服务层提供RESTful接口
- **新增** 认证API依赖认证服务处理用户注册、登录、验证等
- **新增** 生命周期API依赖生命周期服务管理项目全生命周期
- **新增** 分析监控API依赖分析监控服务处理发布和指标
- **新增** 告警API依赖告警引擎服务处理实时告警
- **新增** 知识库API依赖知识库服务处理向量检索
- 外部依赖
- PostgreSQL 异步驱动asyncpg
- Redis用于缓存如需要
- **新增** pgvector扩展向量检索
- **新增** 向量数据库(可选)
**更新** 新增针对所有新增功能模块的依赖关系分析。
```mermaid
graph LR
Cfg["配置<br/>config.py"] --> DB["数据库引擎<br/>database.py"]
DB --> Models["ORM 模型<br/>models/*"]
Models --> Services["服务层<br/>services/*"]
Services --> AuthAPI["认证API<br/>api/auth.py"]
Services --> LifeCycleAPI["生命周期API<br/>api/lifecycle.py"]
Services --> AnalyticsAPI["分析监控API<br/>api/analytics.py"]
Services --> AlertsAPI["告警API<br/>api/alerts.py"]
Services --> KnowledgeAPI["知识库API<br/>api/knowledge.py"]
Services --> CitationsAPI["引用API<br/>api/citations.py"]
Services --> ReportsAPI["报告API<br/>api/reports.py"]
Alembic["迁移<br/>alembic/*"] --> DB
Docker["编排<br/>docker-compose.yml"] --> DB
Vector["向量数据库<br/>pgvector"] --> DB
```
**图表来源**
- [backend/app/config.py:1-23](file://backend/app/config.py#L1-L23)
- [backend/app/database.py:1-29](file://backend/app/database.py#L1-L29)
- [backend/app/models/__init__.py:1-14](file://backend/app/models/__init__.py#L1-L14)
- [backend/alembic/env.py:1-89](file://backend/alembic/env.py#L1-L89)
- [docker-compose.yml:1-71](file://docker-compose.yml#L1-L71)
**章节来源**
- [backend/app/config.py:1-23](file://backend/app/config.py#L1-L23)
- [backend/app/database.py:1-29](file://backend/app/database.py#L1-L29)
- [backend/app/models/__init__.py:1-14](file://backend/app/models/__init__.py#L1-L14)
- [backend/alembic/env.py:1-89](file://backend/alembic/env.py#L1-L89)
- [docker-compose.yml:1-71](file://docker-compose.yml#L1-L71)
## 性能考虑
- 索引优化
- 为高频过滤字段建立单列索引user_id/status/next_query_at/platform/queried_at/confidence/match_type
- 对 JSONB 字段可考虑 GIN 索引(如需复杂查询),当前迁移脚本未启用
- **新增** 为用户管理字段建立索引email、organization_id、verification_code、reset_token
- **新增** 为生命周期表建立复合索引:(organization_id, status)、(project_id, stage_number)、(brand_id, keyword)
- **新增** 为代理系统建立复合索引:(agent_id, status)、(organization_id, project_id)、(created_by, task_type)
- **新增** 为分析监控建立复合索引:(organization_id, platform)、(publish_record_id, recorded_at)
- **新增** 为告警系统建立复合索引:(brand_id, alert_type)、(user_id, is_read)、(organization_id, insight_type)
- **新增** 为知识库建立向量索引HNSW(cosine)支持大规模相似度搜索
- **新增** 建议为confidence和match_type字段建立单独索引支持高效过滤
- 查询优化
- 分页与计数分离,避免重复扫描
- 使用 JOIN 限定用户范围,减少全表扫描
- 时间范围查询使用索引覆盖
- **新增** 支持按confidence范围和match_type进行高效过滤
- **新增** 支持按邮箱验证状态和管理员权限进行高效过滤
- **新增** 支持向量相似度搜索的性能优化
- **新增** 复合查询的索引选择性分析
- 缓存策略
- 引用统计与趋势数据可缓存至 Redis设置合理过期时间
- 导出 CSV 可缓存热点查询结果,降低数据库压力
- **新增** 认证令牌和用户会话可缓存,提高认证效率
- **新增** 报告统计数据可缓存,提高频繁访问的响应速度
- **新增** 知识库检索结果可缓存,降低向量搜索压力
- **新增** 代理任务状态可缓存,提高任务调度效率
- 连接与并发
- 使用异步连接池,避免阻塞
- 控制并发度,避免大量写入导致锁争用
- **新增** 向量索引并发控制避免HNSW索引锁定
- **新增** 分布式锁机制,确保代理任务并发安全
- 存储优化
- **新增** 分区策略:按月/季度分区content_metrics、knowledge_search_logs
- **新增** 归档策略:历史数据归档到冷存储
- **新增** 压缩策略JSONB字段压缩存储
**更新** 新增针对所有新增功能的性能优化建议,特别是向量检索和复合查询的优化策略。
## 故障排查指南
- 迁移失败
- 检查 DATABASE_URL 是否正确Alembic 配置与环境变量一致
- 确认数据库已初始化且用户具备权限
- **新增** 检查新字段的默认值和约束条件
- **新增** 验证用户管理字段的数据类型和长度限制
- **新增** 验证pgvector扩展是否正确安装
- **新增** 检查向量索引创建是否成功
- 查询异常
- 核对服务层权限校验逻辑,确认 user_id 与查询归属一致
- 检查索引是否存在,必要时重建索引
- **新增** 验证confidence和match_type字段的数据类型和取值范围
- **新增** 检查用户管理字段的验证逻辑和过期时间
- **新增** 验证生命周期表的外键约束和级联删除
- **新增** 检查向量索引的HNSW配置和性能
- 导出失败
- 确认查询所有权校验通过
- 检查 CSV 写入逻辑与字符编码
- **新增** 验证新字段在导出过程中的处理逻辑
- **新增** 检查向量数据的序列化处理
- **新增** 认证功能故障
- 检查JWT密钥配置和令牌生成
- 验证验证码和重置令牌的有效性
- 确认邮箱验证流程的正确性
- **新增** 生命周期功能故障
- 检查项目阶段转换的业务规则
- 验证代理任务的调度和执行
- 确认内容版本控制的完整性
- **新增** 分析监控故障
- 检查发布记录的状态流转
- 验证指标数据的采集和存储
- 确认优化洞察的生成逻辑
- **新增** 告警系统故障
- 检查告警规则的配置和阈值
- 验证告警通知的发送机制
- 确认告警设置的用户偏好
- **新增** 知识库故障
- 检查向量嵌入的生成和存储
- 验证相似度搜索的准确性
- 确认文档去重和分块的处理
**更新** 新增针对所有新增功能的故障排查指导,包括向量检索和生命周期管理的专项排查。
**章节来源**
- [backend/alembic/env.py:33-88](file://backend/alembic/env.py#L33-L88)
- [backend/app/services/citation.py:14-22](file://backend/app/services/citation.py#L14-L22)
- [backend/app/services/auth.py:74-107](file://backend/app/services/auth.py#L74-L107)
## 结论
本数据库设计围绕用户、查询、引用记录、任务与订阅五大实体展开,采用 PostgreSQL + SQLAlchemy Async + Alembic 的成熟技术栈,具备良好的扩展性与可维护性。通过合理的索引策略、事务边界与服务层封装,能够满足日常查询、统计与导出需求。
**更新** 新增的完整业务生命周期、分析监控、告警系统、知识库等企业级功能架构,形成了从用户管理到智能代理的完整数据体系。新增的组织管理、项目阶段、代理系统、向量检索等功能显著增强了系统的业务能力和智能化水平。
**更新** 新增的7个迁移版本涵盖了从基础用户管理到高级AI功能的完整演进路径。建议在生产环境中进一步引入缓存与监控持续优化查询路径与索引覆盖特别是向量检索和复合查询的性能优化。
## 附录
- 部署与运维
- 使用 Docker Compose 启动数据库与应用,确保数据库健康检查通过后再启动应用
- 生产环境建议使用独立数据库实例与只读副本,配合连接池与慢查询日志
- **新增** 升级时确保迁移脚本按顺序执行,从初始版本到最新版本
- **新增** 配置JWT密钥和Redis缓存确保认证功能正常运行
- **新增** 部署pgvector扩展确保向量检索功能正常
- **新增** 配置向量数据库集群,支持大规模向量相似度搜索
- 备份与恢复
- 使用 pg_dump/pg_restore 进行逻辑备份与恢复
- 对关键表定期增量备份,结合 WAL 归档实现点-in-time 恢复
- **新增** 新字段变更需要纳入备份策略,确保数据完整性
- **新增** 用户管理字段包含敏感信息,需要特别注意备份安全
- **新增** 向量数据需要特殊备份策略确保embedding数据完整性
- 监控与告警
- 监控连接数、查询延迟、索引命中率与慢查询
- 对迁移脚本变更进行版本化管理与回滚演练
- **新增** 监控新字段的使用情况和性能影响
- **新增** 监控用户认证和验证功能的运行状态
- **新增** 监控代理任务的执行状态和性能
- **新增** 监控向量索引的查询性能和内存使用
- **新增** 监控知识库的检索准确性和响应时间
- 性能调优
- **新增** 向量检索性能调优HNSW索引参数优化、并发查询控制
- **新增** 复合查询性能调优:索引选择性分析、查询计划优化
- **新增** 分区表性能调优:分区策略选择、数据分布优化
- **新增** 缓存策略优化:热点数据识别、缓存失效策略
- 安全加固
- **新增** 向量数据加密存储敏感embedding数据保护
- **新增** 访问控制增强:基于组织的角色权限管理
- **新增** 审计日志完善:所有数据变更的审计追踪
**更新** 新增针对所有新增功能的部署和运维指导,包括向量数据库部署、性能调优和安全加固等专项内容。