后端: - alembic 0009: 两张固化表 + GIN prefix_keys 索引 + articles trigger - /api/v1/search/suggestions: 混合 A(高频词 ts_stat) + B(真实标题) + 冷启动 fallback - worker 每日 03:00 + 启动时刷新 search_keywords - 顺便填 commit 11 TODO: articles.title_zh_tsv + GIN 索引(未来 FTS 基础) 前端: - NInput -> NAutoComplete + debounce 250ms - 选标题 -> 跳详情;选关键词 -> 填入 + 触发搜索 - AbortController 防 race condition 性能: prefix_keys @> ARRAY[prefix] 走 GIN 亚毫秒,100w 行也稳
44 lines
1.6 KiB
Python
44 lines
1.6 KiB
Python
"""搜索建议 - 真实文章标题片段表(articles 写入 trigger 自动维护)。
|
|
|
|
- 数据源:articles.title_zh(优先)/ articles.title(短新闻回退)
|
|
- 用途:/api/v1/search/suggestions 返回"真实文章标题"建议(B 方案)
|
|
- 维护:PG trigger(articles INSERT/UPDATE OF title_zh/title/published_at 触发)
|
|
- 查询:prefix_keys @> ARRAY['美'] 走 GIN 索引,按 published_at DESC 排序
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
|
|
from sqlalchemy import BigInteger, DateTime, ForeignKey, String, func
|
|
from sqlalchemy.dialects.postgresql import ARRAY, TEXT
|
|
from sqlalchemy.orm import Mapped, mapped_column
|
|
|
|
from app.database import Base
|
|
|
|
|
|
class SearchTitleSuggestion(Base):
|
|
__tablename__ = "search_title_suggestions"
|
|
|
|
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
|
|
|
article_id: Mapped[int] = mapped_column(
|
|
BigInteger,
|
|
ForeignKey("articles.id", ondelete="CASCADE"),
|
|
nullable=False,
|
|
)
|
|
|
|
# 该条用的是哪边的文本:'zh' (title_zh) / 'src' (title 短新闻回退)
|
|
title_lang: Mapped[str] = mapped_column(String(8), nullable=False, default="zh")
|
|
|
|
# 预计算前缀数组(从第 1 字到全词)
|
|
prefix_keys: Mapped[list[str]] = mapped_column(ARRAY(TEXT), nullable=False)
|
|
|
|
published_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
|
|
|
created_at: Mapped[datetime] = mapped_column(
|
|
DateTime(timezone=True), server_default=func.now(), nullable=False
|
|
)
|
|
|
|
def __repr__(self) -> str:
|
|
return f"<SearchTitleSuggestion article_id={self.article_id} lang={self.title_lang}>"
|