Files
AIclinicalresearch/docs/00-系统总体设计/03-数据库架构说明.md
HaHafeng beb7f7f559 feat(asl): Implement full-text screening core LLM service and validation system (Day 1-3)
Core Components:
- PDFStorageService with Dify/OSS adapters
- LLM12FieldsService with Nougat-first + dual-model + 3-layer JSON parsing
- PromptBuilder for dynamic prompt assembly
- MedicalLogicValidator with 5 rules + fault tolerance
- EvidenceChainValidator for citation integrity
- ConflictDetectionService for dual-model comparison

Prompt Engineering:
- System Prompt (6601 chars, Section-Aware strategy)
- User Prompt template (PICOS context injection)
- JSON Schema (12 fields constraints)
- Cochrane standards (not loaded in MVP)

Key Innovations:
- 3-layer JSON parsing (JSON.parse + json-repair + code block extraction)
- Promise.allSettled for dual-model fault tolerance
- safeGetFieldValue for robust field extraction
- Mixed CN/EN token calculation

Integration Tests:
- integration-test.ts (full test)
- quick-test.ts (quick test)
- cached-result-test.ts (fault tolerance test)

Documentation Updates:
- Development record (Day 2-3 summary)
- Quality assurance strategy (full-text screening)
- Development plan (progress update)
- Module status (v1.1 update)
- Technical debt (10 new items)

Test Results:
- JSON parsing success rate: 100%
- Medical logic validation: 5/5 passed
- Dual-model parallel processing: OK
- Cost per PDF: CNY 0.10

Files: 238 changed, 14383 insertions(+), 32 deletions(-)
Docs: docs/03-涓氬姟妯″潡/ASL-AI鏅鸿兘鏂囩尞/05-寮€鍙戣褰?2025-11-22_Day2-Day3_LLM鏈嶅姟涓庨獙璇佺郴缁熷紑鍙?md
2025-11-22 22:21:12 +08:00

11 KiB
Raw Blame History

数据库架构说明

创建日期: 2025-11-06
文档目的: 澄清数据库部署方式和架构


📋 核心澄清

您有自己独立的PostgreSQL数据库

关键事实:

  1. PostgreSQL是通过Docker部署的docker-compose.yml
  2. 这是您项目的独立数据库不是Dify的
  3. Dify有自己完全独立的数据库dify/docker/目录下)
  4. 您不需要手动安装PostgreSQLDocker会自动创建

🐳 Docker部署详情

docker-compose.yml配置

# 位置AIclinicalresearch/docker-compose.yml

services:
  # PostgreSQL 数据库
  postgres:
    image: postgres:15-alpine        # 使用官方PostgreSQL镜像
    container_name: ai-clinical-postgres
    environment:
      POSTGRES_DB: ai_clinical_research    # 数据库名
      POSTGRES_USER: postgres              # 用户名
      POSTGRES_PASSWORD: postgres123       # 密码
    ports:
      - "5432:5432"                        # 端口映射
    volumes:
      - postgres_data:/var/lib/postgresql/data  # 数据持久化
    networks:
      - ai-clinical-network
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 5

  # Redis 缓存
  redis:
    image: redis:7-alpine
    container_name: ai-clinical-redis
    ports:
      - "6379:6379"
    volumes:
      - redis_data:/data
    networks:
      - ai-clinical-network

volumes:
  postgres_data:    # PostgreSQL数据卷数据持久化存储
  redis_data:       # Redis数据卷

🚀 启动流程

一键启动脚本(一键启动.bat

[步骤2/7] 启动PostgreSQL和Redis容器
docker-compose up -d

这个命令会:
1. 自动下载PostgreSQL 15镜像如果本地没有
2. 创建PostgreSQL容器
3. 创建Redis容器
4. 创建数据卷postgres_data用于持久化存储
5. 启动容器并在后台运行

您不需要手动安装PostgreSQL

  • Docker会自动创建和管理
  • 数据存储在Docker数据卷中不会丢失
  • 可以通过localhost:5432连接

🗄️ 数据库连接信息

连接配置

数据库连接字符串DATABASE_URL

postgresql://postgres:postgres123@localhost:5432/ai_clinical_research

拆解:

  • 协议: postgresql://
  • 用户名: postgres
  • 密码: postgres123
  • 主机: localhostDocker映射到本地
  • 端口: 5432
  • 数据库名: ai_clinical_research

后端配置backend/.env

# 数据库连接
DATABASE_URL=postgresql://postgres:postgres123@localhost:5432/ai_clinical_research

# 这个连接的是您自己的PostgreSQL不是Dify的

🔍 两个独立的数据库系统

系统对比

项目 您的数据库 Dify的数据库
位置 AIclinicalresearch/docker-compose.yml dify/docker/docker-compose.yml
容器名 ai-clinical-postgres dify-db(猜测)
端口 5432 可能是5433或不暴露
数据库名 ai_clinical_research dify
用途 存储您项目的业务数据 存储Dify的数据
访问方式 直接Prisma访问 通过Dify API访问

架构图

┌─────────────────────────────────────────────────────────┐
│                  AIclinicalresearch项目                   │
│                                                           │
│  ┌──────────────┐      ┌──────────────┐                │
│  │   Backend    │──────│  PostgreSQL  │                │
│  │  (Node.js)   │ SQL  │   (Docker)   │                │
│  │              │      │              │                │
│  │   Prisma     │      │ Port: 5432   │                │
│  └──────────────┘      └──────────────┘                │
│         │                                                │
│         │ HTTP API                                       │
│         ↓                                                │
│  ┌──────────────┐                                       │
│  │    Dify      │──────> Dify自己的PostgreSQL           │
│  │   (Docker)   │        (完全独立)                      │
│  └──────────────┘                                       │
│                                                           │
└─────────────────────────────────────────────────────────┘

📊 当前数据库表结构

您的PostgreSQL中的表

-- 来源backend/prisma/schema.prisma

-- 用户模块
users                   -- 用户表

-- 项目模块
projects                -- 项目表

-- AI问答模块
conversations           -- 对话表
messages                -- 消息表
general_conversations   -- 通用对话表
general_messages        -- 通用消息表

-- 知识库模块
knowledge_bases         -- 知识库表
documents               -- 文档表

-- 批处理模块Phase 3
batch_tasks             -- 批处理任务表
batch_results           -- 批处理结果表
task_templates          -- 任务模板表

-- 稿件审查模块
review_tasks            -- 稿件审查任务表

-- 运营管理模块
admin_logs              -- 管理员日志表

总计16张表全部在您自己的PostgreSQL中。


🔧 常用操作

查看Docker容器状态

# 查看所有容器
docker ps

# 应该能看到:
# ai-clinical-postgres    (PostgreSQL)
# ai-clinical-redis       (Redis)

连接到PostgreSQL

方法1使用Docker命令

# 进入PostgreSQL容器
docker exec -it ai-clinical-postgres psql -U postgres -d ai_clinical_research

# 然后可以执行SQL
\dt          # 查看所有表
\d users     # 查看users表结构
SELECT * FROM users LIMIT 10;

方法2使用数据库客户端

  • DBeaver / pgAdmin / DataGrip / Navicat
  • 连接信息:
    • Host: localhost
    • Port: 5432
    • Database: ai_clinical_research
    • User: postgres
    • Password: postgres123

停止和启动数据库

# 停止(但不删除数据)
docker-compose down

# 启动
docker-compose up -d

# 重启
docker-compose restart postgres

查看数据库日志

# 查看PostgreSQL日志
docker logs ai-clinical-postgres

# 实时查看日志
docker logs -f ai-clinical-postgres

💾 数据持久化

数据存储位置

数据卷Volume

postgres_data:/var/lib/postgresql/data

实际存储位置:

  • Windows: C:\ProgramData\Docker\volumes\aiclinicalresearch_postgres_data\_data
  • Mac/Linux: /var/lib/docker/volumes/aiclinicalresearch_postgres_data/_data

重要:

  • 即使删除容器(docker-compose down),数据不会丢失
  • 数据存储在Docker数据卷中持久化保存
  • ⚠️ 只有执行docker-compose down -v(删除数据卷)才会清空数据

备份数据库

# 备份导出SQL
docker exec ai-clinical-postgres pg_dump -U postgres ai_clinical_research > backup.sql

# 恢复导入SQL
docker exec -i ai-clinical-postgres psql -U postgres ai_clinical_research < backup.sql

🎯 未来Schema隔离计划

当前状态

-- 所有表都在public schema
public.users
public.projects
public.conversations
public.knowledge_bases
public.documents
public.review_tasks
...

目标架构Schema隔离

-- 平台层Schema
CREATE SCHEMA platform_schema;
platform_schema.users
platform_schema.roles
platform_schema.permissions

-- 业务模块Schema
CREATE SCHEMA aia_schema;        -- AI智能问答
aia_schema.projects
aia_schema.conversations
aia_schema.messages

CREATE SCHEMA pkb_schema;        -- 个人知识库
pkb_schema.knowledge_bases
pkb_schema.documents

CREATE SCHEMA asl_schema;        -- AI智能文献
asl_schema.projects
asl_schema.literature_items
asl_schema.screening_results

CREATE SCHEMA review_schema;     -- 稿件审查
review_schema.review_tasks
review_schema.review_journals

实施计划:

  • 阶段一(立即): 逻辑隔离,使用表名前缀(aia_projects, asl_projects
  • 阶段二(微服务拆分时): 物理隔离创建真正的Schema

🔍 Dify数据库独立系统

Dify的部署

dify/docker/docker-compose.yml
  ├── dify-db (PostgreSQL)
  ├── dify-redis
  ├── dify-web
  ├── dify-api
  └── ...

关键点:

  • Dify有自己完全独立的docker-compose.yml
  • Dify的PostgreSQL是独立的容器
  • 您的项目不直接访问Dify的数据库
  • 通过Dify APIHTTP REST调用Dify功能

您的项目如何使用Dify

// 不是直接访问Dify数据库而是通过API

// 创建知识库
const response = await fetch('http://localhost/v1/datasets', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${DIFY_API_KEY}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: '我的知识库'
  })
});

// 上传文档
const formData = new FormData();
formData.append('file', file);
await fetch(`http://localhost/v1/datasets/${datasetId}/document/create-by-file`, {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${DIFY_API_KEY}`
  },
  body: formData
});

您的数据库中存储:

-- knowledge_bases表
{
  id: 'uuid',
  name: '我的知识库',
  dify_dataset_id: 'xxx'  -- 关联Dify的dataset_id
}

🎯 总结

核心要点

  1. 您有自己的PostgreSQL数据库

    • 通过Docker部署docker-compose.yml
    • 容器名:ai-clinical-postgres
    • 数据库名:ai_clinical_research
  2. 您不需要手动安装PostgreSQL

    • docker-compose up -d会自动创建
    • 数据持久化存储在Docker数据卷中
  3. Dify是完全独立的系统

    • 有自己的PostgreSQL数据库
    • 您通过Dify API访问不直接访问数据库
  4. 当前16张表全部在您的PostgreSQL中

    • 用户、项目、对话、知识库、文档、批处理、稿件审查等
    • 全部在public schema未来需要隔离

为什么您不记得安装PostgreSQL

因为您根本没有手动安装! 😊

  • Docker自动下载镜像
  • Docker自动创建容器
  • 一键启动脚本自动启动
  • 您只需要运行一键启动.bat

这就是Docker的魔力


需要进一步了解的内容:

  1. 如何备份和恢复数据库?
  2. 如何迁移到Schema隔离架构
  3. 如何连接数据库进行手动查询?
  4. Prisma如何管理数据库迁移