perf: /history 消除题材查询 N+1 并修正排序注释
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -52,7 +52,7 @@ async def active_core_stocks():
|
|||||||
s["lastAppear"] = r["trade_date"]
|
s["lastAppear"] = r["trade_date"]
|
||||||
|
|
||||||
stocks = list(stock_days.values())
|
stocks = list(stock_days.values())
|
||||||
# 稳定排序:先按最近上榜日降序,再按出现次数降序
|
# 稳定排序:先按出现次数降序,再按最近上榜日降序
|
||||||
stocks.sort(key=lambda x: x.get("lastAppear") or "", reverse=True)
|
stocks.sort(key=lambda x: x.get("lastAppear") or "", reverse=True)
|
||||||
stocks.sort(key=lambda x: -x["appearCount"])
|
stocks.sort(key=lambda x: -x["appearCount"])
|
||||||
return JSONResponse({"dates": dates, "stocks": stocks}, headers=_NO_CACHE_HEADERS)
|
return JSONResponse({"dates": dates, "stocks": stocks}, headers=_NO_CACHE_HEADERS)
|
||||||
@@ -67,14 +67,20 @@ async def core_stock_history(date: str = Query(..., description="交易日 YYYY-
|
|||||||
rows = conn.execute(
|
rows = conn.execute(
|
||||||
"SELECT * FROM daily_core_stocks WHERE trade_date = ? ORDER BY rank ASC", (date,)
|
"SELECT * FROM daily_core_stocks WHERE trade_date = ? ORDER BY rank ASC", (date,)
|
||||||
).fetchall()
|
).fetchall()
|
||||||
|
# 一次性取该日全部题材关联,按 stock_code 分组,避免逐股 N+1 查询
|
||||||
|
themes_rows = conn.execute(
|
||||||
|
"SELECT stock_code, theme_code, theme_name FROM daily_core_stock_themes WHERE trade_date = ?",
|
||||||
|
(date,),
|
||||||
|
).fetchall()
|
||||||
|
themes_by_stock: dict[str, list] = {}
|
||||||
|
for t in themes_rows:
|
||||||
|
themes_by_stock.setdefault(t["stock_code"], []).append(
|
||||||
|
{"theme_code": t["theme_code"], "theme_name": t["theme_name"]}
|
||||||
|
)
|
||||||
items = []
|
items = []
|
||||||
for r in rows:
|
for r in rows:
|
||||||
d = dict_from_row(r)
|
d = dict_from_row(r)
|
||||||
themes = conn.execute(
|
d["themes"] = themes_by_stock.get(d["stock_code"], [])
|
||||||
"SELECT theme_code, theme_name FROM daily_core_stock_themes WHERE trade_date = ? AND stock_code = ?",
|
|
||||||
(date, d["stock_code"]),
|
|
||||||
).fetchall()
|
|
||||||
d["themes"] = [dict(t) for t in themes]
|
|
||||||
items.append(d)
|
items.append(d)
|
||||||
return JSONResponse({"date": date, "items": items}, headers=_NO_CACHE_HEADERS)
|
return JSONResponse({"date": date, "items": items}, headers=_NO_CACHE_HEADERS)
|
||||||
finally:
|
finally:
|
||||||
|
|||||||
Reference in New Issue
Block a user