Spaces:
3SCError404
/
Paused

nexus / models /kb_article.py
dushyantsingh0
backend stabilization
4405ca9
Raw History Blame Contribute Delete
2.45 kB
from sqlalchemy import Column, String, Text, ForeignKey, Boolean, Index, Computed
from sqlalchemy.dialects.postgresql import UUID, TSVECTOR
from sqlalchemy.orm import relationship
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")