Spaces:
Paused

File size: 2,467 Bytes
b7980f7
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from sqlalchemy import Column, String, Text, ForeignKey, DateTime, Boolean, Index, Computed
from sqlalchemy.dialects.postgresql import UUID, TSVECTOR
from sqlalchemy.orm import relationship, backref
from pgvector.sqlalchemy import Vector
from core.database import Base
from core.config import get_settings
from models.base import PrimaryKeyMixin, TimestampMixin, SoftDeleteMixin

settings = get_settings()

class KBArticle(Base, PrimaryKeyMixin, TimestampMixin, SoftDeleteMixin):
    __tablename__ = "kb_articles"

    workspace_id = Column(UUID(as_uuid=True), ForeignKey("workspaces.id"), nullable=False, index=True)
    author_id = Column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
    project_id = Column(UUID(as_uuid=True), ForeignKey("projects.id"), nullable=True)

    title = Column(String(500), nullable=False)
    content = Column(Text, nullable=False)
    category = Column(String(100), nullable=True)
    is_published = Column(Boolean, default=True)
    summary = Column(Text, nullable=True)
    duplicate_of_id = Column(UUID(as_uuid=True), ForeignKey("kb_articles.id"), nullable=True, index=True)
    force_original = Column(Boolean, default=False, index=True)
    
    # Semantic vector for RAG
    embedding = Column(Vector(settings.AI_EMBEDDING_DIM), nullable=True)
    
    # --- Search Optimization ---
    # 1. Computed TSVector for GIN search (Keyword Engine)
    search_vector = Column(
        TSVECTOR, 
        Computed("to_tsvector('english', coalesce(title, '') || ' ' || coalesce(content, ''))", persisted=True)
    )
    
    # 2. Indexes for hybrid search
    __table_args__ = (
        Index('idx_kb_search_vector', "search_vector", postgresql_using='gin'),
        Index(
            'idx_kb_embedding_hnsw', 
            "embedding", 
            postgresql_using='hnsw', 
            postgresql_with={'m': 16, 'ef_construction': 64}, 
            postgresql_ops={'embedding': 'vector_cosine_ops'}
        ),
    )

    # Relationships
    workspace = relationship("Workspace")
    author = relationship("User")
    project = relationship("Project", back_populates="kb_articles")
    chunks = relationship("KBArticleChunk", back_populates="article", cascade="all, delete-orphan")
    attachments = relationship("Attachment", back_populates="article", cascade="all, delete-orphan")
    
    # Self-referential for duplicates
    duplicate_of = relationship("KBArticle", remote_side="KBArticle.id", backref="duplicates")