feat: 工参属性全部由 OpenCode 同一条 SQL 导出;即席查询表没有时间列时不加时间条件

即席查询的 4G/5G 小区工参表没有日期列、4G 只有当前记录,取不到历史日工参,工参不再走即席查询。即席查询的表配置写了 time_field 而表里没有这一列时,按页面做法不带时间条件。
This commit is contained in:
2026-11-11 03:02:05 +08:00
parent 33d132d7b6
commit 688441f4a7
5 changed files with 101 additions and 230 deletions
+27 -67
View File
@@ -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
View File
@@ -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(
+15
View File
@@ -1,5 +1,6 @@
import asyncio
import json
from datetime import date
import pytest
@@ -27,6 +28,20 @@ def test_result_json_carries_table_params_like_the_page():
assert payload["result"][0]["feild"] == "cgi" and payload["result"][0]["table"] == HEAD["tablename"]
def test_where_skips_time_when_table_has_no_time_column():
gongcan = [{**HEAD, "time_field": "starttime", "city_field": "city"}, {**HEAD, "columnname": "cell_name"}]
kpi = [{**HEAD, "columnname": "starttime", "time_field": "starttime"}, {**HEAD, "columnname": "cgi"}]
assert not adhoc._has_time_column(gongcan) and adhoc._has_time_column(kpi)
start, end = adhoc.time_window("prev_day", 1, date(2026, 11, 11))
assert [item["feild"] for item in adhoc._where(gongcan[0], start, end, "江门", timed=False)] == ["city"]
timed = adhoc._where(kpi[0], start, end, "江门")
assert [(item["feild"], item["symbol"], item["val"]) for item in timed] == [
("starttime", ">=", "2026-11-10 00:00:00"),
("starttime", "<", "2026-11-10 23:59:59"),
("city", "in", "江门"),
]
def test_count_sends_indexcount_and_rejects_error_payload(monkeypatch):
sent = []
replies = [{"count": 37604, "indexcount": "0"}, {"stat": "0", "message": "null"}, {}]
+28 -61
View File
@@ -15,7 +15,6 @@ from app.collect.gongcan import (
build_cells,
claim_snapshot,
fetch_snapshot,
key_overlap,
month_start,
nearest_sites,
pick_after,
@@ -26,7 +25,6 @@ from app.collect.gongcan import (
target_center,
)
from app.models import Base, CellData4G, CellData5G, GongcanSnapshot
from app.nqi.client import NqiError
from app.nqi.opencode import CsvTable, OpenCode
CITY = "江门"
@@ -73,7 +71,7 @@ class Platform:
await asyncio.sleep(self.delay)
if day not in self.days:
raise GongcanError("平台没有这一天")
return self.days[day], "opencode"
return self.days[day]
def make_store(platform, stored=None, clock=None):
@@ -82,7 +80,7 @@ def make_store(platform, stored=None, clock=None):
clock = clock or Clock()
for day, cells in (stored or {}).items():
snapshot_id = claim_snapshot(db, CITY, day, clock())
save_snapshot(db, snapshot_id, cells, "adhoc", clock())
save_snapshot(db, snapshot_id, cells, clock())
return GongcanStore(db, platform, poll_seconds=0.01, clock=clock)
@@ -95,44 +93,34 @@ def test_month_start_crosses_year():
def test_platform_files_use_make_date_and_keep_commas_out_of_text_columns():
task = snapshot_task_name(CITY, date(2026, 11, 1))
assert re.fullmatch(r"gc_[0-9a-f]{12}", task) and task != snapshot_task_name(CITY, date(2026, 10, 1))
lte, nr = platform_files(task, CITY, date(2026, 11, 1), attributes=False)
assert lte.sql.startswith("select cgi, longitude, latitude, eff_from_date, eff_to_date from appdbv3.a_common_cfg_lte_cellant_d where city = '江门'")
lte, nr = platform_files(task, CITY, date(2026, 11, 1))
assert lte.sql.startswith("select cgi, longitude, latitude, eff_from_date, eff_to_date, replace(cell_name::text, ',', ',') as cell_name")
assert lte.sql.endswith("from appdbv3.a_common_cfg_lte_cellant_d where city = '江门' and eff_from_date <= make_date(2026, 11, 1) and eff_to_date > make_date(2026, 11, 1)")
assert nr.sql.startswith("select ncgi, cgi, longitude, latitude,")
assert "make_date(2026, 11, 1)" in lte.sql and not re.search(r"\d{4}-\d{2}-\d{2}", lte.sql + nr.sql)
assert (lte.phase, lte.key, nr.key) == ("xy", "xy/lte", "xy/nr")
lte_attr, nr_attr = platform_files(task, CITY, date(2026, 11, 1), attributes=True)
assert "replace(station_name::text, ',', ',') as station_name" in lte_attr.sql
assert "replace(gnodeb_name::text, ',', ',') as gnodeb_name" in nr_attr.sql
assert {"station_name", "enodeb_id", "azimuth"} <= set(lte_attr.required) and lte_attr.phase == "attr"
assert "replace(gnodeb_name::text, ',', ',') as gnodeb_name" in nr.sql
assert not re.search(r"\d{4}-\d{2}-\d{2}", lte.sql + nr.sql)
assert (lte.phase, lte.key, nr.key) == ("gc", "gc/lte", "gc/nr")
assert {"cgi", "latitude", "station_name", "enodeb_id", "azimuth"} <= set(lte.required)
assert {"ncgi", "nrcell_name", "gnodeb_id"} <= set(nr.required)
def test_build_cells_merges_coordinates_by_cgi():
attrs = [
{"cgi": "c1", "cell_name": "A", "station_name": "S1", "enodeb_id": "1", "network_type": "LTE"},
{"cgi": "c1", "cell_name": "A-dup", "station_name": "S1"},
{"cgi": "c2", "cell_name": "B", "station_name": "S2"},
def test_build_cells_merges_antenna_rows_by_cgi():
rows = [
{"cgi": "c1", "cell_name": "A", "station_name": "S1", "enodeb_id": "1", "network_type": "LTE", "longitude": "", "latitude": ""},
{"cgi": "c1", "cell_name": "A-dup", "station_name": "S1", "longitude": "113.1", "latitude": "22.5"},
{"cgi": "c2", "cell_name": "B", "station_name": "S2", "longitude": "0", "latitude": "0"},
{"cgi": "", "cell_name": "no key"},
]
coords = [
{"cgi": "c1", "longitude": "", "latitude": ""},
{"cgi": "c1", "longitude": "113.1", "latitude": "22.5"},
{"cgi": "c2", "longitude": "0", "latitude": "0"},
]
cells = build_cells(attrs, coords, "4G")
cells = build_cells(rows, "4G")
assert [(item["cgi"], item["cell_name"], item["station_name"], item["latitude"], item["longitude"]) for item in cells] == [
("c1", "A", "S1", 22.5, 113.1),
("c2", "B", "S2", None, None),
]
assert cells[0]["enodeb_id"] == "1" and cells[1]["network_type"] == ""
assert set(cells[0]) == {"cgi", "latitude", "longitude"} | set(gongcan.ATTRIBUTES["4G"])
rows = build_cells([{"ncgi": "", "cgi": "n1", "nrcell_name": "N", "gnodeb_id": "9"}], [{"ncgi": "n1", "longitude": "113", "latitude": "22"}], "5G")
assert rows == [{**rows[0], "ncgi": "n1", "nrcell_name": "N", "gnodeb_id": "9", "latitude": 22.0, "longitude": 113.0}]
assert "cgi" not in rows[0] and "enodeb_id" not in rows[0]
def test_key_overlap():
assert key_overlap([{"cgi": "a"}, {"cgi": "b"}, {"cgi": "c"}], [{"cgi": "a"}, {"cgi": "b"}, {"cgi": "d"}], "4G") == 0.5
assert key_overlap([], [{"cgi": "a"}], "4G") == 0.0
nr_rows = build_cells([{"ncgi": "", "cgi": "n1", "nrcell_name": "N", "gnodeb_id": "9", "longitude": "113", "latitude": "22"}], "5G")
assert nr_rows == [{**nr_rows[0], "ncgi": "n1", "nrcell_name": "N", "gnodeb_id": "9", "latitude": 22.0, "longitude": 113.0}]
assert "cgi" not in nr_rows[0] and "enodeb_id" not in nr_rows[0]
class SnapshotOpenCode(OpenCode):
@@ -163,40 +151,19 @@ PLATFORM_ROWS = {
}
def adhoc_returns(monkeypatch, result):
async def export_day(client, tablename, day, city, fields, **kwargs):
if isinstance(result, Exception):
raise result
return result["4G" if "lte" in tablename else "5G"]
monkeypatch.setattr(gongcan.adhoc, "export_day", export_day)
def test_snapshot_takes_attributes_from_adhoc_and_coordinates_from_opencode(monkeypatch):
adhoc_returns(monkeypatch, {"4G": [{"cgi": "c1", "station_name": "即席站"}], "5G": [{"ncgi": "n1", "station_name": "即席站"}]})
def test_snapshot_comes_from_one_opencode_export():
oc = SnapshotOpenCode(PLATFORM_ROWS)
cells, source = asyncio.run(fetch_snapshot(None, oc, CITY, date(2026, 11, 1)))
assert source == "adhoc" and oc.phases == ["xy"] and oc.cleaned == [snapshot_task_name(CITY, date(2026, 11, 1))]
assert [(row["cgi"], row["station_name"], row["latitude"]) for row in cells["4G"]] == [("c1", "即席站", 22.0)]
assert [(row["ncgi"], row["station_name"], row["latitude"]) for row in cells["5G"]] == [("n1", "即席站", 22.0)]
cells = asyncio.run(fetch_snapshot(oc, CITY, date(2026, 11, 1)))
assert oc.phases == ["gc"] and oc.cleaned == [snapshot_task_name(CITY, date(2026, 11, 1))]
assert [(row["cgi"], row["station_name"], row["latitude"]) for row in cells["4G"]] == [("c1", "OC站", 22.0)]
assert [(row["ncgi"], row["station_name"], row["latitude"]) for row in cells["5G"]] == [("n1", "OC站", 22.0)]
def test_snapshot_falls_back_to_opencode_attributes(monkeypatch):
adhoc_returns(monkeypatch, NqiError("即席查询没有返回行数"))
oc = SnapshotOpenCode(PLATFORM_ROWS)
cells, source = asyncio.run(fetch_snapshot(None, oc, CITY, date(2026, 11, 1)))
assert source == "opencode" and oc.phases == ["attr"] and cells["4G"][0]["station_name"] == "OC站"
adhoc_returns(monkeypatch, {"4G": [{"cgi": "other"}], "5G": [{"ncgi": "n1"}]})
mismatch = SnapshotOpenCode(PLATFORM_ROWS)
cells, source = asyncio.run(fetch_snapshot(None, mismatch, CITY, date(2026, 11, 1)))
assert source == "opencode" and mismatch.phases == ["xy", "attr"] and cells["4G"][0]["cgi"] == "c1"
def test_snapshot_rejects_empty_city(monkeypatch):
adhoc_returns(monkeypatch, NqiError("x"))
def test_snapshot_rejects_empty_city():
oc = SnapshotOpenCode({"4G": [], "5G": PLATFORM_ROWS["5G"]})
with pytest.raises(GongcanError):
asyncio.run(fetch_snapshot(None, SnapshotOpenCode({"4G": [], "5G": []}), CITY, date(2026, 11, 1)))
asyncio.run(fetch_snapshot(oc, CITY, date(2026, 11, 1)))
assert oc.cleaned == [snapshot_task_name(CITY, date(2026, 11, 1))]
def test_store_answers_presence_queries():
+17 -21
View File
@@ -1,33 +1,27 @@
# 评估工参的数据来源
退服评估要用拆除前、拆除后的 4G/5G 小区工参(含经纬度)。除工参外的其他数据(话务、流量等)都走即席查询,
不经过 OpenCode。工参按“地市 + 日期”整份存进本系统的 PostgreSQL,任务先查库,库里没有才去大数据平台取。
退服评估要用拆除前、拆除后的 4G/5G 小区工参(含经纬度)。工参由 OpenCode 导出;除工参外的其他数据(话务、流量等)都走即席查询。
工参按“地市 + 日期”整份存进本系统的 PostgreSQL,任务先查库,库里没有才去大数据平台取。
代码位置:
| 内容 | 文件 |
| --- | --- |
| OpenCode 接口、提示词、导出核对 | `backend/app/nqi/opencode.py` |
| 即席查询按天取指定列 | `backend/app/nqi/adhoc.py` 的 `export_day` |
| 快照合并、入库、日期规则、邻站 | `backend/app/collect/gongcan.py` |
| 表结构 | `backend/app/models.py` 的 `GongcanSnapshot`、`CellData4G`、`CellData5G`,迁移 `0007_gongcan_snapshot`、`0008_celldata_split` |
## 一份快照怎么来
1. 即席查询取当天全市工参(经纬度是脱敏的,不取):
- 4G `appdbv3.v_a_common_cfg_lte_cellant_d`,主键 `cgi`
- 5G `appdbv3.a_common_cfg_nr_cellant_d`,主键 `ncgi`
- 列:小区名、站点名 `station_name`、基站 ID/名称、`network_type`、`area`、`town`、`state`、`cover_type`、`frequency_band`、`vendor`、`azimuth`
2. OpenCode 在一个会话、一条提示词里导出全市当天有效的 CGI 和经纬度(4G/5G 各一个文件),
1. OpenCode 在一个会话、一条提示词里导出全市当天有效的 4G、5G 工参,各一个文件。
原表是 `appdbv3.a_common_cfg_lte_cellant_d` / `a_common_cfg_nr_cellant_d`,按 `eff_from_date <= 当天 < eff_to_date` 取。
3. 按 CGI 把经纬度合并回去。OpenCode 里没有的小区经纬度留空。坐标不在经度 70–140、纬度 15–55 之内的视为无效,也留空。
4. 自动校验:即席查询给的 CGI 集合和 OpenCode 当天快照的 CGI 集合重合度(交集/并集)低于 98%,
或者即席查询本身失败,就在同一个会话里让 OpenCode 把属性列一起导出,属性改用 OpenCode 的。
快照表的 `attr_source` 记录属性来自 `adhoc` 还是 `opencode`。
5. 4G 或 5G 任何一边是空的,整份快照算失败。
列:CGI(5G 是 `ncgi`)、经纬度、生效日期,以及小区名、`station_name`、基站 ID/名称、`network_type`、`area`、`town`、
`state`、`cover_type`、`frequency_band`、`vendor`、`azimuth`。
2. 4G 一行一个天线,按 CGI 合并:属性取第一行,坐标取第一条有效坐标。坐标不在经度 70–140、纬度 15–55 之内的视为无效,留空。
3. 4G 或 5G 任何一边是空的,整份快照算失败。快照表的 `attr_source` 固定为 `opencode`。
OpenCode 那份按生效日期严格截取,是日期口径的基准;即席查询的日期口径(视图上的 `starttime`)还没在页面上抓包确认过,
所以靠第 4 步兜底。
工参不走即席查询:即席查询的“4G小区工参”“5G小区工参”两张表没有日期列,4G 视图只有当前记录,
取不到历史日的完整工参(见下面“已知的坑”)。坐标本来就要走 OpenCode,属性放在同一条 SQL 里不增加 AI 调用。
### 实测(2026-11-01,江门)
@@ -37,8 +31,7 @@ OpenCode 那份按生效日期严格截取,是日期口径的基准;即席
| 5G | 23,814 | 2.4 MB | 23,811 | 每行 `cgi == ncgi` |
一条提示词 4 条导出命令约 138 秒、约 22 万输入 token;读文件每个 0.1–0.2 秒;清理约 10 秒。
一份快照的 OpenCode 开销约 2.5 分钟。属性改由 OpenCode 导出时不额外增加 AI 调用(同样一条提示词,只是 SQL 多几列)。
即席查询按每页 200 行要翻约 320 页,翻页之间停 0.3 秒。
生产上一份全市快照(4G、5G 带属性两个文件)约 75–80 秒。
## 存储与并发
@@ -133,9 +126,13 @@ python script/download-file-all-async.py --sql "select cgi, longitude, latitude,
- `getTableCount` 第一次总是带 `indexcount=0`。页面在结果为 0 行时会把时间放宽到表的粒度周期(周、月)再查一次,并带 `indexcount=1`。
补上后,抓包里的“重要场景-小区月粒度”表用我们自己拼的请求能正常计数(33,342 行,与页面一致)。
以前 `getTableCount` 出错会被当成 0 行静默返回,已改为报错。
- **4G/5G 小区工参表在即席查询里还取不到**:带上上面的参数后,计数返回 `{}`、取数返回 0 行且 `dbTime` 为 0,
说明服务端根本没执行查询,这两张表还要别的参数。现有抓包里没有查这两张表的请求,需要在页面上查一次并抓包对照。
在此之前快照自动改用 OpenCode 的属性。
- **即席查询的工参表没有日期列**(抓包 `Temp/nqi-celldata.chlz`):4G `appdbv3.v_a_common_cfg_lte_cellant_d`、
5G `appdbv3.a_common_cfg_nr_cellant_d` 的配置写着 `time_field = starttime`,表里却没有这一列。页面只带地市条件;
带了 `starttime` 条件服务端不执行(计数返回 `{}`)。程序里表没有 time_field 列时不加时间条件。
- 可以加自定义字段条件,如 `curr_flag = 1`、`eff_from_date <= …`、`eff_to_date > …`,会原样拼进 SQL。
- 4G 视图只有当前记录:江门全量 40,341 行,按生效日期取 10-01 只有 28,614 行(OpenCode 原表当天 38,312 个 CGI)。
- 5G 表有历史版本,加 `curr_flag = 1` 是 23,801 行,与 OpenCode 的 11-10 快照一致。
- 经纬度返回 `***`;每页可取 5,000 行,约 4.5 秒一页。
## 迁移模板工具时的字段对照
@@ -155,4 +152,3 @@ python script/download-file-all-async.py --sql "select cgi, longitude, latitude,
- OpenCode 弹出权限确认(`permission`)或提问(`question`)时的处理。
- 会话异常后换新会话重试。
- 即席查询恢复后,它的 CGI 与 OpenCode 快照的实际重合度,98% 的阈值要按实测调整。