feat: 工参属性全部由 OpenCode 同一条 SQL 导出;即席查询表没有时间列时不加时间条件
即席查询的 4G/5G 小区工参表没有日期列、4G 只有当前记录,取不到历史日工参,工参不再走即席查询。即席查询的表配置写了 time_field 而表里没有这一列时,按页面做法不带时间条件。
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
"""评估用的 4G/5G 小区工参:按地市、日期整份保存,任务先查库,没有再去大数据平台取。
|
||||
|
||||
一份快照 = 即席查询当天的工参(经纬度是脱敏的)+ OpenCode 导出的当天 CGI 与经纬度,按 CGI 合并,
|
||||
OpenCode 里没有坐标的小区经纬度留空。即席查询取不到,或者它给的 CGI 和 OpenCode 那份对不上时,
|
||||
改由 OpenCode 把属性列一起导出。OpenCode 那份按 eff_from_date/eff_to_date 取当天有效的记录,是日期口径的基准。
|
||||
一份快照由 OpenCode 在一条提示词里导出:全市当天有效(eff_from_date <= 当天 < eff_to_date)的 4G、5G 工参,
|
||||
CGI、经纬度和属性在同一条 SQL 里,没有有效坐标的小区经纬度留空。
|
||||
即席查询的工参表没有日期列,4G 只有当前记录,取不到历史日,所以工参不走即席查询。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,14 +20,12 @@ from sqlalchemy.engine import Engine
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.models import CellData4G, CellData5G, GongcanSnapshot, utcnow
|
||||
from app.nqi import adhoc
|
||||
from app.nqi.client import NqiClient, NqiError
|
||||
from app.nqi.client import NqiClient
|
||||
from app.nqi.opencode import EFFECTIVE, ExportFile, OpenCode, snapshot_where, task_session
|
||||
|
||||
logger = logging.getLogger("decom")
|
||||
|
||||
TECHS = ("4G", "5G")
|
||||
ADHOC_TABLES = {"4G": "appdbv3.v_a_common_cfg_lte_cellant_d", "5G": "appdbv3.a_common_cfg_nr_cellant_d"}
|
||||
PLATFORM_TABLES = {"4G": "appdbv3.a_common_cfg_lte_cellant_d", "5G": "appdbv3.a_common_cfg_nr_cellant_d"}
|
||||
KEYS = {"4G": ("cgi",), "5G": ("ncgi", "cgi")}
|
||||
KEY_COLUMN = {"4G": "cgi", "5G": "ncgi"}
|
||||
@@ -38,7 +36,6 @@ ATTRIBUTES = {
|
||||
}
|
||||
CELL_TABLES = {"4G": CellData4G.__table__, "5G": CellData5G.__table__}
|
||||
COORDS = ("longitude", "latitude")
|
||||
MATCH_RATIO = 0.98
|
||||
FAILED_COOLDOWN = timedelta(minutes=10)
|
||||
STALE_LOADING = timedelta(minutes=40)
|
||||
|
||||
@@ -67,30 +64,19 @@ class Target:
|
||||
return f"站点 {self.site}" if self.site else f"小区 {'、'.join(self.cgis)}"
|
||||
|
||||
|
||||
def attribute_columns(tech: str) -> tuple[str, ...]:
|
||||
return ATTRIBUTES[tech]
|
||||
|
||||
|
||||
def adhoc_fields(tech: str) -> tuple[str, ...]:
|
||||
return KEYS[tech] + attribute_columns(tech)
|
||||
|
||||
|
||||
def snapshot_task_name(city: str, day: date) -> str:
|
||||
"""OpenCode 目录名不带日期样式的数字,平台的脱敏会把它当日期改掉。"""
|
||||
return "gc_" + hashlib.sha1(f"{city}|{day.isoformat()}".encode("utf-8")).hexdigest()[:12]
|
||||
|
||||
|
||||
def platform_files(task: str, city: str, day: date, *, attributes: bool) -> list[ExportFile]:
|
||||
"""全市当天有效的工参。只要坐标时三四列;要属性时文字列把英文逗号换成中文逗号,避免 CSV 错列。"""
|
||||
def platform_files(task: str, city: str, day: date) -> list[ExportFile]:
|
||||
"""全市当天有效的工参。文字列把英文逗号换成中文逗号,避免 CSV 错列。"""
|
||||
files = []
|
||||
for tech, name in (("4G", "lte"), ("5G", "nr")):
|
||||
columns = KEYS[tech] + COORDS + EFFECTIVE
|
||||
select_list = list(columns)
|
||||
if attributes:
|
||||
columns += attribute_columns(tech)
|
||||
select_list += [f"replace({column}::text, ',', ',') as {column}" for column in attribute_columns(tech)]
|
||||
plain = KEYS[tech] + COORDS + EFFECTIVE
|
||||
select_list = list(plain) + [f"replace({column}::text, ',', ',') as {column}" for column in ATTRIBUTES[tech]]
|
||||
sql = f"select {', '.join(select_list)} from {PLATFORM_TABLES[tech]} where {snapshot_where(city, day)}"
|
||||
files.append(ExportFile(task, "attr" if attributes else "xy", f"{name}.csv", sql, day, columns))
|
||||
files.append(ExportFile(task, "gc", f"{name}.csv", sql, day, plain + ATTRIBUTES[tech]))
|
||||
return files
|
||||
|
||||
|
||||
@@ -125,11 +111,11 @@ def coordinates(rows: list[dict], tech: str) -> dict[str, tuple[float, float]]:
|
||||
return found
|
||||
|
||||
|
||||
def build_cells(attr_rows: list[dict], coord_rows: list[dict], tech: str) -> list[dict]:
|
||||
"""按 CellData_4G / CellData_5G 的列名组成一行一个小区。"""
|
||||
coords = coordinates(coord_rows, tech)
|
||||
def build_cells(rows: list[dict], tech: str) -> list[dict]:
|
||||
"""按 CellData_4G / CellData_5G 的列名组成一行一个小区,属性取该 CGI 的第一行。"""
|
||||
coords = coordinates(rows, tech)
|
||||
cells: dict[str, dict] = {}
|
||||
for row in attr_rows:
|
||||
for row in rows:
|
||||
key = key_of(row, tech)
|
||||
if not key or key in cells:
|
||||
continue
|
||||
@@ -158,42 +144,16 @@ def unified(row, tech: str) -> dict:
|
||||
return item
|
||||
|
||||
|
||||
def key_overlap(attr_rows: list[dict], coord_rows: list[dict], tech: str) -> float:
|
||||
left = {key_of(row, tech) for row in attr_rows} - {""}
|
||||
right = {key_of(row, tech) for row in coord_rows} - {""}
|
||||
if not left or not right:
|
||||
return 0.0
|
||||
return len(left & right) / len(left | right)
|
||||
|
||||
|
||||
async def fetch_snapshot(nqi: NqiClient, oc: OpenCode, city: str, day: date, *, use_adhoc: bool = True) -> tuple[dict[str, list[dict]], str]:
|
||||
"""从大数据平台取一份快照,返回按制式分开的小区行和属性来源(adhoc / opencode)。"""
|
||||
attrs: dict[str, list[dict]] | None = None
|
||||
if use_adhoc:
|
||||
try:
|
||||
attrs = {tech: await adhoc.export_day(nqi, ADHOC_TABLES[tech], day, city, adhoc_fields(tech)) for tech in TECHS}
|
||||
except NqiError as exc:
|
||||
logger.info("即席查询取 %s %s 工参未成功,改由 OpenCode 导出属性: %s", city, day, exc)
|
||||
attrs = None
|
||||
async def fetch_snapshot(oc: OpenCode, city: str, day: date) -> dict[str, list[dict]]:
|
||||
"""从大数据平台取一份快照,返回按制式分开的小区行。"""
|
||||
task = snapshot_task_name(city, day)
|
||||
async with task_session(oc, task) as session_id:
|
||||
files = platform_files(task, city, day, attributes=attrs is None)
|
||||
files = platform_files(task, city, day)
|
||||
tables = await oc.export(session_id, files)
|
||||
rows = {tech: tables[item.key].rows for tech, item in zip(TECHS, files)}
|
||||
if attrs is not None:
|
||||
ratios = {tech: key_overlap(attrs[tech], rows[tech], tech) for tech in TECHS}
|
||||
if min(ratios.values()) < MATCH_RATIO:
|
||||
logger.info("即席查询的 CGI 与 OpenCode 当天快照重合 %s,改用 OpenCode 的属性", ratios)
|
||||
attrs = None
|
||||
files = platform_files(task, city, day, attributes=True)
|
||||
tables = await oc.export(session_id, files)
|
||||
rows = {tech: tables[item.key].rows for tech, item in zip(TECHS, files)}
|
||||
source = "adhoc" if attrs is not None else "opencode"
|
||||
attrs = attrs if attrs is not None else rows
|
||||
cells = {tech: build_cells(attrs[tech], rows[tech], tech) for tech in TECHS}
|
||||
cells = {tech: build_cells(tables[item.key].rows, tech) for tech, item in zip(TECHS, files)}
|
||||
if not all(cells.values()):
|
||||
raise GongcanError(f"{city} {day} 的工参是空的")
|
||||
return cells, source
|
||||
return cells
|
||||
|
||||
|
||||
_SNAPSHOT = GongcanSnapshot.__table__
|
||||
@@ -230,7 +190,7 @@ def claim_snapshot(engine: Engine, city: str, day: date, now: datetime) -> int |
|
||||
return int(row.id) if taken.rowcount == 1 else None
|
||||
|
||||
|
||||
def save_snapshot(engine: Engine, snapshot_id: int, cells: dict[str, list[dict]], source: str, now: datetime) -> None:
|
||||
def save_snapshot(engine: Engine, snapshot_id: int, cells: dict[str, list[dict]], now: datetime) -> None:
|
||||
with engine.begin() as connection:
|
||||
for tech, table in CELL_TABLES.items():
|
||||
rows = cells.get(tech) or []
|
||||
@@ -242,7 +202,7 @@ def save_snapshot(engine: Engine, snapshot_id: int, cells: dict[str, list[dict]]
|
||||
.where(_SNAPSHOT.c.id == snapshot_id)
|
||||
.values(
|
||||
status="ready",
|
||||
attr_source=source,
|
||||
attr_source="opencode",
|
||||
lte_cells=len(cells.get("4G") or []),
|
||||
nr_cells=len(cells.get("5G") or []),
|
||||
located_cells=sum(1 for rows in cells.values() for row in rows if row["latitude"] is not None),
|
||||
@@ -275,7 +235,7 @@ class GongcanStore:
|
||||
def __init__(
|
||||
self,
|
||||
engine: Engine,
|
||||
loader: Callable[[str, date], Awaitable[tuple[dict[str, list[dict]], str]]],
|
||||
loader: Callable[[str, date], Awaitable[dict[str, list[dict]]]],
|
||||
*,
|
||||
poll_seconds: float = 10.0,
|
||||
wait_timeout: timedelta = timedelta(minutes=45),
|
||||
@@ -338,19 +298,19 @@ class GongcanStore:
|
||||
|
||||
async def _load(self, snapshot_id: int, city: str, day: date) -> None:
|
||||
try:
|
||||
cells, source = await self.loader(city, day)
|
||||
save_snapshot(self.engine, snapshot_id, cells, source, self.clock())
|
||||
cells = await self.loader(city, day)
|
||||
save_snapshot(self.engine, snapshot_id, cells, self.clock())
|
||||
except BaseException as exc:
|
||||
fail_snapshot(self.engine, snapshot_id, f"{type(exc).__name__}: {exc}", self.clock())
|
||||
raise
|
||||
logger.info("工参快照 %s %s 已入库:4G %s 个、5G %s 个小区,属性来自 %s", city, day, len(cells.get("4G") or []), len(cells.get("5G") or []), source)
|
||||
logger.info("工参快照 %s %s 已入库:4G %s 个、5G %s 个小区", city, day, len(cells.get("4G") or []), len(cells.get("5G") or []))
|
||||
|
||||
|
||||
def platform_loader(nqi: NqiClient, *, use_adhoc: bool = True) -> Callable[[str, date], Awaitable[tuple[dict[str, list[dict]], str]]]:
|
||||
def platform_loader(nqi: NqiClient) -> Callable[[str, date], Awaitable[dict[str, list[dict]]]]:
|
||||
oc = OpenCode(nqi)
|
||||
|
||||
async def load(city: str, day: date) -> tuple[dict[str, list[dict]], str]:
|
||||
return await fetch_snapshot(nqi, oc, city, day, use_adhoc=use_adhoc)
|
||||
async def load(city: str, day: date) -> dict[str, list[dict]]:
|
||||
return await fetch_snapshot(oc, city, day)
|
||||
|
||||
return load
|
||||
|
||||
|
||||
+14
-81
@@ -2,9 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
from datetime import date, datetime, timedelta
|
||||
from urllib.parse import urlencode
|
||||
|
||||
@@ -145,7 +143,7 @@ async def export_table(
|
||||
if not columns:
|
||||
raise NqiError("这张表没有可导出的字段")
|
||||
title = str(columns[0].get("tablename_cn") or tablename)
|
||||
where = _where(columns[0], start, end, city)
|
||||
where = _where(columns[0], start, end, city, timed=_has_time_column(columns))
|
||||
common = {
|
||||
"geographicdimension": columns[0].get("geographicdimension") or "",
|
||||
"timedimension": columns[0].get("timedimension") or "",
|
||||
@@ -191,79 +189,6 @@ async def export_table(
|
||||
return title, columns, rows
|
||||
|
||||
|
||||
async def export_day(
|
||||
client: NqiClient,
|
||||
tablename: str,
|
||||
day: date,
|
||||
city: str,
|
||||
fields: tuple[str, ...],
|
||||
*,
|
||||
page_size: int = PAGE_SIZE,
|
||||
pause_seconds: float = 0.3,
|
||||
) -> list[dict]:
|
||||
"""取一张表某一天、某个地市的指定几列。
|
||||
|
||||
维度有多个可选值时(如“小区,网格,地市,分公司”“天粒度”),按页面默认取第一个并去掉“粒度”。
|
||||
翻页按实际返回的行数推进,平台把每页压到更少时也不会漏行;取不全就报错。
|
||||
"""
|
||||
await ensure_session(client)
|
||||
columns = await _columns(client, tablename)
|
||||
selected = [column for column in columns if column.get("columnname") in fields]
|
||||
missing = set(fields) - {str(column.get("columnname")) for column in selected}
|
||||
if missing:
|
||||
raise NqiError(f"{tablename} 缺少字段:{'、'.join(sorted(missing))}")
|
||||
head = columns[0]
|
||||
common = {
|
||||
"geographicdimension": _first_choice(head.get("geographicdimension")),
|
||||
"timedimension": _first_choice(head.get("timedimension")).removesuffix("粒度"),
|
||||
"enodebField": head.get("enodeb_field") or "",
|
||||
"cgiField": head.get("cgi_field") or "",
|
||||
"timeField": head.get("time_field") or "starttime",
|
||||
"cellField": head.get("cell_field") or "",
|
||||
"cityField": head.get("city_field") or "city",
|
||||
"result": _result_json(head, selected),
|
||||
"where": json.dumps(_where(head, _start(day), _end(day), city), ensure_ascii=False),
|
||||
}
|
||||
total, index_count = await _count(client, common)
|
||||
rows: list[dict] = []
|
||||
pages = 0
|
||||
while len(rows) < total:
|
||||
pages += 1
|
||||
if pages > MAX_PAGES:
|
||||
raise NqiError("数据行数超出单次导出上限")
|
||||
page = await _post_json(
|
||||
client,
|
||||
f"{PAGE}/getTable",
|
||||
{
|
||||
**common,
|
||||
**_column_form(selected),
|
||||
"draw": pages,
|
||||
"start": len(rows),
|
||||
"length": page_size,
|
||||
"indexcount": index_count,
|
||||
"total": total,
|
||||
"order[0][column]": 0,
|
||||
"order[0][dir]": "desc",
|
||||
"search[value]": "",
|
||||
"search[regex]": "false",
|
||||
},
|
||||
)
|
||||
data = page.get("data") if isinstance(page, dict) else None
|
||||
batch = [item for item in data if isinstance(item, dict)] if isinstance(data, list) else []
|
||||
if not batch:
|
||||
break
|
||||
rows.extend(batch)
|
||||
if pause_seconds:
|
||||
await asyncio.sleep(pause_seconds)
|
||||
if len(rows) < total:
|
||||
raise NqiError(f"{tablename} 只取到 {len(rows)} 行,应有 {total} 行")
|
||||
return rows
|
||||
|
||||
|
||||
def _first_choice(value: object) -> str:
|
||||
return re.split(r"[,,.、]", str(value or ""))[0].strip()
|
||||
|
||||
|
||||
async def _count(client: NqiClient, common: dict) -> tuple[int, str]:
|
||||
"""平台出错时返回 {"stat":"0"},没有 count。不能当成 0 行。页面第一次计数总是带 indexcount=0,缺了会报错。"""
|
||||
counted = await _post_json(client, f"{PAGE}/getTableCount", {**common, "indexcount": "0"})
|
||||
@@ -302,12 +227,20 @@ def _field(column: dict) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _where(column: dict, start: datetime, end: datetime, city: str) -> list[dict]:
|
||||
def _has_time_column(columns: list[dict]) -> bool:
|
||||
"""工参这类表的配置写了 time_field,表里却没有这一列;页面这时不带时间条件,带了服务端不执行。"""
|
||||
time_field = str(columns[0].get("time_field") or "starttime") if columns else ""
|
||||
return any(column.get("columnname") == time_field for column in columns)
|
||||
|
||||
|
||||
def _where(column: dict, start: datetime, end: datetime, city: str, *, timed: bool = True) -> list[dict]:
|
||||
time_field = str(column.get("time_field") or "starttime")
|
||||
conditions = [
|
||||
{"datatype": "timestamp", "feild": time_field, "feildName": "", "symbol": ">=", "val": _stamp(start), "whereCon": "and", "query": True},
|
||||
{"datatype": "timestamp", "feild": time_field, "feildName": "", "symbol": "<", "val": _stamp(end), "whereCon": "and", "query": True},
|
||||
]
|
||||
conditions = []
|
||||
if timed:
|
||||
conditions += [
|
||||
{"datatype": "timestamp", "feild": time_field, "feildName": "", "symbol": ">=", "val": _stamp(start), "whereCon": "and", "query": True},
|
||||
{"datatype": "timestamp", "feild": time_field, "feildName": "", "symbol": "<", "val": _stamp(end), "whereCon": "and", "query": True},
|
||||
]
|
||||
city_name = city.strip()
|
||||
if city_name:
|
||||
conditions.append(
|
||||
|
||||
Reference in New Issue
Block a user